*/}}

miniaudio.h 3.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379
  1. /*
  2. Audio playback and capture library. Choice of public domain or MIT-0. See license statements at the end of this file.
  3. miniaudio - v0.11.15 - 2023-04-30
  4. David Reid - mackron@gmail.com
  5. Website: https://miniaud.io
  6. Documentation: https://miniaud.io/docs
  7. GitHub: https://github.com/mackron/miniaudio
  8. */
  9. /*
  10. 1. Introduction
  11. ===============
  12. miniaudio is a single file library for audio playback and capture. To use it, do the following in
  13. one .c file:
  14. ```c
  15. #define MINIAUDIO_IMPLEMENTATION
  16. #include "miniaudio.h"
  17. ```
  18. You can do `#include "miniaudio.h"` in other parts of the program just like any other header.
  19. miniaudio includes both low level and high level APIs. The low level API is good for those who want
  20. to do all of their mixing themselves and only require a light weight interface to the underlying
  21. audio device. The high level API is good for those who have complex mixing and effect requirements.
  22. In miniaudio, objects are transparent structures. Unlike many other libraries, there are no handles
  23. to opaque objects which means you need to allocate memory for objects yourself. In the examples
  24. presented in this documentation you will often see objects declared on the stack. You need to be
  25. careful when translating these examples to your own code so that you don't accidentally declare
  26. your objects on the stack and then cause them to become invalid once the function returns. In
  27. addition, you must ensure the memory address of your objects remain the same throughout their
  28. lifetime. You therefore cannot be making copies of your objects.
  29. A config/init pattern is used throughout the entire library. The idea is that you set up a config
  30. object and pass that into the initialization routine. The advantage to this system is that the
  31. config object can be initialized with logical defaults and new properties added to it without
  32. breaking the API. The config object can be allocated on the stack and does not need to be
  33. maintained after initialization of the corresponding object.
  34. 1.1. Low Level API
  35. ------------------
  36. The low level API gives you access to the raw audio data of an audio device. It supports playback,
  37. capture, full-duplex and loopback (WASAPI only). You can enumerate over devices to determine which
  38. physical device(s) you want to connect to.
  39. The low level API uses the concept of a "device" as the abstraction for physical devices. The idea
  40. is that you choose a physical device to emit or capture audio from, and then move data to/from the
  41. device when miniaudio tells you to. Data is delivered to and from devices asynchronously via a
  42. callback which you specify when initializing the device.
  43. When initializing the device you first need to configure it. The device configuration allows you to
  44. specify things like the format of the data delivered via the callback, the size of the internal
  45. buffer and the ID of the device you want to emit or capture audio from.
  46. Once you have the device configuration set up you can initialize the device. When initializing a
  47. device you need to allocate memory for the device object beforehand. This gives the application
  48. complete control over how the memory is allocated. In the example below we initialize a playback
  49. device on the stack, but you could allocate it on the heap if that suits your situation better.
  50. ```c
  51. void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
  52. {
  53. // In playback mode copy data to pOutput. In capture mode read data from pInput. In full-duplex mode, both
  54. // pOutput and pInput will be valid and you can move data from pInput into pOutput. Never process more than
  55. // frameCount frames.
  56. }
  57. int main()
  58. {
  59. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  60. config.playback.format = ma_format_f32; // Set to ma_format_unknown to use the device's native format.
  61. config.playback.channels = 2; // Set to 0 to use the device's native channel count.
  62. config.sampleRate = 48000; // Set to 0 to use the device's native sample rate.
  63. config.dataCallback = data_callback; // This function will be called when miniaudio needs more data.
  64. config.pUserData = pMyCustomData; // Can be accessed from the device object (device.pUserData).
  65. ma_device device;
  66. if (ma_device_init(NULL, &config, &device) != MA_SUCCESS) {
  67. return -1; // Failed to initialize the device.
  68. }
  69. ma_device_start(&device); // The device is sleeping by default so you'll need to start it manually.
  70. // Do something here. Probably your program's main loop.
  71. ma_device_uninit(&device); // This will stop the device so no need to do that manually.
  72. return 0;
  73. }
  74. ```
  75. In the example above, `data_callback()` is where audio data is written and read from the device.
  76. The idea is in playback mode you cause sound to be emitted from the speakers by writing audio data
  77. to the output buffer (`pOutput` in the example). In capture mode you read data from the input
  78. buffer (`pInput`) to extract sound captured by the microphone. The `frameCount` parameter tells you
  79. how many frames can be written to the output buffer and read from the input buffer. A "frame" is
  80. one sample for each channel. For example, in a stereo stream (2 channels), one frame is 2
  81. samples: one for the left, one for the right. The channel count is defined by the device config.
  82. The size in bytes of an individual sample is defined by the sample format which is also specified
  83. in the device config. Multi-channel audio data is always interleaved, which means the samples for
  84. each frame are stored next to each other in memory. For example, in a stereo stream the first pair
  85. of samples will be the left and right samples for the first frame, the second pair of samples will
  86. be the left and right samples for the second frame, etc.
  87. The configuration of the device is defined by the `ma_device_config` structure. The config object
  88. is always initialized with `ma_device_config_init()`. It's important to always initialize the
  89. config with this function as it initializes it with logical defaults and ensures your program
  90. doesn't break when new members are added to the `ma_device_config` structure. The example above
  91. uses a fairly simple and standard device configuration. The call to `ma_device_config_init()` takes
  92. a single parameter, which is whether or not the device is a playback, capture, duplex or loopback
  93. device (loopback devices are not supported on all backends). The `config.playback.format` member
  94. sets the sample format which can be one of the following (all formats are native-endian):
  95. +---------------+----------------------------------------+---------------------------+
  96. | Symbol | Description | Range |
  97. +---------------+----------------------------------------+---------------------------+
  98. | ma_format_f32 | 32-bit floating point | [-1, 1] |
  99. | ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
  100. | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
  101. | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
  102. | ma_format_u8 | 8-bit unsigned integer | [0, 255] |
  103. +---------------+----------------------------------------+---------------------------+
  104. The `config.playback.channels` member sets the number of channels to use with the device. The
  105. channel count cannot exceed MA_MAX_CHANNELS. The `config.sampleRate` member sets the sample rate
  106. (which must be the same for both playback and capture in full-duplex configurations). This is
  107. usually set to 44100 or 48000, but can be set to anything. It's recommended to keep this between
  108. 8000 and 384000, however.
  109. Note that leaving the format, channel count and/or sample rate at their default values will result
  110. in the internal device's native configuration being used which is useful if you want to avoid the
  111. overhead of miniaudio's automatic data conversion.
  112. In addition to the sample format, channel count and sample rate, the data callback and user data
  113. pointer are also set via the config. The user data pointer is not passed into the callback as a
  114. parameter, but is instead set to the `pUserData` member of `ma_device` which you can access
  115. directly since all miniaudio structures are transparent.
  116. Initializing the device is done with `ma_device_init()`. This will return a result code telling you
  117. what went wrong, if anything. On success it will return `MA_SUCCESS`. After initialization is
  118. complete the device will be in a stopped state. To start it, use `ma_device_start()`.
  119. Uninitializing the device will stop it, which is what the example above does, but you can also stop
  120. the device with `ma_device_stop()`. To resume the device simply call `ma_device_start()` again.
  121. Note that it's important to never stop or start the device from inside the callback. This will
  122. result in a deadlock. Instead you set a variable or signal an event indicating that the device
  123. needs to stop and handle it in a different thread. The following APIs must never be called inside
  124. the callback:
  125. ```c
  126. ma_device_init()
  127. ma_device_init_ex()
  128. ma_device_uninit()
  129. ma_device_start()
  130. ma_device_stop()
  131. ```
  132. You must never try uninitializing and reinitializing a device inside the callback. You must also
  133. never try to stop and start it from inside the callback. There are a few other things you shouldn't
  134. do in the callback depending on your requirements, however this isn't so much a thread-safety
  135. thing, but rather a real-time processing thing which is beyond the scope of this introduction.
  136. The example above demonstrates the initialization of a playback device, but it works exactly the
  137. same for capture. All you need to do is change the device type from `ma_device_type_playback` to
  138. `ma_device_type_capture` when setting up the config, like so:
  139. ```c
  140. ma_device_config config = ma_device_config_init(ma_device_type_capture);
  141. config.capture.format = MY_FORMAT;
  142. config.capture.channels = MY_CHANNEL_COUNT;
  143. ```
  144. In the data callback you just read from the input buffer (`pInput` in the example above) and leave
  145. the output buffer alone (it will be set to NULL when the device type is set to
  146. `ma_device_type_capture`).
  147. These are the available device types and how you should handle the buffers in the callback:
  148. +-------------------------+--------------------------------------------------------+
  149. | Device Type | Callback Behavior |
  150. +-------------------------+--------------------------------------------------------+
  151. | ma_device_type_playback | Write to output buffer, leave input buffer untouched. |
  152. | ma_device_type_capture | Read from input buffer, leave output buffer untouched. |
  153. | ma_device_type_duplex | Read from input buffer, write to output buffer. |
  154. | ma_device_type_loopback | Read from input buffer, leave output buffer untouched. |
  155. +-------------------------+--------------------------------------------------------+
  156. You will notice in the example above that the sample format and channel count is specified
  157. separately for playback and capture. This is to support different data formats between the playback
  158. and capture devices in a full-duplex system. An example may be that you want to capture audio data
  159. as a monaural stream (one channel), but output sound to a stereo speaker system. Note that if you
  160. use different formats between playback and capture in a full-duplex configuration you will need to
  161. convert the data yourself. There are functions available to help you do this which will be
  162. explained later.
  163. The example above did not specify a physical device to connect to which means it will use the
  164. operating system's default device. If you have multiple physical devices connected and you want to
  165. use a specific one you will need to specify the device ID in the configuration, like so:
  166. ```c
  167. config.playback.pDeviceID = pMyPlaybackDeviceID; // Only if requesting a playback or duplex device.
  168. config.capture.pDeviceID = pMyCaptureDeviceID; // Only if requesting a capture, duplex or loopback device.
  169. ```
  170. To retrieve the device ID you will need to perform device enumeration, however this requires the
  171. use of a new concept called the "context". Conceptually speaking the context sits above the device.
  172. There is one context to many devices. The purpose of the context is to represent the backend at a
  173. more global level and to perform operations outside the scope of an individual device. Mainly it is
  174. used for performing run-time linking against backend libraries, initializing backends and
  175. enumerating devices. The example below shows how to enumerate devices.
  176. ```c
  177. ma_context context;
  178. if (ma_context_init(NULL, 0, NULL, &context) != MA_SUCCESS) {
  179. // Error.
  180. }
  181. ma_device_info* pPlaybackInfos;
  182. ma_uint32 playbackCount;
  183. ma_device_info* pCaptureInfos;
  184. ma_uint32 captureCount;
  185. if (ma_context_get_devices(&context, &pPlaybackInfos, &playbackCount, &pCaptureInfos, &captureCount) != MA_SUCCESS) {
  186. // Error.
  187. }
  188. // Loop over each device info and do something with it. Here we just print the name with their index. You may want
  189. // to give the user the opportunity to choose which device they'd prefer.
  190. for (ma_uint32 iDevice = 0; iDevice < playbackCount; iDevice += 1) {
  191. printf("%d - %s\n", iDevice, pPlaybackInfos[iDevice].name);
  192. }
  193. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  194. config.playback.pDeviceID = &pPlaybackInfos[chosenPlaybackDeviceIndex].id;
  195. config.playback.format = MY_FORMAT;
  196. config.playback.channels = MY_CHANNEL_COUNT;
  197. config.sampleRate = MY_SAMPLE_RATE;
  198. config.dataCallback = data_callback;
  199. config.pUserData = pMyCustomData;
  200. ma_device device;
  201. if (ma_device_init(&context, &config, &device) != MA_SUCCESS) {
  202. // Error
  203. }
  204. ...
  205. ma_device_uninit(&device);
  206. ma_context_uninit(&context);
  207. ```
  208. The first thing we do in this example is initialize a `ma_context` object with `ma_context_init()`.
  209. The first parameter is a pointer to a list of `ma_backend` values which are used to override the
  210. default backend priorities. When this is NULL, as in this example, miniaudio's default priorities
  211. are used. The second parameter is the number of backends listed in the array pointed to by the
  212. first parameter. The third parameter is a pointer to a `ma_context_config` object which can be
  213. NULL, in which case defaults are used. The context configuration is used for setting the logging
  214. callback, custom memory allocation callbacks, user-defined data and some backend-specific
  215. configurations.
  216. Once the context has been initialized you can enumerate devices. In the example above we use the
  217. simpler `ma_context_get_devices()`, however you can also use a callback for handling devices by
  218. using `ma_context_enumerate_devices()`. When using `ma_context_get_devices()` you provide a pointer
  219. to a pointer that will, upon output, be set to a pointer to a buffer containing a list of
  220. `ma_device_info` structures. You also provide a pointer to an unsigned integer that will receive
  221. the number of items in the returned buffer. Do not free the returned buffers as their memory is
  222. managed internally by miniaudio.
  223. The `ma_device_info` structure contains an `id` member which is the ID you pass to the device
  224. config. It also contains the name of the device which is useful for presenting a list of devices
  225. to the user via the UI.
  226. When creating your own context you will want to pass it to `ma_device_init()` when initializing the
  227. device. Passing in NULL, like we do in the first example, will result in miniaudio creating the
  228. context for you, which you don't want to do since you've already created a context. Note that
  229. internally the context is only tracked by it's pointer which means you must not change the location
  230. of the `ma_context` object. If this is an issue, consider using `malloc()` to allocate memory for
  231. the context.
  232. 1.2. High Level API
  233. -------------------
  234. The high level API consists of three main parts:
  235. * Resource management for loading and streaming sounds.
  236. * A node graph for advanced mixing and effect processing.
  237. * A high level "engine" that wraps around the resource manager and node graph.
  238. The resource manager (`ma_resource_manager`) is used for loading sounds. It supports loading sounds
  239. fully into memory and also streaming. It will also deal with reference counting for you which
  240. avoids the same sound being loaded multiple times.
  241. The node graph is used for mixing and effect processing. The idea is that you connect a number of
  242. nodes into the graph by connecting each node's outputs to another node's inputs. Each node can
  243. implement it's own effect. By chaining nodes together, advanced mixing and effect processing can
  244. be achieved.
  245. The engine encapsulates both the resource manager and the node graph to create a simple, easy to
  246. use high level API. The resource manager and node graph APIs are covered in more later sections of
  247. this manual.
  248. The code below shows how you can initialize an engine using it's default configuration.
  249. ```c
  250. ma_result result;
  251. ma_engine engine;
  252. result = ma_engine_init(NULL, &engine);
  253. if (result != MA_SUCCESS) {
  254. return result; // Failed to initialize the engine.
  255. }
  256. ```
  257. This creates an engine instance which will initialize a device internally which you can access with
  258. `ma_engine_get_device()`. It will also initialize a resource manager for you which can be accessed
  259. with `ma_engine_get_resource_manager()`. The engine itself is a node graph (`ma_node_graph`) which
  260. means you can pass a pointer to the engine object into any of the `ma_node_graph` APIs (with a
  261. cast). Alternatively, you can use `ma_engine_get_node_graph()` instead of a cast.
  262. Note that all objects in miniaudio, including the `ma_engine` object in the example above, are
  263. transparent structures. There are no handles to opaque structures in miniaudio which means you need
  264. to be mindful of how you declare them. In the example above we are declaring it on the stack, but
  265. this will result in the struct being invalidated once the function encapsulating it returns. If
  266. allocating the engine on the heap is more appropriate, you can easily do so with a standard call
  267. to `malloc()` or whatever heap allocation routine you like:
  268. ```c
  269. ma_engine* pEngine = malloc(sizeof(*pEngine));
  270. ```
  271. The `ma_engine` API uses the same config/init pattern used all throughout miniaudio. To configure
  272. an engine, you can fill out a `ma_engine_config` object and pass it into the first parameter of
  273. `ma_engine_init()`:
  274. ```c
  275. ma_result result;
  276. ma_engine engine;
  277. ma_engine_config engineConfig;
  278. engineConfig = ma_engine_config_init();
  279. engineConfig.pResourceManager = &myCustomResourceManager; // <-- Initialized as some earlier stage.
  280. result = ma_engine_init(&engineConfig, &engine);
  281. if (result != MA_SUCCESS) {
  282. return result;
  283. }
  284. ```
  285. This creates an engine instance using a custom config. In this particular example it's showing how
  286. you can specify a custom resource manager rather than having the engine initialize one internally.
  287. This is particularly useful if you want to have multiple engine's share the same resource manager.
  288. The engine must be uninitialized with `ma_engine_uninit()` when it's no longer needed.
  289. By default the engine will be started, but nothing will be playing because no sounds have been
  290. initialized. The easiest but least flexible way of playing a sound is like so:
  291. ```c
  292. ma_engine_play_sound(&engine, "my_sound.wav", NULL);
  293. ```
  294. This plays what miniaudio calls an "inline" sound. It plays the sound once, and then puts the
  295. internal sound up for recycling. The last parameter is used to specify which sound group the sound
  296. should be associated with which will be explained later. This particular way of playing a sound is
  297. simple, but lacks flexibility and features. A more flexible way of playing a sound is to first
  298. initialize a sound:
  299. ```c
  300. ma_result result;
  301. ma_sound sound;
  302. result = ma_sound_init_from_file(&engine, "my_sound.wav", 0, NULL, NULL, &sound);
  303. if (result != MA_SUCCESS) {
  304. return result;
  305. }
  306. ma_sound_start(&sound);
  307. ```
  308. This returns a `ma_sound` object which represents a single instance of the specified sound file. If
  309. you want to play the same file multiple times simultaneously, you need to create one sound for each
  310. instance.
  311. Sounds should be uninitialized with `ma_sound_uninit()`.
  312. Sounds are not started by default. Start a sound with `ma_sound_start()` and stop it with
  313. `ma_sound_stop()`. When a sound is stopped, it is not rewound to the start. Use
  314. `ma_sound_seek_to_pcm_frame(&sound, 0)` to seek back to the start of a sound. By default, starting
  315. and stopping sounds happens immediately, but sometimes it might be convenient to schedule the sound
  316. the be started and/or stopped at a specific time. This can be done with the following functions:
  317. ```c
  318. ma_sound_set_start_time_in_pcm_frames()
  319. ma_sound_set_start_time_in_milliseconds()
  320. ma_sound_set_stop_time_in_pcm_frames()
  321. ma_sound_set_stop_time_in_milliseconds()
  322. ```
  323. The start/stop time needs to be specified based on the absolute timer which is controlled by the
  324. engine. The current global time time in PCM frames can be retrieved with
  325. `ma_engine_get_time_in_pcm_frames()`. The engine's global time can be changed with
  326. `ma_engine_set_time_in_pcm_frames()` for synchronization purposes if required. Note that scheduling
  327. a start time still requires an explicit call to `ma_sound_start()` before anything will play:
  328. ```c
  329. ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 2);
  330. ma_sound_start(&sound);
  331. ```
  332. The third parameter of `ma_sound_init_from_file()` is a set of flags that control how the sound be
  333. loaded and a few options on which features should be enabled for that sound. By default, the sound
  334. is synchronously loaded fully into memory straight from the file system without any kind of
  335. decoding. If you want to decode the sound before storing it in memory, you need to specify the
  336. `MA_SOUND_FLAG_DECODE` flag. This is useful if you want to incur the cost of decoding at an earlier
  337. stage, such as a loading stage. Without this option, decoding will happen dynamically at mixing
  338. time which might be too expensive on the audio thread.
  339. If you want to load the sound asynchronously, you can specify the `MA_SOUND_FLAG_ASYNC` flag. This
  340. will result in `ma_sound_init_from_file()` returning quickly, but the sound will not start playing
  341. until the sound has had some audio decoded.
  342. The fourth parameter is a pointer to sound group. A sound group is used as a mechanism to organise
  343. sounds into groups which have their own effect processing and volume control. An example is a game
  344. which might have separate groups for sfx, voice and music. Each of these groups have their own
  345. independent volume control. Use `ma_sound_group_init()` or `ma_sound_group_init_ex()` to initialize
  346. a sound group.
  347. Sounds and sound groups are nodes in the engine's node graph and can be plugged into any `ma_node`
  348. API. This makes it possible to connect sounds and sound groups to effect nodes to produce complex
  349. effect chains.
  350. A sound can have it's volume changed with `ma_sound_set_volume()`. If you prefer decibel volume
  351. control you can use `ma_volume_db_to_linear()` to convert from decibel representation to linear.
  352. Panning and pitching is supported with `ma_sound_set_pan()` and `ma_sound_set_pitch()`. If you know
  353. a sound will never have it's pitch changed with `ma_sound_set_pitch()` or via the doppler effect,
  354. you can specify the `MA_SOUND_FLAG_NO_PITCH` flag when initializing the sound for an optimization.
  355. By default, sounds and sound groups have spatialization enabled. If you don't ever want to
  356. spatialize your sounds, initialize the sound with the `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. The
  357. spatialization model is fairly simple and is roughly on feature parity with OpenAL. HRTF and
  358. environmental occlusion are not currently supported, but planned for the future. The supported
  359. features include:
  360. * Sound and listener positioning and orientation with cones
  361. * Attenuation models: none, inverse, linear and exponential
  362. * Doppler effect
  363. Sounds can be faded in and out with `ma_sound_set_fade_in_pcm_frames()`.
  364. To check if a sound is currently playing, you can use `ma_sound_is_playing()`. To check if a sound
  365. is at the end, use `ma_sound_at_end()`. Looping of a sound can be controlled with
  366. `ma_sound_set_looping()`. Use `ma_sound_is_looping()` to check whether or not the sound is looping.
  367. 2. Building
  368. ===========
  369. miniaudio should work cleanly out of the box without the need to download or install any
  370. dependencies. See below for platform-specific details.
  371. Note that GCC and Clang require `-msse2`, `-mavx2`, etc. for SIMD optimizations.
  372. If you get errors about undefined references to `__sync_val_compare_and_swap_8`, `__atomic_load_8`,
  373. etc. you need to link with `-latomic`.
  374. 2.1. Windows
  375. ------------
  376. The Windows build should compile cleanly on all popular compilers without the need to configure any
  377. include paths nor link to any libraries.
  378. The UWP build may require linking to mmdevapi.lib if you get errors about an unresolved external
  379. symbol for `ActivateAudioInterfaceAsync()`.
  380. 2.2. macOS and iOS
  381. ------------------
  382. The macOS build should compile cleanly without the need to download any dependencies nor link to
  383. any libraries or frameworks. The iOS build needs to be compiled as Objective-C and will need to
  384. link the relevant frameworks but should compile cleanly out of the box with Xcode. Compiling
  385. through the command line requires linking to `-lpthread` and `-lm`.
  386. Due to the way miniaudio links to frameworks at runtime, your application may not pass Apple's
  387. notarization process. To fix this there are two options. The first is to use the
  388. `MA_NO_RUNTIME_LINKING` option, like so:
  389. ```c
  390. #ifdef __APPLE__
  391. #define MA_NO_RUNTIME_LINKING
  392. #endif
  393. #define MINIAUDIO_IMPLEMENTATION
  394. #include "miniaudio.h"
  395. ```
  396. This will require linking with `-framework CoreFoundation -framework CoreAudio -framework AudioToolbox`.
  397. If you get errors about AudioToolbox, try with `-framework AudioUnit` instead. You may get this when
  398. using older versions of iOS. Alternatively, if you would rather keep using runtime linking you can
  399. add the following to your entitlements.xcent file:
  400. ```
  401. <key>com.apple.security.cs.allow-dyld-environment-variables</key>
  402. <true/>
  403. <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
  404. <true/>
  405. ```
  406. See this discussion for more info: https://github.com/mackron/miniaudio/issues/203.
  407. 2.3. Linux
  408. ----------
  409. The Linux build only requires linking to `-ldl`, `-lpthread` and `-lm`. You do not need any
  410. development packages. You may need to link with `-latomic` if you're compiling for 32-bit ARM.
  411. 2.4. BSD
  412. --------
  413. The BSD build only requires linking to `-lpthread` and `-lm`. NetBSD uses audio(4), OpenBSD uses
  414. sndio and FreeBSD uses OSS. You may need to link with `-latomic` if you're compiling for 32-bit
  415. ARM.
  416. 2.5. Android
  417. ------------
  418. AAudio is the highest priority backend on Android. This should work out of the box without needing
  419. any kind of compiler configuration. Support for AAudio starts with Android 8 which means older
  420. versions will fall back to OpenSL|ES which requires API level 16+.
  421. There have been reports that the OpenSL|ES backend fails to initialize on some Android based
  422. devices due to `dlopen()` failing to open "libOpenSLES.so". If this happens on your platform
  423. you'll need to disable run-time linking with `MA_NO_RUNTIME_LINKING` and link with -lOpenSLES.
  424. 2.6. Emscripten
  425. ---------------
  426. The Emscripten build emits Web Audio JavaScript directly and should compile cleanly out of the box.
  427. You cannot use `-std=c*` compiler flags, nor `-ansi`.
  428. 2.7. Build Options
  429. ------------------
  430. `#define` these options before including miniaudio.h.
  431. +----------------------------------+--------------------------------------------------------------------+
  432. | Option | Description |
  433. +----------------------------------+--------------------------------------------------------------------+
  434. | MA_NO_WASAPI | Disables the WASAPI backend. |
  435. +----------------------------------+--------------------------------------------------------------------+
  436. | MA_NO_DSOUND | Disables the DirectSound backend. |
  437. +----------------------------------+--------------------------------------------------------------------+
  438. | MA_NO_WINMM | Disables the WinMM backend. |
  439. +----------------------------------+--------------------------------------------------------------------+
  440. | MA_NO_ALSA | Disables the ALSA backend. |
  441. +----------------------------------+--------------------------------------------------------------------+
  442. | MA_NO_PULSEAUDIO | Disables the PulseAudio backend. |
  443. +----------------------------------+--------------------------------------------------------------------+
  444. | MA_NO_JACK | Disables the JACK backend. |
  445. +----------------------------------+--------------------------------------------------------------------+
  446. | MA_NO_COREAUDIO | Disables the Core Audio backend. |
  447. +----------------------------------+--------------------------------------------------------------------+
  448. | MA_NO_SNDIO | Disables the sndio backend. |
  449. +----------------------------------+--------------------------------------------------------------------+
  450. | MA_NO_AUDIO4 | Disables the audio(4) backend. |
  451. +----------------------------------+--------------------------------------------------------------------+
  452. | MA_NO_OSS | Disables the OSS backend. |
  453. +----------------------------------+--------------------------------------------------------------------+
  454. | MA_NO_AAUDIO | Disables the AAudio backend. |
  455. +----------------------------------+--------------------------------------------------------------------+
  456. | MA_NO_OPENSL | Disables the OpenSL|ES backend. |
  457. +----------------------------------+--------------------------------------------------------------------+
  458. | MA_NO_WEBAUDIO | Disables the Web Audio backend. |
  459. +----------------------------------+--------------------------------------------------------------------+
  460. | MA_NO_NULL | Disables the null backend. |
  461. +----------------------------------+--------------------------------------------------------------------+
  462. | MA_ENABLE_ONLY_SPECIFIC_BACKENDS | Disables all backends by default and requires `MA_ENABLE_*` to |
  463. | | enable specific backends. |
  464. +----------------------------------+--------------------------------------------------------------------+
  465. | MA_ENABLE_WASAPI | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  466. | | enable the WASAPI backend. |
  467. +----------------------------------+--------------------------------------------------------------------+
  468. | MA_ENABLE_DSOUND | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  469. | | enable the DirectSound backend. |
  470. +----------------------------------+--------------------------------------------------------------------+
  471. | MA_ENABLE_WINMM | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  472. | | enable the WinMM backend. |
  473. +----------------------------------+--------------------------------------------------------------------+
  474. | MA_ENABLE_ALSA | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  475. | | enable the ALSA backend. |
  476. +----------------------------------+--------------------------------------------------------------------+
  477. | MA_ENABLE_PULSEAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  478. | | enable the PulseAudio backend. |
  479. +----------------------------------+--------------------------------------------------------------------+
  480. | MA_ENABLE_JACK | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  481. | | enable the JACK backend. |
  482. +----------------------------------+--------------------------------------------------------------------+
  483. | MA_ENABLE_COREAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  484. | | enable the Core Audio backend. |
  485. +----------------------------------+--------------------------------------------------------------------+
  486. | MA_ENABLE_SNDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  487. | | enable the sndio backend. |
  488. +----------------------------------+--------------------------------------------------------------------+
  489. | MA_ENABLE_AUDIO4 | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  490. | | enable the audio(4) backend. |
  491. +----------------------------------+--------------------------------------------------------------------+
  492. | MA_ENABLE_OSS | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  493. | | enable the OSS backend. |
  494. +----------------------------------+--------------------------------------------------------------------+
  495. | MA_ENABLE_AAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  496. | | enable the AAudio backend. |
  497. +----------------------------------+--------------------------------------------------------------------+
  498. | MA_ENABLE_OPENSL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  499. | | enable the OpenSL|ES backend. |
  500. +----------------------------------+--------------------------------------------------------------------+
  501. | MA_ENABLE_WEBAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  502. | | enable the Web Audio backend. |
  503. +----------------------------------+--------------------------------------------------------------------+
  504. | MA_ENABLE_NULL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  505. | | enable the null backend. |
  506. +----------------------------------+--------------------------------------------------------------------+
  507. | MA_NO_DECODING | Disables decoding APIs. |
  508. +----------------------------------+--------------------------------------------------------------------+
  509. | MA_NO_ENCODING | Disables encoding APIs. |
  510. +----------------------------------+--------------------------------------------------------------------+
  511. | MA_NO_WAV | Disables the built-in WAV decoder and encoder. |
  512. +----------------------------------+--------------------------------------------------------------------+
  513. | MA_NO_FLAC | Disables the built-in FLAC decoder. |
  514. +----------------------------------+--------------------------------------------------------------------+
  515. | MA_NO_MP3 | Disables the built-in MP3 decoder. |
  516. +----------------------------------+--------------------------------------------------------------------+
  517. | MA_NO_DEVICE_IO | Disables playback and recording. This will disable `ma_context` |
  518. | | and `ma_device` APIs. This is useful if you only want to use |
  519. | | miniaudio's data conversion and/or decoding APIs. |
  520. +----------------------------------+--------------------------------------------------------------------+
  521. | MA_NO_RESOURCE_MANAGER | Disables the resource manager. When using the engine this will |
  522. | | also disable the following functions: |
  523. | | |
  524. | | ``` |
  525. | | ma_sound_init_from_file() |
  526. | | ma_sound_init_from_file_w() |
  527. | | ma_sound_init_copy() |
  528. | | ma_engine_play_sound_ex() |
  529. | | ma_engine_play_sound() |
  530. | | ``` |
  531. | | |
  532. | | The only way to initialize a `ma_sound` object is to initialize it |
  533. | | from a data source. |
  534. +----------------------------------+--------------------------------------------------------------------+
  535. | MA_NO_NODE_GRAPH | Disables the node graph API. This will also disable the engine API |
  536. | | because it depends on the node graph. |
  537. +----------------------------------+--------------------------------------------------------------------+
  538. | MA_NO_ENGINE | Disables the engine API. |
  539. +----------------------------------+--------------------------------------------------------------------+
  540. | MA_NO_THREADING | Disables the `ma_thread`, `ma_mutex`, `ma_semaphore` and |
  541. | | `ma_event` APIs. This option is useful if you only need to use |
  542. | | miniaudio for data conversion, decoding and/or encoding. Some |
  543. | | families of APIs require threading which means the following |
  544. | | options must also be set: |
  545. | | |
  546. | | ``` |
  547. | | MA_NO_DEVICE_IO |
  548. | | ``` |
  549. +----------------------------------+--------------------------------------------------------------------+
  550. | MA_NO_GENERATION | Disables generation APIs such a `ma_waveform` and `ma_noise`. |
  551. +----------------------------------+--------------------------------------------------------------------+
  552. | MA_NO_SSE2 | Disables SSE2 optimizations. |
  553. +----------------------------------+--------------------------------------------------------------------+
  554. | MA_NO_AVX2 | Disables AVX2 optimizations. |
  555. +----------------------------------+--------------------------------------------------------------------+
  556. | MA_NO_NEON | Disables NEON optimizations. |
  557. +----------------------------------+--------------------------------------------------------------------+
  558. | MA_NO_RUNTIME_LINKING | Disables runtime linking. This is useful for passing Apple's |
  559. | | notarization process. When enabling this, you may need to avoid |
  560. | | using `-std=c89` or `-std=c99` on Linux builds or else you may end |
  561. | | up with compilation errors due to conflicts with `timespec` and |
  562. | | `timeval` data types. |
  563. | | |
  564. | | You may need to enable this if your target platform does not allow |
  565. | | runtime linking via `dlopen()`. |
  566. +----------------------------------+--------------------------------------------------------------------+
  567. | MA_DEBUG_OUTPUT | Enable `printf()` output of debug logs (`MA_LOG_LEVEL_DEBUG`). |
  568. +----------------------------------+--------------------------------------------------------------------+
  569. | MA_COINIT_VALUE | Windows only. The value to pass to internal calls to |
  570. | | `CoInitializeEx()`. Defaults to `COINIT_MULTITHREADED`. |
  571. +----------------------------------+--------------------------------------------------------------------+
  572. | MA_API | Controls how public APIs should be decorated. Default is `extern`. |
  573. +----------------------------------+--------------------------------------------------------------------+
  574. 3. Definitions
  575. ==============
  576. This section defines common terms used throughout miniaudio. Unfortunately there is often ambiguity
  577. in the use of terms throughout the audio space, so this section is intended to clarify how miniaudio
  578. uses each term.
  579. 3.1. Sample
  580. -----------
  581. A sample is a single unit of audio data. If the sample format is f32, then one sample is one 32-bit
  582. floating point number.
  583. 3.2. Frame / PCM Frame
  584. ----------------------
  585. A frame is a group of samples equal to the number of channels. For a stereo stream a frame is 2
  586. samples, a mono frame is 1 sample, a 5.1 surround sound frame is 6 samples, etc. The terms "frame"
  587. and "PCM frame" are the same thing in miniaudio. Note that this is different to a compressed frame.
  588. If ever miniaudio needs to refer to a compressed frame, such as a FLAC frame, it will always
  589. clarify what it's referring to with something like "FLAC frame".
  590. 3.3. Channel
  591. ------------
  592. A stream of monaural audio that is emitted from an individual speaker in a speaker system, or
  593. received from an individual microphone in a microphone system. A stereo stream has two channels (a
  594. left channel, and a right channel), a 5.1 surround sound system has 6 channels, etc. Some audio
  595. systems refer to a channel as a complex audio stream that's mixed with other channels to produce
  596. the final mix - this is completely different to miniaudio's use of the term "channel" and should
  597. not be confused.
  598. 3.4. Sample Rate
  599. ----------------
  600. The sample rate in miniaudio is always expressed in Hz, such as 44100, 48000, etc. It's the number
  601. of PCM frames that are processed per second.
  602. 3.5. Formats
  603. ------------
  604. Throughout miniaudio you will see references to different sample formats:
  605. +---------------+----------------------------------------+---------------------------+
  606. | Symbol | Description | Range |
  607. +---------------+----------------------------------------+---------------------------+
  608. | ma_format_f32 | 32-bit floating point | [-1, 1] |
  609. | ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
  610. | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
  611. | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
  612. | ma_format_u8 | 8-bit unsigned integer | [0, 255] |
  613. +---------------+----------------------------------------+---------------------------+
  614. All formats are native-endian.
  615. 4. Data Sources
  616. ===============
  617. The data source abstraction in miniaudio is used for retrieving audio data from some source. A few
  618. examples include `ma_decoder`, `ma_noise` and `ma_waveform`. You will need to be familiar with data
  619. sources in order to make sense of some of the higher level concepts in miniaudio.
  620. The `ma_data_source` API is a generic interface for reading from a data source. Any object that
  621. implements the data source interface can be plugged into any `ma_data_source` function.
  622. To read data from a data source:
  623. ```c
  624. ma_result result;
  625. ma_uint64 framesRead;
  626. result = ma_data_source_read_pcm_frames(pDataSource, pFramesOut, frameCount, &framesRead);
  627. if (result != MA_SUCCESS) {
  628. return result; // Failed to read data from the data source.
  629. }
  630. ```
  631. If you don't need the number of frames that were successfully read you can pass in `NULL` to the
  632. `pFramesRead` parameter. If this returns a value less than the number of frames requested it means
  633. the end of the file has been reached. `MA_AT_END` will be returned only when the number of frames
  634. read is 0.
  635. When calling any data source function, with the exception of `ma_data_source_init()` and
  636. `ma_data_source_uninit()`, you can pass in any object that implements a data source. For example,
  637. you could plug in a decoder like so:
  638. ```c
  639. ma_result result;
  640. ma_uint64 framesRead;
  641. ma_decoder decoder; // <-- This would be initialized with `ma_decoder_init_*()`.
  642. result = ma_data_source_read_pcm_frames(&decoder, pFramesOut, frameCount, &framesRead);
  643. if (result != MA_SUCCESS) {
  644. return result; // Failed to read data from the decoder.
  645. }
  646. ```
  647. If you want to seek forward you can pass in `NULL` to the `pFramesOut` parameter. Alternatively you
  648. can use `ma_data_source_seek_pcm_frames()`.
  649. To seek to a specific PCM frame:
  650. ```c
  651. result = ma_data_source_seek_to_pcm_frame(pDataSource, frameIndex);
  652. if (result != MA_SUCCESS) {
  653. return result; // Failed to seek to PCM frame.
  654. }
  655. ```
  656. You can retrieve the total length of a data source in PCM frames, but note that some data sources
  657. may not have the notion of a length, such as noise and waveforms, and others may just not have a
  658. way of determining the length such as some decoders. To retrieve the length:
  659. ```c
  660. ma_uint64 length;
  661. result = ma_data_source_get_length_in_pcm_frames(pDataSource, &length);
  662. if (result != MA_SUCCESS) {
  663. return result; // Failed to retrieve the length.
  664. }
  665. ```
  666. Care should be taken when retrieving the length of a data source where the underlying decoder is
  667. pulling data from a data stream with an undefined length, such as internet radio or some kind of
  668. broadcast. If you do this, `ma_data_source_get_length_in_pcm_frames()` may never return.
  669. The current position of the cursor in PCM frames can also be retrieved:
  670. ```c
  671. ma_uint64 cursor;
  672. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursor);
  673. if (result != MA_SUCCESS) {
  674. return result; // Failed to retrieve the cursor.
  675. }
  676. ```
  677. You will often need to know the data format that will be returned after reading. This can be
  678. retrieved like so:
  679. ```c
  680. ma_format format;
  681. ma_uint32 channels;
  682. ma_uint32 sampleRate;
  683. ma_channel channelMap[MA_MAX_CHANNELS];
  684. result = ma_data_source_get_data_format(pDataSource, &format, &channels, &sampleRate, channelMap, MA_MAX_CHANNELS);
  685. if (result != MA_SUCCESS) {
  686. return result; // Failed to retrieve data format.
  687. }
  688. ```
  689. If you do not need a specific data format property, just pass in NULL to the respective parameter.
  690. There may be cases where you want to implement something like a sound bank where you only want to
  691. read data within a certain range of the underlying data. To do this you can use a range:
  692. ```c
  693. result = ma_data_source_set_range_in_pcm_frames(pDataSource, rangeBegInFrames, rangeEndInFrames);
  694. if (result != MA_SUCCESS) {
  695. return result; // Failed to set the range.
  696. }
  697. ```
  698. This is useful if you have a sound bank where many sounds are stored in the same file and you want
  699. the data source to only play one of those sub-sounds. Note that once the range is set, everything
  700. that takes a position, such as cursors and loop points, should always be relatvie to the start of
  701. the range. When the range is set, any previously defined loop point will be reset.
  702. Custom loop points can also be used with data sources. By default, data sources will loop after
  703. they reach the end of the data source, but if you need to loop at a specific location, you can do
  704. the following:
  705. ```c
  706. result = ma_data_set_loop_point_in_pcm_frames(pDataSource, loopBegInFrames, loopEndInFrames);
  707. if (result != MA_SUCCESS) {
  708. return result; // Failed to set the loop point.
  709. }
  710. ```
  711. The loop point is relative to the current range.
  712. It's sometimes useful to chain data sources together so that a seamless transition can be achieved.
  713. To do this, you can use chaining:
  714. ```c
  715. ma_decoder decoder1;
  716. ma_decoder decoder2;
  717. // ... initialize decoders with ma_decoder_init_*() ...
  718. result = ma_data_source_set_next(&decoder1, &decoder2);
  719. if (result != MA_SUCCESS) {
  720. return result; // Failed to set the next data source.
  721. }
  722. result = ma_data_source_read_pcm_frames(&decoder1, pFramesOut, frameCount, pFramesRead);
  723. if (result != MA_SUCCESS) {
  724. return result; // Failed to read from the decoder.
  725. }
  726. ```
  727. In the example above we're using decoders. When reading from a chain, you always want to read from
  728. the top level data source in the chain. In the example above, `decoder1` is the top level data
  729. source in the chain. When `decoder1` reaches the end, `decoder2` will start seamlessly without any
  730. gaps.
  731. Note that when looping is enabled, only the current data source will be looped. You can loop the
  732. entire chain by linking in a loop like so:
  733. ```c
  734. ma_data_source_set_next(&decoder1, &decoder2); // decoder1 -> decoder2
  735. ma_data_source_set_next(&decoder2, &decoder1); // decoder2 -> decoder1 (loop back to the start).
  736. ```
  737. Note that setting up chaining is not thread safe, so care needs to be taken if you're dynamically
  738. changing links while the audio thread is in the middle of reading.
  739. Do not use `ma_decoder_seek_to_pcm_frame()` as a means to reuse a data source to play multiple
  740. instances of the same sound simultaneously. This can be extremely inefficient depending on the type
  741. of data source and can result in glitching due to subtle changes to the state of internal filters.
  742. Instead, initialize multiple data sources for each instance.
  743. 4.1. Custom Data Sources
  744. ------------------------
  745. You can implement a custom data source by implementing the functions in `ma_data_source_vtable`.
  746. Your custom object must have `ma_data_source_base` as it's first member:
  747. ```c
  748. struct my_data_source
  749. {
  750. ma_data_source_base base;
  751. ...
  752. };
  753. ```
  754. In your initialization routine, you need to call `ma_data_source_init()` in order to set up the
  755. base object (`ma_data_source_base`):
  756. ```c
  757. static ma_result my_data_source_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  758. {
  759. // Read data here. Output in the same format returned by my_data_source_get_data_format().
  760. }
  761. static ma_result my_data_source_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  762. {
  763. // Seek to a specific PCM frame here. Return MA_NOT_IMPLEMENTED if seeking is not supported.
  764. }
  765. static ma_result my_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  766. {
  767. // Return the format of the data here.
  768. }
  769. static ma_result my_data_source_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  770. {
  771. // Retrieve the current position of the cursor here. Return MA_NOT_IMPLEMENTED and set *pCursor to 0 if there is no notion of a cursor.
  772. }
  773. static ma_result my_data_source_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  774. {
  775. // Retrieve the length in PCM frames here. Return MA_NOT_IMPLEMENTED and set *pLength to 0 if there is no notion of a length or if the length is unknown.
  776. }
  777. static ma_data_source_vtable g_my_data_source_vtable =
  778. {
  779. my_data_source_read,
  780. my_data_source_seek,
  781. my_data_source_get_data_format,
  782. my_data_source_get_cursor,
  783. my_data_source_get_length
  784. };
  785. ma_result my_data_source_init(my_data_source* pMyDataSource)
  786. {
  787. ma_result result;
  788. ma_data_source_config baseConfig;
  789. baseConfig = ma_data_source_config_init();
  790. baseConfig.vtable = &g_my_data_source_vtable;
  791. result = ma_data_source_init(&baseConfig, &pMyDataSource->base);
  792. if (result != MA_SUCCESS) {
  793. return result;
  794. }
  795. // ... do the initialization of your custom data source here ...
  796. return MA_SUCCESS;
  797. }
  798. void my_data_source_uninit(my_data_source* pMyDataSource)
  799. {
  800. // ... do the uninitialization of your custom data source here ...
  801. // You must uninitialize the base data source.
  802. ma_data_source_uninit(&pMyDataSource->base);
  803. }
  804. ```
  805. Note that `ma_data_source_init()` and `ma_data_source_uninit()` are never called directly outside
  806. of the custom data source. It's up to the custom data source itself to call these within their own
  807. init/uninit functions.
  808. 5. Engine
  809. =========
  810. The `ma_engine` API is a high level API for managing and mixing sounds and effect processing. The
  811. `ma_engine` object encapsulates a resource manager and a node graph, both of which will be
  812. explained in more detail later.
  813. Sounds are called `ma_sound` and are created from an engine. Sounds can be associated with a mixing
  814. group called `ma_sound_group` which are also created from the engine. Both `ma_sound` and
  815. `ma_sound_group` objects are nodes within the engine's node graph.
  816. When the engine is initialized, it will normally create a device internally. If you would rather
  817. manage the device yourself, you can do so and just pass a pointer to it via the engine config when
  818. you initialize the engine. You can also just use the engine without a device, which again can be
  819. configured via the engine config.
  820. The most basic way to initialize the engine is with a default config, like so:
  821. ```c
  822. ma_result result;
  823. ma_engine engine;
  824. result = ma_engine_init(NULL, &engine);
  825. if (result != MA_SUCCESS) {
  826. return result; // Failed to initialize the engine.
  827. }
  828. ```
  829. This will result in the engine initializing a playback device using the operating system's default
  830. device. This will be sufficient for many use cases, but if you need more flexibility you'll want to
  831. configure the engine with an engine config:
  832. ```c
  833. ma_result result;
  834. ma_engine engine;
  835. ma_engine_config engineConfig;
  836. engineConfig = ma_engine_config_init();
  837. engineConfig.pDevice = &myDevice;
  838. result = ma_engine_init(&engineConfig, &engine);
  839. if (result != MA_SUCCESS) {
  840. return result; // Failed to initialize the engine.
  841. }
  842. ```
  843. In the example above we're passing in a pre-initialized device. Since the caller is the one in
  844. control of the device's data callback, it's their responsibility to manually call
  845. `ma_engine_read_pcm_frames()` from inside their data callback:
  846. ```c
  847. void playback_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
  848. {
  849. ma_engine_read_pcm_frames(&g_Engine, pOutput, frameCount, NULL);
  850. }
  851. ```
  852. You can also use the engine independent of a device entirely:
  853. ```c
  854. ma_result result;
  855. ma_engine engine;
  856. ma_engine_config engineConfig;
  857. engineConfig = ma_engine_config_init();
  858. engineConfig.noDevice = MA_TRUE;
  859. engineConfig.channels = 2; // Must be set when not using a device.
  860. engineConfig.sampleRate = 48000; // Must be set when not using a device.
  861. result = ma_engine_init(&engineConfig, &engine);
  862. if (result != MA_SUCCESS) {
  863. return result; // Failed to initialize the engine.
  864. }
  865. ```
  866. Note that when you're not using a device, you must set the channel count and sample rate in the
  867. config or else miniaudio won't know what to use (miniaudio will use the device to determine this
  868. normally). When not using a device, you need to use `ma_engine_read_pcm_frames()` to process audio
  869. data from the engine. This kind of setup is useful if you want to do something like offline
  870. processing or want to use a different audio system for playback such as SDL.
  871. When a sound is loaded it goes through a resource manager. By default the engine will initialize a
  872. resource manager internally, but you can also specify a pre-initialized resource manager:
  873. ```c
  874. ma_result result;
  875. ma_engine engine1;
  876. ma_engine engine2;
  877. ma_engine_config engineConfig;
  878. engineConfig = ma_engine_config_init();
  879. engineConfig.pResourceManager = &myResourceManager;
  880. ma_engine_init(&engineConfig, &engine1);
  881. ma_engine_init(&engineConfig, &engine2);
  882. ```
  883. In this example we are initializing two engines, both of which are sharing the same resource
  884. manager. This is especially useful for saving memory when loading the same file across multiple
  885. engines. If you were not to use a shared resource manager, each engine instance would use their own
  886. which would result in any sounds that are used between both engine's being loaded twice. By using
  887. a shared resource manager, it would only be loaded once. Using multiple engine's is useful when you
  888. need to output to multiple playback devices, such as in a local multiplayer game where each player
  889. is using their own set of headphones.
  890. By default an engine will be in a started state. To make it so the engine is not automatically
  891. started you can configure it as such:
  892. ```c
  893. engineConfig.noAutoStart = MA_TRUE;
  894. // The engine will need to be started manually.
  895. ma_engine_start(&engine);
  896. // Later on the engine can be stopped with ma_engine_stop().
  897. ma_engine_stop(&engine);
  898. ```
  899. The concept of starting or stopping an engine is only relevant when using the engine with a
  900. device. Attempting to start or stop an engine that is not associated with a device will result in
  901. `MA_INVALID_OPERATION`.
  902. The master volume of the engine can be controlled with `ma_engine_set_volume()` which takes a
  903. linear scale, with 0 resulting in silence and anything above 1 resulting in amplification. If you
  904. prefer decibel based volume control, use `ma_volume_db_to_linear()` to convert from dB to linear.
  905. When a sound is spatialized, it is done so relative to a listener. An engine can be configured to
  906. have multiple listeners which can be configured via the config:
  907. ```c
  908. engineConfig.listenerCount = 2;
  909. ```
  910. The maximum number of listeners is restricted to `MA_ENGINE_MAX_LISTENERS`. By default, when a
  911. sound is spatialized, it will be done so relative to the closest listener. You can also pin a sound
  912. to a specific listener which will be explained later. Listener's have a position, direction, cone,
  913. and velocity (for doppler effect). A listener is referenced by an index, the meaning of which is up
  914. to the caller (the index is 0 based and cannot go beyond the listener count, minus 1). The
  915. position, direction and velocity are all specified in absolute terms:
  916. ```c
  917. ma_engine_listener_set_position(&engine, listenerIndex, worldPosX, worldPosY, worldPosZ);
  918. ```
  919. The direction of the listener represents it's forward vector. The listener's up vector can also be
  920. specified and defaults to +1 on the Y axis.
  921. ```c
  922. ma_engine_listener_set_direction(&engine, listenerIndex, forwardX, forwardY, forwardZ);
  923. ma_engine_listener_set_world_up(&engine, listenerIndex, 0, 1, 0);
  924. ```
  925. The engine supports directional attenuation. The listener can have a cone the controls how sound is
  926. attenuated based on the listener's direction. When a sound is between the inner and outer cones, it
  927. will be attenuated between 1 and the cone's outer gain:
  928. ```c
  929. ma_engine_listener_set_cone(&engine, listenerIndex, innerAngleInRadians, outerAngleInRadians, outerGain);
  930. ```
  931. When a sound is inside the inner code, no directional attenuation is applied. When the sound is
  932. outside of the outer cone, the attenuation will be set to `outerGain` in the example above. When
  933. the sound is in between the inner and outer cones, the attenuation will be interpolated between 1
  934. and the outer gain.
  935. The engine's coordinate system follows the OpenGL coordinate system where positive X points right,
  936. positive Y points up and negative Z points forward.
  937. The simplest and least flexible way to play a sound is like so:
  938. ```c
  939. ma_engine_play_sound(&engine, "my_sound.wav", pGroup);
  940. ```
  941. This is a "fire and forget" style of function. The engine will manage the `ma_sound` object
  942. internally. When the sound finishes playing, it'll be put up for recycling. For more flexibility
  943. you'll want to initialize a sound object:
  944. ```c
  945. ma_sound sound;
  946. result = ma_sound_init_from_file(&engine, "my_sound.wav", flags, pGroup, NULL, &sound);
  947. if (result != MA_SUCCESS) {
  948. return result; // Failed to load sound.
  949. }
  950. ```
  951. Sounds need to be uninitialized with `ma_sound_uninit()`.
  952. The example above loads a sound from a file. If the resource manager has been disabled you will not
  953. be able to use this function and instead you'll need to initialize a sound directly from a data
  954. source:
  955. ```c
  956. ma_sound sound;
  957. result = ma_sound_init_from_data_source(&engine, &dataSource, flags, pGroup, &sound);
  958. if (result != MA_SUCCESS) {
  959. return result;
  960. }
  961. ```
  962. Each `ma_sound` object represents a single instance of the sound. If you want to play the same
  963. sound multiple times at the same time, you need to initialize a separate `ma_sound` object.
  964. For the most flexibility when initializing sounds, use `ma_sound_init_ex()`. This uses miniaudio's
  965. standard config/init pattern:
  966. ```c
  967. ma_sound sound;
  968. ma_sound_config soundConfig;
  969. soundConfig = ma_sound_config_init();
  970. soundConfig.pFilePath = NULL; // Set this to load from a file path.
  971. soundConfig.pDataSource = NULL; // Set this to initialize from an existing data source.
  972. soundConfig.pInitialAttachment = &someNodeInTheNodeGraph;
  973. soundConfig.initialAttachmentInputBusIndex = 0;
  974. soundConfig.channelsIn = 1;
  975. soundConfig.channelsOut = 0; // Set to 0 to use the engine's native channel count.
  976. result = ma_sound_init_ex(&soundConfig, &sound);
  977. if (result != MA_SUCCESS) {
  978. return result;
  979. }
  980. ```
  981. In the example above, the sound is being initialized without a file nor a data source. This is
  982. valid, in which case the sound acts as a node in the middle of the node graph. This means you can
  983. connect other sounds to this sound and allow it to act like a sound group. Indeed, this is exactly
  984. what a `ma_sound_group` is.
  985. When loading a sound, you specify a set of flags that control how the sound is loaded and what
  986. features are enabled for that sound. When no flags are set, the sound will be fully loaded into
  987. memory in exactly the same format as how it's stored on the file system. The resource manager will
  988. allocate a block of memory and then load the file directly into it. When reading audio data, it
  989. will be decoded dynamically on the fly. In order to save processing time on the audio thread, it
  990. might be beneficial to pre-decode the sound. You can do this with the `MA_SOUND_FLAG_DECODE` flag:
  991. ```c
  992. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE, pGroup, NULL, &sound);
  993. ```
  994. By default, sounds will be loaded synchronously, meaning `ma_sound_init_*()` will not return until
  995. the sound has been fully loaded. If this is prohibitive you can instead load sounds asynchronously
  996. by specifying the `MA_SOUND_FLAG_ASYNC` flag:
  997. ```c
  998. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, NULL, &sound);
  999. ```
  1000. This will result in `ma_sound_init_*()` returning quickly, but the sound won't yet have been fully
  1001. loaded. When you start the sound, it won't output anything until some sound is available. The sound
  1002. will start outputting audio before the sound has been fully decoded when the `MA_SOUND_FLAG_DECODE`
  1003. is specified.
  1004. If you need to wait for an asynchronously loaded sound to be fully loaded, you can use a fence. A
  1005. fence in miniaudio is a simple synchronization mechanism which simply blocks until it's internal
  1006. counter hit's zero. You can specify a fence like so:
  1007. ```c
  1008. ma_result result;
  1009. ma_fence fence;
  1010. ma_sound sounds[4];
  1011. result = ma_fence_init(&fence);
  1012. if (result != MA_SUCCESS) {
  1013. return result;
  1014. }
  1015. // Load some sounds asynchronously.
  1016. for (int iSound = 0; iSound < 4; iSound += 1) {
  1017. ma_sound_init_from_file(&engine, mySoundFilesPaths[iSound], MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, &fence, &sounds[iSound]);
  1018. }
  1019. // ... do some other stuff here in the mean time ...
  1020. // Wait for all sounds to finish loading.
  1021. ma_fence_wait(&fence);
  1022. ```
  1023. If loading the entire sound into memory is prohibitive, you can also configure the engine to stream
  1024. the audio data:
  1025. ```c
  1026. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_STREAM, pGroup, NULL, &sound);
  1027. ```
  1028. When streaming sounds, 2 seconds worth of audio data is stored in memory. Although it should work
  1029. fine, it's inefficient to use streaming for short sounds. Streaming is useful for things like music
  1030. tracks in games.
  1031. When loading a sound from a file path, the engine will reference count the file to prevent it from
  1032. being loaded if it's already in memory. When you uninitialize a sound, the reference count will be
  1033. decremented, and if it hits zero, the sound will be unloaded from memory. This reference counting
  1034. system is not used for streams. The engine will use a 64-bit hash of the file name when comparing
  1035. file paths which means there's a small chance you might encounter a name collision. If this is an
  1036. issue, you'll need to use a different name for one of the colliding file paths, or just not load
  1037. from files and instead load from a data source.
  1038. You can use `ma_sound_init_copy()` to initialize a copy of another sound. Note, however, that this
  1039. only works for sounds that were initialized with `ma_sound_init_from_file()` and without the
  1040. `MA_SOUND_FLAG_STREAM` flag.
  1041. When you initialize a sound, if you specify a sound group the sound will be attached to that group
  1042. automatically. If you set it to NULL, it will be automatically attached to the engine's endpoint.
  1043. If you would instead rather leave the sound unattached by default, you can can specify the
  1044. `MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT` flag. This is useful if you want to set up a complex node
  1045. graph.
  1046. Sounds are not started by default. To start a sound, use `ma_sound_start()`. Stop a sound with
  1047. `ma_sound_stop()`.
  1048. Sounds can have their volume controlled with `ma_sound_set_volume()` in the same way as the
  1049. engine's master volume.
  1050. Sounds support stereo panning and pitching. Set the pan with `ma_sound_set_pan()`. Setting the pan
  1051. to 0 will result in an unpanned sound. Setting it to -1 will shift everything to the left, whereas
  1052. +1 will shift it to the right. The pitch can be controlled with `ma_sound_set_pitch()`. A larger
  1053. value will result in a higher pitch. The pitch must be greater than 0.
  1054. The engine supports 3D spatialization of sounds. By default sounds will have spatialization
  1055. enabled, but if a sound does not need to be spatialized it's best to disable it. There are two ways
  1056. to disable spatialization of a sound:
  1057. ```c
  1058. // Disable spatialization at initialization time via a flag:
  1059. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_NO_SPATIALIZATION, NULL, NULL, &sound);
  1060. // Dynamically disable or enable spatialization post-initialization:
  1061. ma_sound_set_spatialization_enabled(&sound, isSpatializationEnabled);
  1062. ```
  1063. By default sounds will be spatialized based on the closest listener. If a sound should always be
  1064. spatialized relative to a specific listener it can be pinned to one:
  1065. ```c
  1066. ma_sound_set_pinned_listener_index(&sound, listenerIndex);
  1067. ```
  1068. Like listeners, sounds have a position. By default, the position of a sound is in absolute space,
  1069. but it can be changed to be relative to a listener:
  1070. ```c
  1071. ma_sound_set_positioning(&sound, ma_positioning_relative);
  1072. ```
  1073. Note that relative positioning of a sound only makes sense if there is either only one listener, or
  1074. the sound is pinned to a specific listener. To set the position of a sound:
  1075. ```c
  1076. ma_sound_set_position(&sound, posX, posY, posZ);
  1077. ```
  1078. The direction works the same way as a listener and represents the sound's forward direction:
  1079. ```c
  1080. ma_sound_set_direction(&sound, forwardX, forwardY, forwardZ);
  1081. ```
  1082. Sound's also have a cone for controlling directional attenuation. This works exactly the same as
  1083. listeners:
  1084. ```c
  1085. ma_sound_set_cone(&sound, innerAngleInRadians, outerAngleInRadians, outerGain);
  1086. ```
  1087. The velocity of a sound is used for doppler effect and can be set as such:
  1088. ```c
  1089. ma_sound_set_velocity(&sound, velocityX, velocityY, velocityZ);
  1090. ```
  1091. The engine supports different attenuation models which can be configured on a per-sound basis. By
  1092. default the attenuation model is set to `ma_attenuation_model_inverse` which is the equivalent to
  1093. OpenAL's `AL_INVERSE_DISTANCE_CLAMPED`. Configure the attenuation model like so:
  1094. ```c
  1095. ma_sound_set_attenuation_model(&sound, ma_attenuation_model_inverse);
  1096. ```
  1097. The supported attenuation models include the following:
  1098. +----------------------------------+----------------------------------------------+
  1099. | ma_attenuation_model_none | No distance attenuation. |
  1100. +----------------------------------+----------------------------------------------+
  1101. | ma_attenuation_model_inverse | Equivalent to `AL_INVERSE_DISTANCE_CLAMPED`. |
  1102. +----------------------------------+----------------------------------------------+
  1103. | ma_attenuation_model_linear | Linear attenuation. |
  1104. +----------------------------------+----------------------------------------------+
  1105. | ma_attenuation_model_exponential | Exponential attenuation. |
  1106. +----------------------------------+----------------------------------------------+
  1107. To control how quickly a sound rolls off as it moves away from the listener, you need to configure
  1108. the rolloff:
  1109. ```c
  1110. ma_sound_set_rolloff(&sound, rolloff);
  1111. ```
  1112. You can control the minimum and maximum gain to apply from spatialization:
  1113. ```c
  1114. ma_sound_set_min_gain(&sound, minGain);
  1115. ma_sound_set_max_gain(&sound, maxGain);
  1116. ```
  1117. Likewise, in the calculation of attenuation, you can control the minimum and maximum distances for
  1118. the attenuation calculation. This is useful if you want to ensure sounds don't drop below a certain
  1119. volume after the listener moves further away and to have sounds play a maximum volume when the
  1120. listener is within a certain distance:
  1121. ```c
  1122. ma_sound_set_min_distance(&sound, minDistance);
  1123. ma_sound_set_max_distance(&sound, maxDistance);
  1124. ```
  1125. The engine's spatialization system supports doppler effect. The doppler factor can be configure on
  1126. a per-sound basis like so:
  1127. ```c
  1128. ma_sound_set_doppler_factor(&sound, dopplerFactor);
  1129. ```
  1130. You can fade sounds in and out with `ma_sound_set_fade_in_pcm_frames()` and
  1131. `ma_sound_set_fade_in_milliseconds()`. Set the volume to -1 to use the current volume as the
  1132. starting volume:
  1133. ```c
  1134. // Fade in over 1 second.
  1135. ma_sound_set_fade_in_milliseconds(&sound, 0, 1, 1000);
  1136. // ... sometime later ...
  1137. // Fade out over 1 second, starting from the current volume.
  1138. ma_sound_set_fade_in_milliseconds(&sound, -1, 0, 1000);
  1139. ```
  1140. By default sounds will start immediately, but sometimes for timing and synchronization purposes it
  1141. can be useful to schedule a sound to start or stop:
  1142. ```c
  1143. // Start the sound in 1 second from now.
  1144. ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 1));
  1145. // Stop the sound in 2 seconds from now.
  1146. ma_sound_set_stop_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 2));
  1147. ```
  1148. Note that scheduling a start time still requires an explicit call to `ma_sound_start()` before
  1149. anything will play.
  1150. The time is specified in global time which is controlled by the engine. You can get the engine's
  1151. current time with `ma_engine_get_time_in_pcm_frames()`. The engine's global time is incremented
  1152. automatically as audio data is read, but it can be reset with `ma_engine_set_time_in_pcm_frames()`
  1153. in case it needs to be resynchronized for some reason.
  1154. To determine whether or not a sound is currently playing, use `ma_sound_is_playing()`. This will
  1155. take the scheduled start and stop times into account.
  1156. Whether or not a sound should loop can be controlled with `ma_sound_set_looping()`. Sounds will not
  1157. be looping by default. Use `ma_sound_is_looping()` to determine whether or not a sound is looping.
  1158. Use `ma_sound_at_end()` to determine whether or not a sound is currently at the end. For a looping
  1159. sound this should never return true. Alternatively, you can configure a callback that will be fired
  1160. when the sound reaches the end. Note that the callback is fired from the audio thread which means
  1161. you cannot be uninitializing sound from the callback. To set the callback you can use
  1162. `ma_sound_set_end_callback()`. Alternatively, if you're using `ma_sound_init_ex()`, you can pass it
  1163. into the config like so:
  1164. ```c
  1165. soundConfig.endCallback = my_end_callback;
  1166. soundConfig.pEndCallbackUserData = pMyEndCallbackUserData;
  1167. ```
  1168. The end callback is declared like so:
  1169. ```c
  1170. void my_end_callback(void* pUserData, ma_sound* pSound)
  1171. {
  1172. ...
  1173. }
  1174. ```
  1175. Internally a sound wraps around a data source. Some APIs exist to control the underlying data
  1176. source, mainly for convenience:
  1177. ```c
  1178. ma_sound_seek_to_pcm_frame(&sound, frameIndex);
  1179. ma_sound_get_data_format(&sound, &format, &channels, &sampleRate, pChannelMap, channelMapCapacity);
  1180. ma_sound_get_cursor_in_pcm_frames(&sound, &cursor);
  1181. ma_sound_get_length_in_pcm_frames(&sound, &length);
  1182. ```
  1183. Sound groups have the same API as sounds, only they are called `ma_sound_group`, and since they do
  1184. not have any notion of a data source, anything relating to a data source is unavailable.
  1185. Internally, sound data is loaded via the `ma_decoder` API which means by default it only supports
  1186. file formats that have built-in support in miniaudio. You can extend this to support any kind of
  1187. file format through the use of custom decoders. To do this you'll need to use a self-managed
  1188. resource manager and configure it appropriately. See the "Resource Management" section below for
  1189. details on how to set this up.
  1190. 6. Resource Management
  1191. ======================
  1192. Many programs will want to manage sound resources for things such as reference counting and
  1193. streaming. This is supported by miniaudio via the `ma_resource_manager` API.
  1194. The resource manager is mainly responsible for the following:
  1195. * Loading of sound files into memory with reference counting.
  1196. * Streaming of sound data.
  1197. When loading a sound file, the resource manager will give you back a `ma_data_source` compatible
  1198. object called `ma_resource_manager_data_source`. This object can be passed into any
  1199. `ma_data_source` API which is how you can read and seek audio data. When loading a sound file, you
  1200. specify whether or not you want the sound to be fully loaded into memory (and optionally
  1201. pre-decoded) or streamed. When loading into memory, you can also specify whether or not you want
  1202. the data to be loaded asynchronously.
  1203. The example below is how you can initialize a resource manager using it's default configuration:
  1204. ```c
  1205. ma_resource_manager_config config;
  1206. ma_resource_manager resourceManager;
  1207. config = ma_resource_manager_config_init();
  1208. result = ma_resource_manager_init(&config, &resourceManager);
  1209. if (result != MA_SUCCESS) {
  1210. ma_device_uninit(&device);
  1211. printf("Failed to initialize the resource manager.");
  1212. return -1;
  1213. }
  1214. ```
  1215. You can configure the format, channels and sample rate of the decoded audio data. By default it
  1216. will use the file's native data format, but you can configure it to use a consistent format. This
  1217. is useful for offloading the cost of data conversion to load time rather than dynamically
  1218. converting at mixing time. To do this, you configure the decoded format, channels and sample rate
  1219. like the code below:
  1220. ```c
  1221. config = ma_resource_manager_config_init();
  1222. config.decodedFormat = device.playback.format;
  1223. config.decodedChannels = device.playback.channels;
  1224. config.decodedSampleRate = device.sampleRate;
  1225. ```
  1226. In the code above, the resource manager will be configured so that any decoded audio data will be
  1227. pre-converted at load time to the device's native data format. If instead you used defaults and
  1228. the data format of the file did not match the device's data format, you would need to convert the
  1229. data at mixing time which may be prohibitive in high-performance and large scale scenarios like
  1230. games.
  1231. Internally the resource manager uses the `ma_decoder` API to load sounds. This means by default it
  1232. only supports decoders that are built into miniaudio. It's possible to support additional encoding
  1233. formats through the use of custom decoders. To do so, pass in your `ma_decoding_backend_vtable`
  1234. vtables into the resource manager config:
  1235. ```c
  1236. ma_decoding_backend_vtable* pCustomBackendVTables[] =
  1237. {
  1238. &g_ma_decoding_backend_vtable_libvorbis,
  1239. &g_ma_decoding_backend_vtable_libopus
  1240. };
  1241. ...
  1242. resourceManagerConfig.ppCustomDecodingBackendVTables = pCustomBackendVTables;
  1243. resourceManagerConfig.customDecodingBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
  1244. resourceManagerConfig.pCustomDecodingBackendUserData = NULL;
  1245. ```
  1246. This system can allow you to support any kind of file format. See the "Decoding" section for
  1247. details on how to implement custom decoders. The miniaudio repository includes examples for Opus
  1248. via libopus and libopusfile and Vorbis via libvorbis and libvorbisfile.
  1249. Asynchronicity is achieved via a job system. When an operation needs to be performed, such as the
  1250. decoding of a page, a job will be posted to a queue which will then be processed by a job thread.
  1251. By default there will be only one job thread running, but this can be configured, like so:
  1252. ```c
  1253. config = ma_resource_manager_config_init();
  1254. config.jobThreadCount = MY_JOB_THREAD_COUNT;
  1255. ```
  1256. By default job threads are managed internally by the resource manager, however you can also self
  1257. manage your job threads if, for example, you want to integrate the job processing into your
  1258. existing job infrastructure, or if you simply don't like the way the resource manager does it. To
  1259. do this, just set the job thread count to 0 and process jobs manually. To process jobs, you first
  1260. need to retrieve a job using `ma_resource_manager_next_job()` and then process it using
  1261. `ma_job_process()`:
  1262. ```c
  1263. config = ma_resource_manager_config_init();
  1264. config.jobThreadCount = 0; // Don't manage any job threads internally.
  1265. config.flags = MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING; // Optional. Makes `ma_resource_manager_next_job()` non-blocking.
  1266. // ... Initialize your custom job threads ...
  1267. void my_custom_job_thread(...)
  1268. {
  1269. for (;;) {
  1270. ma_job job;
  1271. ma_result result = ma_resource_manager_next_job(pMyResourceManager, &job);
  1272. if (result != MA_SUCCESS) {
  1273. if (result == MA_NO_DATA_AVAILABLE) {
  1274. // No jobs are available. Keep going. Will only get this if the resource manager was initialized
  1275. // with MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING.
  1276. continue;
  1277. } else if (result == MA_CANCELLED) {
  1278. // MA_JOB_TYPE_QUIT was posted. Exit.
  1279. break;
  1280. } else {
  1281. // Some other error occurred.
  1282. break;
  1283. }
  1284. }
  1285. ma_job_process(&job);
  1286. }
  1287. }
  1288. ```
  1289. In the example above, the `MA_JOB_TYPE_QUIT` event is the used as the termination
  1290. indicator, but you can use whatever you would like to terminate the thread. The call to
  1291. `ma_resource_manager_next_job()` is blocking by default, but can be configured to be non-blocking
  1292. by initializing the resource manager with the `MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING` configuration
  1293. flag. Note that the `MA_JOB_TYPE_QUIT` will never be removed from the job queue. This
  1294. is to give every thread the opportunity to catch the event and terminate naturally.
  1295. When loading a file, it's sometimes convenient to be able to customize how files are opened and
  1296. read instead of using standard `fopen()`, `fclose()`, etc. which is what miniaudio will use by
  1297. default. This can be done by setting `pVFS` member of the resource manager's config:
  1298. ```c
  1299. // Initialize your custom VFS object. See documentation for VFS for information on how to do this.
  1300. my_custom_vfs vfs = my_custom_vfs_init();
  1301. config = ma_resource_manager_config_init();
  1302. config.pVFS = &vfs;
  1303. ```
  1304. This is particularly useful in programs like games where you want to read straight from an archive
  1305. rather than the normal file system. If you do not specify a custom VFS, the resource manager will
  1306. use the operating system's normal file operations.
  1307. To load a sound file and create a data source, call `ma_resource_manager_data_source_init()`. When
  1308. loading a sound you need to specify the file path and options for how the sounds should be loaded.
  1309. By default a sound will be loaded synchronously. The returned data source is owned by the caller
  1310. which means the caller is responsible for the allocation and freeing of the data source. Below is
  1311. an example for initializing a data source:
  1312. ```c
  1313. ma_resource_manager_data_source dataSource;
  1314. ma_result result = ma_resource_manager_data_source_init(pResourceManager, pFilePath, flags, &dataSource);
  1315. if (result != MA_SUCCESS) {
  1316. // Error.
  1317. }
  1318. // ...
  1319. // A ma_resource_manager_data_source object is compatible with the `ma_data_source` API. To read data, just call
  1320. // the `ma_data_source_read_pcm_frames()` like you would with any normal data source.
  1321. result = ma_data_source_read_pcm_frames(&dataSource, pDecodedData, frameCount, &framesRead);
  1322. if (result != MA_SUCCESS) {
  1323. // Failed to read PCM frames.
  1324. }
  1325. // ...
  1326. ma_resource_manager_data_source_uninit(pResourceManager, &dataSource);
  1327. ```
  1328. The `flags` parameter specifies how you want to perform loading of the sound file. It can be a
  1329. combination of the following flags:
  1330. ```
  1331. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM
  1332. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE
  1333. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC
  1334. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT
  1335. ```
  1336. When no flags are specified (set to 0), the sound will be fully loaded into memory, but not
  1337. decoded, meaning the raw file data will be stored in memory, and then dynamically decoded when
  1338. `ma_data_source_read_pcm_frames()` is called. To instead decode the audio data before storing it in
  1339. memory, use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` flag. By default, the sound file will
  1340. be loaded synchronously, meaning `ma_resource_manager_data_source_init()` will only return after
  1341. the entire file has been loaded. This is good for simplicity, but can be prohibitively slow. You
  1342. can instead load the sound asynchronously using the `MA_RESOURCE_MANAGER_DATA_SOURCE_ASYNC` flag.
  1343. This will result in `ma_resource_manager_data_source_init()` returning quickly, but no data will be
  1344. returned by `ma_data_source_read_pcm_frames()` until some data is available. When no data is
  1345. available because the asynchronous decoding hasn't caught up, `MA_BUSY` will be returned by
  1346. `ma_data_source_read_pcm_frames()`.
  1347. For large sounds, it's often prohibitive to store the entire file in memory. To mitigate this, you
  1348. can instead stream audio data which you can do by specifying the
  1349. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. When streaming, data will be decoded in 1
  1350. second pages. When a new page needs to be decoded, a job will be posted to the job queue and then
  1351. subsequently processed in a job thread.
  1352. For in-memory sounds, reference counting is used to ensure the data is loaded only once. This means
  1353. multiple calls to `ma_resource_manager_data_source_init()` with the same file path will result in
  1354. the file data only being loaded once. Each call to `ma_resource_manager_data_source_init()` must be
  1355. matched up with a call to `ma_resource_manager_data_source_uninit()`. Sometimes it can be useful
  1356. for a program to register self-managed raw audio data and associate it with a file path. Use the
  1357. `ma_resource_manager_register_*()` and `ma_resource_manager_unregister_*()` APIs to do this.
  1358. `ma_resource_manager_register_decoded_data()` is used to associate a pointer to raw, self-managed
  1359. decoded audio data in the specified data format with the specified name. Likewise,
  1360. `ma_resource_manager_register_encoded_data()` is used to associate a pointer to raw self-managed
  1361. encoded audio data (the raw file data) with the specified name. Note that these names need not be
  1362. actual file paths. When `ma_resource_manager_data_source_init()` is called (without the
  1363. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag), the resource manager will look for these
  1364. explicitly registered data buffers and, if found, will use it as the backing data for the data
  1365. source. Note that the resource manager does *not* make a copy of this data so it is up to the
  1366. caller to ensure the pointer stays valid for it's lifetime. Use
  1367. `ma_resource_manager_unregister_data()` to unregister the self-managed data. You can also use
  1368. `ma_resource_manager_register_file()` and `ma_resource_manager_unregister_file()` to register and
  1369. unregister a file. It does not make sense to use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM`
  1370. flag with a self-managed data pointer.
  1371. 6.1. Asynchronous Loading and Synchronization
  1372. ---------------------------------------------
  1373. When loading asynchronously, it can be useful to poll whether or not loading has finished. Use
  1374. `ma_resource_manager_data_source_result()` to determine this. For in-memory sounds, this will
  1375. return `MA_SUCCESS` when the file has been *entirely* decoded. If the sound is still being decoded,
  1376. `MA_BUSY` will be returned. Otherwise, some other error code will be returned if the sound failed
  1377. to load. For streaming data sources, `MA_SUCCESS` will be returned when the first page has been
  1378. decoded and the sound is ready to be played. If the first page is still being decoded, `MA_BUSY`
  1379. will be returned. Otherwise, some other error code will be returned if the sound failed to load.
  1380. In addition to polling, you can also use a simple synchronization object called a "fence" to wait
  1381. for asynchronously loaded sounds to finish. This is called `ma_fence`. The advantage to using a
  1382. fence is that it can be used to wait for a group of sounds to finish loading rather than waiting
  1383. for sounds on an individual basis. There are two stages to loading a sound:
  1384. * Initialization of the internal decoder; and
  1385. * Completion of decoding of the file (the file is fully decoded)
  1386. You can specify separate fences for each of the different stages. Waiting for the initialization
  1387. of the internal decoder is important for when you need to know the sample format, channels and
  1388. sample rate of the file.
  1389. The example below shows how you could use a fence when loading a number of sounds:
  1390. ```c
  1391. // This fence will be released when all sounds are finished loading entirely.
  1392. ma_fence fence;
  1393. ma_fence_init(&fence);
  1394. // This will be passed into the initialization routine for each sound.
  1395. ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
  1396. notifications.done.pFence = &fence;
  1397. // Now load a bunch of sounds:
  1398. for (iSound = 0; iSound < soundCount; iSound += 1) {
  1399. ma_resource_manager_data_source_init(pResourceManager, pSoundFilePaths[iSound], flags, &notifications, &pSoundSources[iSound]);
  1400. }
  1401. // ... DO SOMETHING ELSE WHILE SOUNDS ARE LOADING ...
  1402. // Wait for loading of sounds to finish.
  1403. ma_fence_wait(&fence);
  1404. ```
  1405. In the example above we used a fence for waiting until the entire file has been fully decoded. If
  1406. you only need to wait for the initialization of the internal decoder to complete, you can use the
  1407. `init` member of the `ma_resource_manager_pipeline_notifications` object:
  1408. ```c
  1409. notifications.init.pFence = &fence;
  1410. ```
  1411. If a fence is not appropriate for your situation, you can instead use a callback that is fired on
  1412. an individual sound basis. This is done in a very similar way to fences:
  1413. ```c
  1414. typedef struct
  1415. {
  1416. ma_async_notification_callbacks cb;
  1417. void* pMyData;
  1418. } my_notification;
  1419. void my_notification_callback(ma_async_notification* pNotification)
  1420. {
  1421. my_notification* pMyNotification = (my_notification*)pNotification;
  1422. // Do something in response to the sound finishing loading.
  1423. }
  1424. ...
  1425. my_notification myCallback;
  1426. myCallback.cb.onSignal = my_notification_callback;
  1427. myCallback.pMyData = pMyData;
  1428. ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
  1429. notifications.done.pNotification = &myCallback;
  1430. ma_resource_manager_data_source_init(pResourceManager, "my_sound.wav", flags, &notifications, &mySound);
  1431. ```
  1432. In the example above we just extend the `ma_async_notification_callbacks` object and pass an
  1433. instantiation into the `ma_resource_manager_pipeline_notifications` in the same way as we did with
  1434. the fence, only we set `pNotification` instead of `pFence`. You can set both of these at the same
  1435. time and they should both work as expected. If using the `pNotification` system, you need to ensure
  1436. your `ma_async_notification_callbacks` object stays valid.
  1437. 6.2. Resource Manager Implementation Details
  1438. --------------------------------------------
  1439. Resources are managed in two main ways:
  1440. * By storing the entire sound inside an in-memory buffer (referred to as a data buffer)
  1441. * By streaming audio data on the fly (referred to as a data stream)
  1442. A resource managed data source (`ma_resource_manager_data_source`) encapsulates a data buffer or
  1443. data stream, depending on whether or not the data source was initialized with the
  1444. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. If so, it will make use of a
  1445. `ma_resource_manager_data_stream` object. Otherwise it will use a `ma_resource_manager_data_buffer`
  1446. object. Both of these objects are data sources which means they can be used with any
  1447. `ma_data_source_*()` API.
  1448. Another major feature of the resource manager is the ability to asynchronously decode audio files.
  1449. This relieves the audio thread of time-consuming decoding which can negatively affect scalability
  1450. due to the audio thread needing to complete it's work extremely quickly to avoid glitching.
  1451. Asynchronous decoding is achieved through a job system. There is a central multi-producer,
  1452. multi-consumer, fixed-capacity job queue. When some asynchronous work needs to be done, a job is
  1453. posted to the queue which is then read by a job thread. The number of job threads can be
  1454. configured for improved scalability, and job threads can all run in parallel without needing to
  1455. worry about the order of execution (how this is achieved is explained below).
  1456. When a sound is being loaded asynchronously, playback can begin before the sound has been fully
  1457. decoded. This enables the application to start playback of the sound quickly, while at the same
  1458. time allowing to resource manager to keep loading in the background. Since there may be less
  1459. threads than the number of sounds being loaded at a given time, a simple scheduling system is used
  1460. to keep decoding time balanced and fair. The resource manager solves this by splitting decoding
  1461. into chunks called pages. By default, each page is 1 second long. When a page has been decoded, a
  1462. new job will be posted to start decoding the next page. By dividing up decoding into pages, an
  1463. individual sound shouldn't ever delay every other sound from having their first page decoded. Of
  1464. course, when loading many sounds at the same time, there will always be an amount of time required
  1465. to process jobs in the queue so in heavy load situations there will still be some delay. To
  1466. determine if a data source is ready to have some frames read, use
  1467. `ma_resource_manager_data_source_get_available_frames()`. This will return the number of frames
  1468. available starting from the current position.
  1469. 6.2.1. Job Queue
  1470. ----------------
  1471. The resource manager uses a job queue which is multi-producer, multi-consumer, and fixed-capacity.
  1472. This job queue is not currently lock-free, and instead uses a spinlock to achieve thread-safety.
  1473. Only a fixed number of jobs can be allocated and inserted into the queue which is done through a
  1474. lock-free data structure for allocating an index into a fixed sized array, with reference counting
  1475. for mitigation of the ABA problem. The reference count is 32-bit.
  1476. For many types of jobs it's important that they execute in a specific order. In these cases, jobs
  1477. are executed serially. For the resource manager, serial execution of jobs is only required on a
  1478. per-object basis (per data buffer or per data stream). Each of these objects stores an execution
  1479. counter. When a job is posted it is associated with an execution counter. When the job is
  1480. processed, it checks if the execution counter of the job equals the execution counter of the
  1481. owning object and if so, processes the job. If the counters are not equal, the job will be posted
  1482. back onto the job queue for later processing. When the job finishes processing the execution order
  1483. of the main object is incremented. This system means the no matter how many job threads are
  1484. executing, decoding of an individual sound will always get processed serially. The advantage to
  1485. having multiple threads comes into play when loading multiple sounds at the same time.
  1486. The resource manager's job queue is not 100% lock-free and will use a spinlock to achieve
  1487. thread-safety for a very small section of code. This is only relevant when the resource manager
  1488. uses more than one job thread. If only using a single job thread, which is the default, the
  1489. lock should never actually wait in practice. The amount of time spent locking should be quite
  1490. short, but it's something to be aware of for those who have pedantic lock-free requirements and
  1491. need to use more than one job thread. There are plans to remove this lock in a future version.
  1492. In addition, posting a job will release a semaphore, which on Win32 is implemented with
  1493. `ReleaseSemaphore` and on POSIX platforms via a condition variable:
  1494. ```c
  1495. pthread_mutex_lock(&pSemaphore->lock);
  1496. {
  1497. pSemaphore->value += 1;
  1498. pthread_cond_signal(&pSemaphore->cond);
  1499. }
  1500. pthread_mutex_unlock(&pSemaphore->lock);
  1501. ```
  1502. Again, this is relevant for those with strict lock-free requirements in the audio thread. To avoid
  1503. this, you can use non-blocking mode (via the `MA_JOB_QUEUE_FLAG_NON_BLOCKING`
  1504. flag) and implement your own job processing routine (see the "Resource Manager" section above for
  1505. details on how to do this).
  1506. 6.2.2. Data Buffers
  1507. -------------------
  1508. When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag is excluded at initialization time, the
  1509. resource manager will try to load the data into an in-memory data buffer. Before doing so, however,
  1510. it will first check if the specified file is already loaded. If so, it will increment a reference
  1511. counter and just use the already loaded data. This saves both time and memory. When the data buffer
  1512. is uninitialized, the reference counter will be decremented. If the counter hits zero, the file
  1513. will be unloaded. This is a detail to keep in mind because it could result in excessive loading and
  1514. unloading of a sound. For example, the following sequence will result in a file be loaded twice,
  1515. once after the other:
  1516. ```c
  1517. ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer0); // Refcount = 1. Initial load.
  1518. ma_resource_manager_data_source_uninit(pResourceManager, &myDataBuffer0); // Refcount = 0. Unloaded.
  1519. ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer1); // Refcount = 1. Reloaded because previous uninit() unloaded it.
  1520. ma_resource_manager_data_source_uninit(pResourceManager, &myDataBuffer1); // Refcount = 0. Unloaded.
  1521. ```
  1522. A binary search tree (BST) is used for storing data buffers as it has good balance between
  1523. efficiency and simplicity. The key of the BST is a 64-bit hash of the file path that was passed
  1524. into `ma_resource_manager_data_source_init()`. The advantage of using a hash is that it saves
  1525. memory over storing the entire path, has faster comparisons, and results in a mostly balanced BST
  1526. due to the random nature of the hash. The disadvantages are that file names are case-sensitive and
  1527. there's a small chance of name collisions. If case-sensitivity is an issue, you should normalize
  1528. your file names to upper- or lower-case before initializing your data sources. If name collisions
  1529. become an issue, you'll need to change the name of one of the colliding names or just not use the
  1530. resource manager.
  1531. When a sound file has not already been loaded and the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC`
  1532. flag is excluded, the file will be decoded synchronously by the calling thread. There are two
  1533. options for controlling how the audio is stored in the data buffer - encoded or decoded. When the
  1534. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` option is excluded, the raw file data will be stored
  1535. in memory. Otherwise the sound will be decoded before storing it in memory. Synchronous loading is
  1536. a very simple and standard process of simply adding an item to the BST, allocating a block of
  1537. memory and then decoding (if `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` is specified).
  1538. When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag is specified, loading of the data buffer
  1539. is done asynchronously. In this case, a job is posted to the queue to start loading and then the
  1540. function immediately returns, setting an internal result code to `MA_BUSY`. This result code is
  1541. returned when the program calls `ma_resource_manager_data_source_result()`. When decoding has fully
  1542. completed `MA_SUCCESS` will be returned. This can be used to know if loading has fully completed.
  1543. When loading asynchronously, a single job is posted to the queue of the type
  1544. `MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE`. This involves making a copy of the file path and
  1545. associating it with job. When the job is processed by the job thread, it will first load the file
  1546. using the VFS associated with the resource manager. When using a custom VFS, it's important that it
  1547. be completely thread-safe because it will be used from one or more job threads at the same time.
  1548. Individual files should only ever be accessed by one thread at a time, however. After opening the
  1549. file via the VFS, the job will determine whether or not the file is being decoded. If not, it
  1550. simply allocates a block of memory and loads the raw file contents into it and returns. On the
  1551. other hand, when the file is being decoded, it will first allocate a decoder on the heap and
  1552. initialize it. Then it will check if the length of the file is known. If so it will allocate a
  1553. block of memory to store the decoded output and initialize it to silence. If the size is unknown,
  1554. it will allocate room for one page. After memory has been allocated, the first page will be
  1555. decoded. If the sound is shorter than a page, the result code will be set to `MA_SUCCESS` and the
  1556. completion event will be signalled and loading is now complete. If, however, there is more to
  1557. decode, a job with the code `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` is posted. This job
  1558. will decode the next page and perform the same process if it reaches the end. If there is more to
  1559. decode, the job will post another `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` job which will
  1560. keep on happening until the sound has been fully decoded. For sounds of an unknown length, each
  1561. page will be linked together as a linked list. Internally this is implemented via the
  1562. `ma_paged_audio_buffer` object.
  1563. 6.2.3. Data Streams
  1564. -------------------
  1565. Data streams only ever store two pages worth of data for each instance. They are most useful for
  1566. large sounds like music tracks in games that would consume too much memory if fully decoded in
  1567. memory. After every frame from a page has been read, a job will be posted to load the next page
  1568. which is done from the VFS.
  1569. For data streams, the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag will determine whether or
  1570. not initialization of the data source waits until the two pages have been decoded. When unset,
  1571. `ma_resource_manager_data_source_init()` will wait until the two pages have been loaded, otherwise
  1572. it will return immediately.
  1573. When frames are read from a data stream using `ma_resource_manager_data_source_read_pcm_frames()`,
  1574. `MA_BUSY` will be returned if there are no frames available. If there are some frames available,
  1575. but less than the number requested, `MA_SUCCESS` will be returned, but the actual number of frames
  1576. read will be less than the number requested. Due to the asynchronous nature of data streams,
  1577. seeking is also asynchronous. If the data stream is in the middle of a seek, `MA_BUSY` will be
  1578. returned when trying to read frames.
  1579. When `ma_resource_manager_data_source_read_pcm_frames()` results in a page getting fully consumed
  1580. a job is posted to load the next page. This will be posted from the same thread that called
  1581. `ma_resource_manager_data_source_read_pcm_frames()`.
  1582. Data streams are uninitialized by posting a job to the queue, but the function won't return until
  1583. that job has been processed. The reason for this is that the caller owns the data stream object and
  1584. therefore miniaudio needs to ensure everything completes before handing back control to the caller.
  1585. Also, if the data stream is uninitialized while pages are in the middle of decoding, they must
  1586. complete before destroying any underlying object and the job system handles this cleanly.
  1587. Note that when a new page needs to be loaded, a job will be posted to the resource manager's job
  1588. thread from the audio thread. You must keep in mind the details mentioned in the "Job Queue"
  1589. section above regarding locking when posting an event if you require a strictly lock-free audio
  1590. thread.
  1591. 7. Node Graph
  1592. =============
  1593. miniaudio's routing infrastructure follows a node graph paradigm. The idea is that you create a
  1594. node whose outputs are attached to inputs of another node, thereby creating a graph. There are
  1595. different types of nodes, with each node in the graph processing input data to produce output,
  1596. which is then fed through the chain. Each node in the graph can apply their own custom effects. At
  1597. the start of the graph will usually be one or more data source nodes which have no inputs and
  1598. instead pull their data from a data source. At the end of the graph is an endpoint which represents
  1599. the end of the chain and is where the final output is ultimately extracted from.
  1600. Each node has a number of input buses and a number of output buses. An output bus from a node is
  1601. attached to an input bus of another. Multiple nodes can connect their output buses to another
  1602. node's input bus, in which case their outputs will be mixed before processing by the node. Below is
  1603. a diagram that illustrates a hypothetical node graph setup:
  1604. ```
  1605. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Data flows left to right >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  1606. +---------------+ +-----------------+
  1607. | Data Source 1 =----+ +----------+ +----= Low Pass Filter =----+
  1608. +---------------+ | | =----+ +-----------------+ | +----------+
  1609. +----= Splitter | +----= ENDPOINT |
  1610. +---------------+ | | =----+ +-----------------+ | +----------+
  1611. | Data Source 2 =----+ +----------+ +----= Echo / Delay =----+
  1612. +---------------+ +-----------------+
  1613. ```
  1614. In the above graph, it starts with two data sources whose outputs are attached to the input of a
  1615. splitter node. It's at this point that the two data sources are mixed. After mixing, the splitter
  1616. performs it's processing routine and produces two outputs which is simply a duplication of the
  1617. input stream. One output is attached to a low pass filter, whereas the other output is attached to
  1618. a echo/delay. The outputs of the the low pass filter and the echo are attached to the endpoint, and
  1619. since they're both connected to the same input bus, they'll be mixed.
  1620. Each input bus must be configured to accept the same number of channels, but the number of channels
  1621. used by input buses can be different to the number of channels for output buses in which case
  1622. miniaudio will automatically convert the input data to the output channel count before processing.
  1623. The number of channels of an output bus of one node must match the channel count of the input bus
  1624. it's attached to. The channel counts cannot be changed after the node has been initialized. If you
  1625. attempt to attach an output bus to an input bus with a different channel count, attachment will
  1626. fail.
  1627. To use a node graph, you first need to initialize a `ma_node_graph` object. This is essentially a
  1628. container around the entire graph. The `ma_node_graph` object is required for some thread-safety
  1629. issues which will be explained later. A `ma_node_graph` object is initialized using miniaudio's
  1630. standard config/init system:
  1631. ```c
  1632. ma_node_graph_config nodeGraphConfig = ma_node_graph_config_init(myChannelCount);
  1633. result = ma_node_graph_init(&nodeGraphConfig, NULL, &nodeGraph); // Second parameter is a pointer to allocation callbacks.
  1634. if (result != MA_SUCCESS) {
  1635. // Failed to initialize node graph.
  1636. }
  1637. ```
  1638. When you initialize the node graph, you're specifying the channel count of the endpoint. The
  1639. endpoint is a special node which has one input bus and one output bus, both of which have the
  1640. same channel count, which is specified in the config. Any nodes that connect directly to the
  1641. endpoint must be configured such that their output buses have the same channel count. When you read
  1642. audio data from the node graph, it'll have the channel count you specified in the config. To read
  1643. data from the graph:
  1644. ```c
  1645. ma_uint32 framesRead;
  1646. result = ma_node_graph_read_pcm_frames(&nodeGraph, pFramesOut, frameCount, &framesRead);
  1647. if (result != MA_SUCCESS) {
  1648. // Failed to read data from the node graph.
  1649. }
  1650. ```
  1651. When you read audio data, miniaudio starts at the node graph's endpoint node which then pulls in
  1652. data from it's input attachments, which in turn recursively pull in data from their inputs, and so
  1653. on. At the start of the graph there will be some kind of data source node which will have zero
  1654. inputs and will instead read directly from a data source. The base nodes don't literally need to
  1655. read from a `ma_data_source` object, but they will always have some kind of underlying object that
  1656. sources some kind of audio. The `ma_data_source_node` node can be used to read from a
  1657. `ma_data_source`. Data is always in floating-point format and in the number of channels you
  1658. specified when the graph was initialized. The sample rate is defined by the underlying data sources.
  1659. It's up to you to ensure they use a consistent and appropriate sample rate.
  1660. The `ma_node` API is designed to allow custom nodes to be implemented with relative ease, but
  1661. miniaudio includes a few stock nodes for common functionality. This is how you would initialize a
  1662. node which reads directly from a data source (`ma_data_source_node`) which is an example of one
  1663. of the stock nodes that comes with miniaudio:
  1664. ```c
  1665. ma_data_source_node_config config = ma_data_source_node_config_init(pMyDataSource);
  1666. ma_data_source_node dataSourceNode;
  1667. result = ma_data_source_node_init(&nodeGraph, &config, NULL, &dataSourceNode);
  1668. if (result != MA_SUCCESS) {
  1669. // Failed to create data source node.
  1670. }
  1671. ```
  1672. The data source node will use the output channel count to determine the channel count of the output
  1673. bus. There will be 1 output bus and 0 input buses (data will be drawn directly from the data
  1674. source). The data source must output to floating-point (`ma_format_f32`) or else an error will be
  1675. returned from `ma_data_source_node_init()`.
  1676. By default the node will not be attached to the graph. To do so, use `ma_node_attach_output_bus()`:
  1677. ```c
  1678. result = ma_node_attach_output_bus(&dataSourceNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0);
  1679. if (result != MA_SUCCESS) {
  1680. // Failed to attach node.
  1681. }
  1682. ```
  1683. The code above connects the data source node directly to the endpoint. Since the data source node
  1684. has only a single output bus, the index will always be 0. Likewise, the endpoint only has a single
  1685. input bus which means the input bus index will also always be 0.
  1686. To detach a specific output bus, use `ma_node_detach_output_bus()`. To detach all output buses, use
  1687. `ma_node_detach_all_output_buses()`. If you want to just move the output bus from one attachment to
  1688. another, you do not need to detach first. You can just call `ma_node_attach_output_bus()` and it'll
  1689. deal with it for you.
  1690. Less frequently you may want to create a specialized node. This will be a node where you implement
  1691. your own processing callback to apply a custom effect of some kind. This is similar to initializing
  1692. one of the stock node types, only this time you need to specify a pointer to a vtable containing a
  1693. pointer to the processing function and the number of input and output buses. Example:
  1694. ```c
  1695. static void my_custom_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  1696. {
  1697. // Do some processing of ppFramesIn (one stream of audio data per input bus)
  1698. const float* pFramesIn_0 = ppFramesIn[0]; // Input bus @ index 0.
  1699. const float* pFramesIn_1 = ppFramesIn[1]; // Input bus @ index 1.
  1700. float* pFramesOut_0 = ppFramesOut[0]; // Output bus @ index 0.
  1701. // Do some processing. On input, `pFrameCountIn` will be the number of input frames in each
  1702. // buffer in `ppFramesIn` and `pFrameCountOut` will be the capacity of each of the buffers
  1703. // in `ppFramesOut`. On output, `pFrameCountIn` should be set to the number of input frames
  1704. // your node consumed and `pFrameCountOut` should be set the number of output frames that
  1705. // were produced.
  1706. //
  1707. // You should process as many frames as you can. If your effect consumes input frames at the
  1708. // same rate as output frames (always the case, unless you're doing resampling), you need
  1709. // only look at `ppFramesOut` and process that exact number of frames. If you're doing
  1710. // resampling, you'll need to be sure to set both `pFrameCountIn` and `pFrameCountOut`
  1711. // properly.
  1712. }
  1713. static ma_node_vtable my_custom_node_vtable =
  1714. {
  1715. my_custom_node_process_pcm_frames, // The function that will be called to process your custom node. This is where you'd implement your effect processing.
  1716. NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
  1717. 2, // 2 input buses.
  1718. 1, // 1 output bus.
  1719. 0 // Default flags.
  1720. };
  1721. ...
  1722. // Each bus needs to have a channel count specified. To do this you need to specify the channel
  1723. // counts in an array and then pass that into the node config.
  1724. ma_uint32 inputChannels[2]; // Equal in size to the number of input channels specified in the vtable.
  1725. ma_uint32 outputChannels[1]; // Equal in size to the number of output channels specified in the vtable.
  1726. inputChannels[0] = channelsIn;
  1727. inputChannels[1] = channelsIn;
  1728. outputChannels[0] = channelsOut;
  1729. ma_node_config nodeConfig = ma_node_config_init();
  1730. nodeConfig.vtable = &my_custom_node_vtable;
  1731. nodeConfig.pInputChannels = inputChannels;
  1732. nodeConfig.pOutputChannels = outputChannels;
  1733. ma_node_base node;
  1734. result = ma_node_init(&nodeGraph, &nodeConfig, NULL, &node);
  1735. if (result != MA_SUCCESS) {
  1736. // Failed to initialize node.
  1737. }
  1738. ```
  1739. When initializing a custom node, as in the code above, you'll normally just place your vtable in
  1740. static space. The number of input and output buses are specified as part of the vtable. If you need
  1741. a variable number of buses on a per-node bases, the vtable should have the relevant bus count set
  1742. to `MA_NODE_BUS_COUNT_UNKNOWN`. In this case, the bus count should be set in the node config:
  1743. ```c
  1744. static ma_node_vtable my_custom_node_vtable =
  1745. {
  1746. my_custom_node_process_pcm_frames, // The function that will be called process your custom node. This is where you'd implement your effect processing.
  1747. NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
  1748. MA_NODE_BUS_COUNT_UNKNOWN, // The number of input buses is determined on a per-node basis.
  1749. 1, // 1 output bus.
  1750. 0 // Default flags.
  1751. };
  1752. ...
  1753. ma_node_config nodeConfig = ma_node_config_init();
  1754. nodeConfig.vtable = &my_custom_node_vtable;
  1755. nodeConfig.inputBusCount = myBusCount; // <-- Since the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN, the input bus count should be set here.
  1756. nodeConfig.pInputChannels = inputChannels; // <-- Make sure there are nodeConfig.inputBusCount elements in this array.
  1757. nodeConfig.pOutputChannels = outputChannels; // <-- The vtable specifies 1 output bus, so there must be 1 element in this array.
  1758. ```
  1759. In the above example it's important to never set the `inputBusCount` and `outputBusCount` members
  1760. to anything other than their defaults if the vtable specifies an explicit count. They can only be
  1761. set if the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN in the relevant bus count.
  1762. Most often you'll want to create a structure to encapsulate your node with some extra data. You
  1763. need to make sure the `ma_node_base` object is your first member of the structure:
  1764. ```c
  1765. typedef struct
  1766. {
  1767. ma_node_base base; // <-- Make sure this is always the first member.
  1768. float someCustomData;
  1769. } my_custom_node;
  1770. ```
  1771. By doing this, your object will be compatible with all `ma_node` APIs and you can attach it to the
  1772. graph just like any other node.
  1773. In the custom processing callback (`my_custom_node_process_pcm_frames()` in the example above), the
  1774. number of channels for each bus is what was specified by the config when the node was initialized
  1775. with `ma_node_init()`. In addition, all attachments to each of the input buses will have been
  1776. pre-mixed by miniaudio. The config allows you to specify different channel counts for each
  1777. individual input and output bus. It's up to the effect to handle it appropriate, and if it can't,
  1778. return an error in it's initialization routine.
  1779. Custom nodes can be assigned some flags to describe their behaviour. These are set via the vtable
  1780. and include the following:
  1781. +-----------------------------------------+---------------------------------------------------+
  1782. | Flag Name | Description |
  1783. +-----------------------------------------+---------------------------------------------------+
  1784. | MA_NODE_FLAG_PASSTHROUGH | Useful for nodes that do not do any kind of audio |
  1785. | | processing, but are instead used for tracking |
  1786. | | time, handling events, etc. Also used by the |
  1787. | | internal endpoint node. It reads directly from |
  1788. | | the input bus to the output bus. Nodes with this |
  1789. | | flag must have exactly 1 input bus and 1 output |
  1790. | | bus, and both buses must have the same channel |
  1791. | | counts. |
  1792. +-----------------------------------------+---------------------------------------------------+
  1793. | MA_NODE_FLAG_CONTINUOUS_PROCESSING | Causes the processing callback to be called even |
  1794. | | when no data is available to be read from input |
  1795. | | attachments. When a node has at least one input |
  1796. | | bus, but there are no inputs attached or the |
  1797. | | inputs do not deliver any data, the node's |
  1798. | | processing callback will not get fired. This flag |
  1799. | | will make it so the callback is always fired |
  1800. | | regardless of whether or not any input data is |
  1801. | | received. This is useful for effects like |
  1802. | | echos where there will be a tail of audio data |
  1803. | | that still needs to be processed even when the |
  1804. | | original data sources have reached their ends. It |
  1805. | | may also be useful for nodes that must always |
  1806. | | have their processing callback fired when there |
  1807. | | are no inputs attached. |
  1808. +-----------------------------------------+---------------------------------------------------+
  1809. | MA_NODE_FLAG_ALLOW_NULL_INPUT | Used in conjunction with |
  1810. | | `MA_NODE_FLAG_CONTINUOUS_PROCESSING`. When this |
  1811. | | is set, the `ppFramesIn` parameter of the |
  1812. | | processing callback will be set to NULL when |
  1813. | | there are no input frames are available. When |
  1814. | | this is unset, silence will be posted to the |
  1815. | | processing callback. |
  1816. +-----------------------------------------+---------------------------------------------------+
  1817. | MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES | Used to tell miniaudio that input and output |
  1818. | | frames are processed at different rates. You |
  1819. | | should set this for any nodes that perform |
  1820. | | resampling. |
  1821. +-----------------------------------------+---------------------------------------------------+
  1822. | MA_NODE_FLAG_SILENT_OUTPUT | Used to tell miniaudio that a node produces only |
  1823. | | silent output. This is useful for nodes where you |
  1824. | | don't want the output to contribute to the final |
  1825. | | mix. An example might be if you want split your |
  1826. | | stream and have one branch be output to a file. |
  1827. | | When using this flag, you should avoid writing to |
  1828. | | the output buffer of the node's processing |
  1829. | | callback because miniaudio will ignore it anyway. |
  1830. +-----------------------------------------+---------------------------------------------------+
  1831. If you need to make a copy of an audio stream for effect processing you can use a splitter node
  1832. called `ma_splitter_node`. This takes has 1 input bus and splits the stream into 2 output buses.
  1833. You can use it like this:
  1834. ```c
  1835. ma_splitter_node_config splitterNodeConfig = ma_splitter_node_config_init(channels);
  1836. ma_splitter_node splitterNode;
  1837. result = ma_splitter_node_init(&nodeGraph, &splitterNodeConfig, NULL, &splitterNode);
  1838. if (result != MA_SUCCESS) {
  1839. // Failed to create node.
  1840. }
  1841. // Attach your output buses to two different input buses (can be on two different nodes).
  1842. ma_node_attach_output_bus(&splitterNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0); // Attach directly to the endpoint.
  1843. ma_node_attach_output_bus(&splitterNode, 1, &myEffectNode, 0); // Attach to input bus 0 of some effect node.
  1844. ```
  1845. The volume of an output bus can be configured on a per-bus basis:
  1846. ```c
  1847. ma_node_set_output_bus_volume(&splitterNode, 0, 0.5f);
  1848. ma_node_set_output_bus_volume(&splitterNode, 1, 0.5f);
  1849. ```
  1850. In the code above we're using the splitter node from before and changing the volume of each of the
  1851. copied streams.
  1852. You can start and stop a node with the following:
  1853. ```c
  1854. ma_node_set_state(&splitterNode, ma_node_state_started); // The default state.
  1855. ma_node_set_state(&splitterNode, ma_node_state_stopped);
  1856. ```
  1857. By default the node is in a started state, but since it won't be connected to anything won't
  1858. actually be invoked by the node graph until it's connected. When you stop a node, data will not be
  1859. read from any of it's input connections. You can use this property to stop a group of sounds
  1860. atomically.
  1861. You can configure the initial state of a node in it's config:
  1862. ```c
  1863. nodeConfig.initialState = ma_node_state_stopped;
  1864. ```
  1865. Note that for the stock specialized nodes, all of their configs will have a `nodeConfig` member
  1866. which is the config to use with the base node. This is where the initial state can be configured
  1867. for specialized nodes:
  1868. ```c
  1869. dataSourceNodeConfig.nodeConfig.initialState = ma_node_state_stopped;
  1870. ```
  1871. When using a specialized node like `ma_data_source_node` or `ma_splitter_node`, be sure to not
  1872. modify the `vtable` member of the `nodeConfig` object.
  1873. 7.1. Timing
  1874. -----------
  1875. The node graph supports starting and stopping nodes at scheduled times. This is especially useful
  1876. for data source nodes where you want to get the node set up, but only start playback at a specific
  1877. time. There are two clocks: local and global.
  1878. A local clock is per-node, whereas the global clock is per graph. Scheduling starts and stops can
  1879. only be done based on the global clock because the local clock will not be running while the node
  1880. is stopped. The global clocks advances whenever `ma_node_graph_read_pcm_frames()` is called. On the
  1881. other hand, the local clock only advances when the node's processing callback is fired, and is
  1882. advanced based on the output frame count.
  1883. To retrieve the global time, use `ma_node_graph_get_time()`. The global time can be set with
  1884. `ma_node_graph_set_time()` which might be useful if you want to do seeking on a global timeline.
  1885. Getting and setting the local time is similar. Use `ma_node_get_time()` to retrieve the local time,
  1886. and `ma_node_set_time()` to set the local time. The global and local times will be advanced by the
  1887. audio thread, so care should be taken to avoid data races. Ideally you should avoid calling these
  1888. outside of the node processing callbacks which are always run on the audio thread.
  1889. There is basic support for scheduling the starting and stopping of nodes. You can only schedule one
  1890. start and one stop at a time. This is mainly intended for putting nodes into a started or stopped
  1891. state in a frame-exact manner. Without this mechanism, starting and stopping of a node is limited
  1892. to the resolution of a call to `ma_node_graph_read_pcm_frames()` which would typically be in blocks
  1893. of several milliseconds. The following APIs can be used for scheduling node states:
  1894. ```c
  1895. ma_node_set_state_time()
  1896. ma_node_get_state_time()
  1897. ```
  1898. The time is absolute and must be based on the global clock. An example is below:
  1899. ```c
  1900. ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1); // Delay starting to 1 second.
  1901. ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5); // Delay stopping to 5 seconds.
  1902. ```
  1903. An example for changing the state using a relative time.
  1904. ```c
  1905. ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1 + ma_node_graph_get_time(&myNodeGraph));
  1906. ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5 + ma_node_graph_get_time(&myNodeGraph));
  1907. ```
  1908. Note that due to the nature of multi-threading the times may not be 100% exact. If this is an
  1909. issue, consider scheduling state changes from within a processing callback. An idea might be to
  1910. have some kind of passthrough trigger node that is used specifically for tracking time and handling
  1911. events.
  1912. 7.2. Thread Safety and Locking
  1913. ------------------------------
  1914. When processing audio, it's ideal not to have any kind of locking in the audio thread. Since it's
  1915. expected that `ma_node_graph_read_pcm_frames()` would be run on the audio thread, it does so
  1916. without the use of any locks. This section discusses the implementation used by miniaudio and goes
  1917. over some of the compromises employed by miniaudio to achieve this goal. Note that the current
  1918. implementation may not be ideal - feedback and critiques are most welcome.
  1919. The node graph API is not *entirely* lock-free. Only `ma_node_graph_read_pcm_frames()` is expected
  1920. to be lock-free. Attachment, detachment and uninitialization of nodes use locks to simplify the
  1921. implementation, but are crafted in a way such that such locking is not required when reading audio
  1922. data from the graph. Locking in these areas are achieved by means of spinlocks.
  1923. The main complication with keeping `ma_node_graph_read_pcm_frames()` lock-free stems from the fact
  1924. that a node can be uninitialized, and it's memory potentially freed, while in the middle of being
  1925. processed on the audio thread. There are times when the audio thread will be referencing a node,
  1926. which means the uninitialization process of a node needs to make sure it delays returning until the
  1927. audio thread is finished so that control is not handed back to the caller thereby giving them a
  1928. chance to free the node's memory.
  1929. When the audio thread is processing a node, it does so by reading from each of the output buses of
  1930. the node. In order for a node to process data for one of it's output buses, it needs to read from
  1931. each of it's input buses, and so on an so forth. It follows that once all output buses of a node
  1932. are detached, the node as a whole will be disconnected and no further processing will occur unless
  1933. it's output buses are reattached, which won't be happening when the node is being uninitialized.
  1934. By having `ma_node_detach_output_bus()` wait until the audio thread is finished with it, we can
  1935. simplify a few things, at the expense of making `ma_node_detach_output_bus()` a bit slower. By
  1936. doing this, the implementation of `ma_node_uninit()` becomes trivial - just detach all output
  1937. nodes, followed by each of the attachments to each of it's input nodes, and then do any final clean
  1938. up.
  1939. With the above design, the worst-case scenario is `ma_node_detach_output_bus()` taking as long as
  1940. it takes to process the output bus being detached. This will happen if it's called at just the
  1941. wrong moment where the audio thread has just iterated it and has just started processing. The
  1942. caller of `ma_node_detach_output_bus()` will stall until the audio thread is finished, which
  1943. includes the cost of recursively processing it's inputs. This is the biggest compromise made with
  1944. the approach taken by miniaudio for it's lock-free processing system. The cost of detaching nodes
  1945. earlier in the pipeline (data sources, for example) will be cheaper than the cost of detaching
  1946. higher level nodes, such as some kind of final post-processing endpoint. If you need to do mass
  1947. detachments, detach starting from the lowest level nodes and work your way towards the final
  1948. endpoint node (but don't try detaching the node graph's endpoint). If the audio thread is not
  1949. running, detachment will be fast and detachment in any order will be the same. The reason nodes
  1950. need to wait for their input attachments to complete is due to the potential for desyncs between
  1951. data sources. If the node was to terminate processing mid way through processing it's inputs,
  1952. there's a chance that some of the underlying data sources will have been read, but then others not.
  1953. That will then result in a potential desynchronization when detaching and reattaching higher-level
  1954. nodes. A possible solution to this is to have an option when detaching to terminate processing
  1955. before processing all input attachments which should be fairly simple.
  1956. Another compromise, albeit less significant, is locking when attaching and detaching nodes. This
  1957. locking is achieved by means of a spinlock in order to reduce memory overhead. A lock is present
  1958. for each input bus and output bus. When an output bus is connected to an input bus, both the output
  1959. bus and input bus is locked. This locking is specifically for attaching and detaching across
  1960. different threads and does not affect `ma_node_graph_read_pcm_frames()` in any way. The locking and
  1961. unlocking is mostly self-explanatory, but a slightly less intuitive aspect comes into it when
  1962. considering that iterating over attachments must not break as a result of attaching or detaching a
  1963. node while iteration is occurring.
  1964. Attaching and detaching are both quite simple. When an output bus of a node is attached to an input
  1965. bus of another node, it's added to a linked list. Basically, an input bus is a linked list, where
  1966. each item in the list is and output bus. We have some intentional (and convenient) restrictions on
  1967. what can done with the linked list in order to simplify the implementation. First of all, whenever
  1968. something needs to iterate over the list, it must do so in a forward direction. Backwards iteration
  1969. is not supported. Also, items can only be added to the start of the list.
  1970. The linked list is a doubly-linked list where each item in the list (an output bus) holds a pointer
  1971. to the next item in the list, and another to the previous item. A pointer to the previous item is
  1972. only required for fast detachment of the node - it is never used in iteration. This is an
  1973. important property because it means from the perspective of iteration, attaching and detaching of
  1974. an item can be done with a single atomic assignment. This is exploited by both the attachment and
  1975. detachment process. When attaching the node, the first thing that is done is the setting of the
  1976. local "next" and "previous" pointers of the node. After that, the item is "attached" to the list
  1977. by simply performing an atomic exchange with the head pointer. After that, the node is "attached"
  1978. to the list from the perspective of iteration. Even though the "previous" pointer of the next item
  1979. hasn't yet been set, from the perspective of iteration it's been attached because iteration will
  1980. only be happening in a forward direction which means the "previous" pointer won't actually ever get
  1981. used. The same general process applies to detachment. See `ma_node_attach_output_bus()` and
  1982. `ma_node_detach_output_bus()` for the implementation of this mechanism.
  1983. 8. Decoding
  1984. ===========
  1985. The `ma_decoder` API is used for reading audio files. Decoders are completely decoupled from
  1986. devices and can be used independently. The following formats are supported:
  1987. +---------+------------------+----------+
  1988. | Format | Decoding Backend | Built-In |
  1989. +---------+------------------+----------+
  1990. | WAV | dr_wav | Yes |
  1991. | MP3 | dr_mp3 | Yes |
  1992. | FLAC | dr_flac | Yes |
  1993. | Vorbis | stb_vorbis | No |
  1994. +---------+------------------+----------+
  1995. Vorbis is supported via stb_vorbis which can be enabled by including the header section before the
  1996. implementation of miniaudio, like the following:
  1997. ```c
  1998. #define STB_VORBIS_HEADER_ONLY
  1999. #include "extras/stb_vorbis.c" // Enables Vorbis decoding.
  2000. #define MINIAUDIO_IMPLEMENTATION
  2001. #include "miniaudio.h"
  2002. // The stb_vorbis implementation must come after the implementation of miniaudio.
  2003. #undef STB_VORBIS_HEADER_ONLY
  2004. #include "extras/stb_vorbis.c"
  2005. ```
  2006. A copy of stb_vorbis is included in the "extras" folder in the miniaudio repository (https://github.com/mackron/miniaudio).
  2007. Built-in decoders are amalgamated into the implementation section of miniaudio. You can disable the
  2008. built-in decoders by specifying one or more of the following options before the miniaudio
  2009. implementation:
  2010. ```c
  2011. #define MA_NO_WAV
  2012. #define MA_NO_MP3
  2013. #define MA_NO_FLAC
  2014. ```
  2015. Disabling built-in decoding libraries is useful if you use these libraries independently of the
  2016. `ma_decoder` API.
  2017. A decoder can be initialized from a file with `ma_decoder_init_file()`, a block of memory with
  2018. `ma_decoder_init_memory()`, or from data delivered via callbacks with `ma_decoder_init()`. Here is
  2019. an example for loading a decoder from a file:
  2020. ```c
  2021. ma_decoder decoder;
  2022. ma_result result = ma_decoder_init_file("MySong.mp3", NULL, &decoder);
  2023. if (result != MA_SUCCESS) {
  2024. return false; // An error occurred.
  2025. }
  2026. ...
  2027. ma_decoder_uninit(&decoder);
  2028. ```
  2029. When initializing a decoder, you can optionally pass in a pointer to a `ma_decoder_config` object
  2030. (the `NULL` argument in the example above) which allows you to configure the output format, channel
  2031. count, sample rate and channel map:
  2032. ```c
  2033. ma_decoder_config config = ma_decoder_config_init(ma_format_f32, 2, 48000);
  2034. ```
  2035. When passing in `NULL` for decoder config in `ma_decoder_init*()`, the output format will be the
  2036. same as that defined by the decoding backend.
  2037. Data is read from the decoder as PCM frames. This will output the number of PCM frames actually
  2038. read. If this is less than the requested number of PCM frames it means you've reached the end. The
  2039. return value will be `MA_AT_END` if no samples have been read and the end has been reached.
  2040. ```c
  2041. ma_result result = ma_decoder_read_pcm_frames(pDecoder, pFrames, framesToRead, &framesRead);
  2042. if (framesRead < framesToRead) {
  2043. // Reached the end.
  2044. }
  2045. ```
  2046. You can also seek to a specific frame like so:
  2047. ```c
  2048. ma_result result = ma_decoder_seek_to_pcm_frame(pDecoder, targetFrame);
  2049. if (result != MA_SUCCESS) {
  2050. return false; // An error occurred.
  2051. }
  2052. ```
  2053. If you want to loop back to the start, you can simply seek back to the first PCM frame:
  2054. ```c
  2055. ma_decoder_seek_to_pcm_frame(pDecoder, 0);
  2056. ```
  2057. When loading a decoder, miniaudio uses a trial and error technique to find the appropriate decoding
  2058. backend. This can be unnecessarily inefficient if the type is already known. In this case you can
  2059. use `encodingFormat` variable in the device config to specify a specific encoding format you want
  2060. to decode:
  2061. ```c
  2062. decoderConfig.encodingFormat = ma_encoding_format_wav;
  2063. ```
  2064. See the `ma_encoding_format` enum for possible encoding formats.
  2065. The `ma_decoder_init_file()` API will try using the file extension to determine which decoding
  2066. backend to prefer.
  2067. 8.1. Custom Decoders
  2068. --------------------
  2069. It's possible to implement a custom decoder and plug it into miniaudio. This is extremely useful
  2070. when you want to use the `ma_decoder` API, but need to support an encoding format that's not one of
  2071. the stock formats supported by miniaudio. This can be put to particularly good use when using the
  2072. `ma_engine` and/or `ma_resource_manager` APIs because they use `ma_decoder` internally. If, for
  2073. example, you wanted to support Opus, you can do so with a custom decoder (there if a reference
  2074. Opus decoder in the "extras" folder of the miniaudio repository which uses libopus + libopusfile).
  2075. A custom decoder must implement a data source. A vtable called `ma_decoding_backend_vtable` needs
  2076. to be implemented which is then passed into the decoder config:
  2077. ```c
  2078. ma_decoding_backend_vtable* pCustomBackendVTables[] =
  2079. {
  2080. &g_ma_decoding_backend_vtable_libvorbis,
  2081. &g_ma_decoding_backend_vtable_libopus
  2082. };
  2083. ...
  2084. decoderConfig = ma_decoder_config_init_default();
  2085. decoderConfig.pCustomBackendUserData = NULL;
  2086. decoderConfig.ppCustomBackendVTables = pCustomBackendVTables;
  2087. decoderConfig.customBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
  2088. ```
  2089. The `ma_decoding_backend_vtable` vtable has the following functions:
  2090. ```
  2091. onInit
  2092. onInitFile
  2093. onInitFileW
  2094. onInitMemory
  2095. onUninit
  2096. ```
  2097. There are only two functions that must be implemented - `onInit` and `onUninit`. The other
  2098. functions can be implemented for a small optimization for loading from a file path or memory. If
  2099. these are not specified, miniaudio will deal with it for you via a generic implementation.
  2100. When you initialize a custom data source (by implementing the `onInit` function in the vtable) you
  2101. will need to output a pointer to a `ma_data_source` which implements your custom decoder. See the
  2102. section about data sources for details on how to implement this. Alternatively, see the
  2103. "custom_decoders" example in the miniaudio repository.
  2104. The `onInit` function takes a pointer to some callbacks for the purpose of reading raw audio data
  2105. from some arbitrary source. You'll use these functions to read from the raw data and perform the
  2106. decoding. When you call them, you will pass in the `pReadSeekTellUserData` pointer to the relevant
  2107. parameter.
  2108. The `pConfig` parameter in `onInit` can be used to configure the backend if appropriate. It's only
  2109. used as a hint and can be ignored. However, if any of the properties are relevant to your decoder,
  2110. an optimal implementation will handle the relevant properties appropriately.
  2111. If memory allocation is required, it should be done so via the specified allocation callbacks if
  2112. possible (the `pAllocationCallbacks` parameter).
  2113. If an error occurs when initializing the decoder, you should leave `ppBackend` unset, or set to
  2114. NULL, and make sure everything is cleaned up appropriately and an appropriate result code returned.
  2115. When multiple custom backends are specified, miniaudio will cycle through the vtables in the order
  2116. they're listed in the array that's passed into the decoder config so it's important that your
  2117. initialization routine is clean.
  2118. When a decoder is uninitialized, the `onUninit` callback will be fired which will give you an
  2119. opportunity to clean up and internal data.
  2120. 9. Encoding
  2121. ===========
  2122. The `ma_encoding` API is used for writing audio files. The only supported output format is WAV
  2123. which is achieved via dr_wav which is amalgamated into the implementation section of miniaudio.
  2124. This can be disabled by specifying the following option before the implementation of miniaudio:
  2125. ```c
  2126. #define MA_NO_WAV
  2127. ```
  2128. An encoder can be initialized to write to a file with `ma_encoder_init_file()` or from data
  2129. delivered via callbacks with `ma_encoder_init()`. Below is an example for initializing an encoder
  2130. to output to a file.
  2131. ```c
  2132. ma_encoder_config config = ma_encoder_config_init(ma_encoding_format_wav, FORMAT, CHANNELS, SAMPLE_RATE);
  2133. ma_encoder encoder;
  2134. ma_result result = ma_encoder_init_file("my_file.wav", &config, &encoder);
  2135. if (result != MA_SUCCESS) {
  2136. // Error
  2137. }
  2138. ...
  2139. ma_encoder_uninit(&encoder);
  2140. ```
  2141. When initializing an encoder you must specify a config which is initialized with
  2142. `ma_encoder_config_init()`. Here you must specify the file type, the output sample format, output
  2143. channel count and output sample rate. The following file types are supported:
  2144. +------------------------+-------------+
  2145. | Enum | Description |
  2146. +------------------------+-------------+
  2147. | ma_encoding_format_wav | WAV |
  2148. +------------------------+-------------+
  2149. If the format, channel count or sample rate is not supported by the output file type an error will
  2150. be returned. The encoder will not perform data conversion so you will need to convert it before
  2151. outputting any audio data. To output audio data, use `ma_encoder_write_pcm_frames()`, like in the
  2152. example below:
  2153. ```c
  2154. framesWritten = ma_encoder_write_pcm_frames(&encoder, pPCMFramesToWrite, framesToWrite);
  2155. ```
  2156. Encoders must be uninitialized with `ma_encoder_uninit()`.
  2157. 10. Data Conversion
  2158. ===================
  2159. A data conversion API is included with miniaudio which supports the majority of data conversion
  2160. requirements. This supports conversion between sample formats, channel counts (with channel
  2161. mapping) and sample rates.
  2162. 10.1. Sample Format Conversion
  2163. ------------------------------
  2164. Conversion between sample formats is achieved with the `ma_pcm_*_to_*()`, `ma_pcm_convert()` and
  2165. `ma_convert_pcm_frames_format()` APIs. Use `ma_pcm_*_to_*()` to convert between two specific
  2166. formats. Use `ma_pcm_convert()` to convert based on a `ma_format` variable. Use
  2167. `ma_convert_pcm_frames_format()` to convert PCM frames where you want to specify the frame count
  2168. and channel count as a variable instead of the total sample count.
  2169. 10.1.1. Dithering
  2170. -----------------
  2171. Dithering can be set using the ditherMode parameter.
  2172. The different dithering modes include the following, in order of efficiency:
  2173. +-----------+--------------------------+
  2174. | Type | Enum Token |
  2175. +-----------+--------------------------+
  2176. | None | ma_dither_mode_none |
  2177. | Rectangle | ma_dither_mode_rectangle |
  2178. | Triangle | ma_dither_mode_triangle |
  2179. +-----------+--------------------------+
  2180. Note that even if the dither mode is set to something other than `ma_dither_mode_none`, it will be
  2181. ignored for conversions where dithering is not needed. Dithering is available for the following
  2182. conversions:
  2183. ```
  2184. s16 -> u8
  2185. s24 -> u8
  2186. s32 -> u8
  2187. f32 -> u8
  2188. s24 -> s16
  2189. s32 -> s16
  2190. f32 -> s16
  2191. ```
  2192. Note that it is not an error to pass something other than ma_dither_mode_none for conversions where
  2193. dither is not used. It will just be ignored.
  2194. 10.2. Channel Conversion
  2195. ------------------------
  2196. Channel conversion is used for channel rearrangement and conversion from one channel count to
  2197. another. The `ma_channel_converter` API is used for channel conversion. Below is an example of
  2198. initializing a simple channel converter which converts from mono to stereo.
  2199. ```c
  2200. ma_channel_converter_config config = ma_channel_converter_config_init(
  2201. ma_format, // Sample format
  2202. 1, // Input channels
  2203. NULL, // Input channel map
  2204. 2, // Output channels
  2205. NULL, // Output channel map
  2206. ma_channel_mix_mode_default); // The mixing algorithm to use when combining channels.
  2207. result = ma_channel_converter_init(&config, NULL, &converter);
  2208. if (result != MA_SUCCESS) {
  2209. // Error.
  2210. }
  2211. ```
  2212. To perform the conversion simply call `ma_channel_converter_process_pcm_frames()` like so:
  2213. ```c
  2214. ma_result result = ma_channel_converter_process_pcm_frames(&converter, pFramesOut, pFramesIn, frameCount);
  2215. if (result != MA_SUCCESS) {
  2216. // Error.
  2217. }
  2218. ```
  2219. It is up to the caller to ensure the output buffer is large enough to accommodate the new PCM
  2220. frames.
  2221. Input and output PCM frames are always interleaved. Deinterleaved layouts are not supported.
  2222. 10.2.1. Channel Mapping
  2223. -----------------------
  2224. In addition to converting from one channel count to another, like the example above, the channel
  2225. converter can also be used to rearrange channels. When initializing the channel converter, you can
  2226. optionally pass in channel maps for both the input and output frames. If the channel counts are the
  2227. same, and each channel map contains the same channel positions with the exception that they're in
  2228. a different order, a simple shuffling of the channels will be performed. If, however, there is not
  2229. a 1:1 mapping of channel positions, or the channel counts differ, the input channels will be mixed
  2230. based on a mixing mode which is specified when initializing the `ma_channel_converter_config`
  2231. object.
  2232. When converting from mono to multi-channel, the mono channel is simply copied to each output
  2233. channel. When going the other way around, the audio of each output channel is simply averaged and
  2234. copied to the mono channel.
  2235. In more complicated cases blending is used. The `ma_channel_mix_mode_simple` mode will drop excess
  2236. channels and silence extra channels. For example, converting from 4 to 2 channels, the 3rd and 4th
  2237. channels will be dropped, whereas converting from 2 to 4 channels will put silence into the 3rd and
  2238. 4th channels.
  2239. The `ma_channel_mix_mode_rectangle` mode uses spacial locality based on a rectangle to compute a
  2240. simple distribution between input and output. Imagine sitting in the middle of a room, with
  2241. speakers on the walls representing channel positions. The `MA_CHANNEL_FRONT_LEFT` position can be
  2242. thought of as being in the corner of the front and left walls.
  2243. Finally, the `ma_channel_mix_mode_custom_weights` mode can be used to use custom user-defined
  2244. weights. Custom weights can be passed in as the last parameter of
  2245. `ma_channel_converter_config_init()`.
  2246. Predefined channel maps can be retrieved with `ma_channel_map_init_standard()`. This takes a
  2247. `ma_standard_channel_map` enum as it's first parameter, which can be one of the following:
  2248. +-----------------------------------+-----------------------------------------------------------+
  2249. | Name | Description |
  2250. +-----------------------------------+-----------------------------------------------------------+
  2251. | ma_standard_channel_map_default | Default channel map used by miniaudio. See below. |
  2252. | ma_standard_channel_map_microsoft | Channel map used by Microsoft's bitfield channel maps. |
  2253. | ma_standard_channel_map_alsa | Default ALSA channel map. |
  2254. | ma_standard_channel_map_rfc3551 | RFC 3551. Based on AIFF. |
  2255. | ma_standard_channel_map_flac | FLAC channel map. |
  2256. | ma_standard_channel_map_vorbis | Vorbis channel map. |
  2257. | ma_standard_channel_map_sound4 | FreeBSD's sound(4). |
  2258. | ma_standard_channel_map_sndio | sndio channel map. http://www.sndio.org/tips.html. |
  2259. | ma_standard_channel_map_webaudio | https://webaudio.github.io/web-audio-api/#ChannelOrdering |
  2260. +-----------------------------------+-----------------------------------------------------------+
  2261. Below are the channel maps used by default in miniaudio (`ma_standard_channel_map_default`):
  2262. +---------------+---------------------------------+
  2263. | Channel Count | Mapping |
  2264. +---------------+---------------------------------+
  2265. | 1 (Mono) | 0: MA_CHANNEL_MONO |
  2266. +---------------+---------------------------------+
  2267. | 2 (Stereo) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2268. | | 1: MA_CHANNEL_FRONT_RIGHT |
  2269. +---------------+---------------------------------+
  2270. | 3 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2271. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2272. | | 2: MA_CHANNEL_FRONT_CENTER |
  2273. +---------------+---------------------------------+
  2274. | 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2275. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2276. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2277. | | 3: MA_CHANNEL_BACK_CENTER |
  2278. +---------------+---------------------------------+
  2279. | 5 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2280. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2281. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2282. | | 3: MA_CHANNEL_BACK_LEFT <br> |
  2283. | | 4: MA_CHANNEL_BACK_RIGHT |
  2284. +---------------+---------------------------------+
  2285. | 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2286. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2287. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2288. | | 3: MA_CHANNEL_LFE <br> |
  2289. | | 4: MA_CHANNEL_SIDE_LEFT <br> |
  2290. | | 5: MA_CHANNEL_SIDE_RIGHT |
  2291. +---------------+---------------------------------+
  2292. | 7 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2293. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2294. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2295. | | 3: MA_CHANNEL_LFE <br> |
  2296. | | 4: MA_CHANNEL_BACK_CENTER <br> |
  2297. | | 4: MA_CHANNEL_SIDE_LEFT <br> |
  2298. | | 5: MA_CHANNEL_SIDE_RIGHT |
  2299. +---------------+---------------------------------+
  2300. | 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2301. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2302. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2303. | | 3: MA_CHANNEL_LFE <br> |
  2304. | | 4: MA_CHANNEL_BACK_LEFT <br> |
  2305. | | 5: MA_CHANNEL_BACK_RIGHT <br> |
  2306. | | 6: MA_CHANNEL_SIDE_LEFT <br> |
  2307. | | 7: MA_CHANNEL_SIDE_RIGHT |
  2308. +---------------+---------------------------------+
  2309. | Other | All channels set to 0. This |
  2310. | | is equivalent to the same |
  2311. | | mapping as the device. |
  2312. +---------------+---------------------------------+
  2313. 10.3. Resampling
  2314. ----------------
  2315. Resampling is achieved with the `ma_resampler` object. To create a resampler object, do something
  2316. like the following:
  2317. ```c
  2318. ma_resampler_config config = ma_resampler_config_init(
  2319. ma_format_s16,
  2320. channels,
  2321. sampleRateIn,
  2322. sampleRateOut,
  2323. ma_resample_algorithm_linear);
  2324. ma_resampler resampler;
  2325. ma_result result = ma_resampler_init(&config, &resampler);
  2326. if (result != MA_SUCCESS) {
  2327. // An error occurred...
  2328. }
  2329. ```
  2330. Do the following to uninitialize the resampler:
  2331. ```c
  2332. ma_resampler_uninit(&resampler);
  2333. ```
  2334. The following example shows how data can be processed
  2335. ```c
  2336. ma_uint64 frameCountIn = 1000;
  2337. ma_uint64 frameCountOut = 2000;
  2338. ma_result result = ma_resampler_process_pcm_frames(&resampler, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
  2339. if (result != MA_SUCCESS) {
  2340. // An error occurred...
  2341. }
  2342. // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the
  2343. // number of output frames written.
  2344. ```
  2345. To initialize the resampler you first need to set up a config (`ma_resampler_config`) with
  2346. `ma_resampler_config_init()`. You need to specify the sample format you want to use, the number of
  2347. channels, the input and output sample rate, and the algorithm.
  2348. The sample format can be either `ma_format_s16` or `ma_format_f32`. If you need a different format
  2349. you will need to perform pre- and post-conversions yourself where necessary. Note that the format
  2350. is the same for both input and output. The format cannot be changed after initialization.
  2351. The resampler supports multiple channels and is always interleaved (both input and output). The
  2352. channel count cannot be changed after initialization.
  2353. The sample rates can be anything other than zero, and are always specified in hertz. They should be
  2354. set to something like 44100, etc. The sample rate is the only configuration property that can be
  2355. changed after initialization.
  2356. The miniaudio resampler has built-in support for the following algorithms:
  2357. +-----------+------------------------------+
  2358. | Algorithm | Enum Token |
  2359. +-----------+------------------------------+
  2360. | Linear | ma_resample_algorithm_linear |
  2361. | Custom | ma_resample_algorithm_custom |
  2362. +-----------+------------------------------+
  2363. The algorithm cannot be changed after initialization.
  2364. Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
  2365. De-interleaved processing is not supported. To process frames, use
  2366. `ma_resampler_process_pcm_frames()`. On input, this function takes the number of output frames you
  2367. can fit in the output buffer and the number of input frames contained in the input buffer. On
  2368. output these variables contain the number of output frames that were written to the output buffer
  2369. and the number of input frames that were consumed in the process. You can pass in NULL for the
  2370. input buffer in which case it will be treated as an infinitely large buffer of zeros. The output
  2371. buffer can also be NULL, in which case the processing will be treated as seek.
  2372. The sample rate can be changed dynamically on the fly. You can change this with explicit sample
  2373. rates with `ma_resampler_set_rate()` and also with a decimal ratio with
  2374. `ma_resampler_set_rate_ratio()`. The ratio is in/out.
  2375. Sometimes it's useful to know exactly how many input frames will be required to output a specific
  2376. number of frames. You can calculate this with `ma_resampler_get_required_input_frame_count()`.
  2377. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
  2378. number of input frames. You can do this with `ma_resampler_get_expected_output_frame_count()`.
  2379. Due to the nature of how resampling works, the resampler introduces some latency. This can be
  2380. retrieved in terms of both the input rate and the output rate with
  2381. `ma_resampler_get_input_latency()` and `ma_resampler_get_output_latency()`.
  2382. 10.3.1. Resampling Algorithms
  2383. -----------------------------
  2384. The choice of resampling algorithm depends on your situation and requirements.
  2385. 10.3.1.1. Linear Resampling
  2386. ---------------------------
  2387. The linear resampler is the fastest, but comes at the expense of poorer quality. There is, however,
  2388. some control over the quality of the linear resampler which may make it a suitable option depending
  2389. on your requirements.
  2390. The linear resampler performs low-pass filtering before or after downsampling or upsampling,
  2391. depending on the sample rates you're converting between. When decreasing the sample rate, the
  2392. low-pass filter will be applied before downsampling. When increasing the rate it will be performed
  2393. after upsampling. By default a fourth order low-pass filter will be applied. This can be configured
  2394. via the `lpfOrder` configuration variable. Setting this to 0 will disable filtering.
  2395. The low-pass filter has a cutoff frequency which defaults to half the sample rate of the lowest of
  2396. the input and output sample rates (Nyquist Frequency).
  2397. The API for the linear resampler is the same as the main resampler API, only it's called
  2398. `ma_linear_resampler`.
  2399. 10.3.2. Custom Resamplers
  2400. -------------------------
  2401. You can implement a custom resampler by using the `ma_resample_algorithm_custom` resampling
  2402. algorithm and setting a vtable in the resampler config:
  2403. ```c
  2404. ma_resampler_config config = ma_resampler_config_init(..., ma_resample_algorithm_custom);
  2405. config.pBackendVTable = &g_customResamplerVTable;
  2406. ```
  2407. Custom resamplers are useful if the stock algorithms are not appropriate for your use case. You
  2408. need to implement the required functions in `ma_resampling_backend_vtable`. Note that not all
  2409. functions in the vtable need to be implemented, but if it's possible to implement, they should be.
  2410. You can use the `ma_linear_resampler` object for an example on how to implement the vtable. The
  2411. `onGetHeapSize` callback is used to calculate the size of any internal heap allocation the custom
  2412. resampler will need to make given the supplied config. When you initialize the resampler via the
  2413. `onInit` callback, you'll be given a pointer to a heap allocation which is where you should store
  2414. the heap allocated data. You should not free this data in `onUninit` because miniaudio will manage
  2415. it for you.
  2416. The `onProcess` callback is where the actual resampling takes place. On input, `pFrameCountIn`
  2417. points to a variable containing the number of frames in the `pFramesIn` buffer and
  2418. `pFrameCountOut` points to a variable containing the capacity in frames of the `pFramesOut` buffer.
  2419. On output, `pFrameCountIn` should be set to the number of input frames that were fully consumed,
  2420. whereas `pFrameCountOut` should be set to the number of frames that were written to `pFramesOut`.
  2421. The `onSetRate` callback is optional and is used for dynamically changing the sample rate. If
  2422. dynamic rate changes are not supported, you can set this callback to NULL.
  2423. The `onGetInputLatency` and `onGetOutputLatency` functions are used for retrieving the latency in
  2424. input and output rates respectively. These can be NULL in which case latency calculations will be
  2425. assumed to be NULL.
  2426. The `onGetRequiredInputFrameCount` callback is used to give miniaudio a hint as to how many input
  2427. frames are required to be available to produce the given number of output frames. Likewise, the
  2428. `onGetExpectedOutputFrameCount` callback is used to determine how many output frames will be
  2429. produced given the specified number of input frames. miniaudio will use these as a hint, but they
  2430. are optional and can be set to NULL if you're unable to implement them.
  2431. 10.4. General Data Conversion
  2432. -----------------------------
  2433. The `ma_data_converter` API can be used to wrap sample format conversion, channel conversion and
  2434. resampling into one operation. This is what miniaudio uses internally to convert between the format
  2435. requested when the device was initialized and the format of the backend's native device. The API
  2436. for general data conversion is very similar to the resampling API. Create a `ma_data_converter`
  2437. object like this:
  2438. ```c
  2439. ma_data_converter_config config = ma_data_converter_config_init(
  2440. inputFormat,
  2441. outputFormat,
  2442. inputChannels,
  2443. outputChannels,
  2444. inputSampleRate,
  2445. outputSampleRate
  2446. );
  2447. ma_data_converter converter;
  2448. ma_result result = ma_data_converter_init(&config, NULL, &converter);
  2449. if (result != MA_SUCCESS) {
  2450. // An error occurred...
  2451. }
  2452. ```
  2453. In the example above we use `ma_data_converter_config_init()` to initialize the config, however
  2454. there's many more properties that can be configured, such as channel maps and resampling quality.
  2455. Something like the following may be more suitable depending on your requirements:
  2456. ```c
  2457. ma_data_converter_config config = ma_data_converter_config_init_default();
  2458. config.formatIn = inputFormat;
  2459. config.formatOut = outputFormat;
  2460. config.channelsIn = inputChannels;
  2461. config.channelsOut = outputChannels;
  2462. config.sampleRateIn = inputSampleRate;
  2463. config.sampleRateOut = outputSampleRate;
  2464. ma_channel_map_init_standard(ma_standard_channel_map_flac, config.channelMapIn, sizeof(config.channelMapIn)/sizeof(config.channelMapIn[0]), config.channelCountIn);
  2465. config.resampling.linear.lpfOrder = MA_MAX_FILTER_ORDER;
  2466. ```
  2467. Do the following to uninitialize the data converter:
  2468. ```c
  2469. ma_data_converter_uninit(&converter, NULL);
  2470. ```
  2471. The following example shows how data can be processed
  2472. ```c
  2473. ma_uint64 frameCountIn = 1000;
  2474. ma_uint64 frameCountOut = 2000;
  2475. ma_result result = ma_data_converter_process_pcm_frames(&converter, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
  2476. if (result != MA_SUCCESS) {
  2477. // An error occurred...
  2478. }
  2479. // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the number
  2480. // of output frames written.
  2481. ```
  2482. The data converter supports multiple channels and is always interleaved (both input and output).
  2483. The channel count cannot be changed after initialization.
  2484. Sample rates can be anything other than zero, and are always specified in hertz. They should be set
  2485. to something like 44100, etc. The sample rate is the only configuration property that can be
  2486. changed after initialization, but only if the `resampling.allowDynamicSampleRate` member of
  2487. `ma_data_converter_config` is set to `MA_TRUE`. To change the sample rate, use
  2488. `ma_data_converter_set_rate()` or `ma_data_converter_set_rate_ratio()`. The ratio must be in/out.
  2489. The resampling algorithm cannot be changed after initialization.
  2490. Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
  2491. De-interleaved processing is not supported. To process frames, use
  2492. `ma_data_converter_process_pcm_frames()`. On input, this function takes the number of output frames
  2493. you can fit in the output buffer and the number of input frames contained in the input buffer. On
  2494. output these variables contain the number of output frames that were written to the output buffer
  2495. and the number of input frames that were consumed in the process. You can pass in NULL for the
  2496. input buffer in which case it will be treated as an infinitely large
  2497. buffer of zeros. The output buffer can also be NULL, in which case the processing will be treated
  2498. as seek.
  2499. Sometimes it's useful to know exactly how many input frames will be required to output a specific
  2500. number of frames. You can calculate this with `ma_data_converter_get_required_input_frame_count()`.
  2501. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
  2502. number of input frames. You can do this with `ma_data_converter_get_expected_output_frame_count()`.
  2503. Due to the nature of how resampling works, the data converter introduces some latency if resampling
  2504. is required. This can be retrieved in terms of both the input rate and the output rate with
  2505. `ma_data_converter_get_input_latency()` and `ma_data_converter_get_output_latency()`.
  2506. 11. Filtering
  2507. =============
  2508. 11.1. Biquad Filtering
  2509. ----------------------
  2510. Biquad filtering is achieved with the `ma_biquad` API. Example:
  2511. ```c
  2512. ma_biquad_config config = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2);
  2513. ma_result result = ma_biquad_init(&config, &biquad);
  2514. if (result != MA_SUCCESS) {
  2515. // Error.
  2516. }
  2517. ...
  2518. ma_biquad_process_pcm_frames(&biquad, pFramesOut, pFramesIn, frameCount);
  2519. ```
  2520. Biquad filtering is implemented using transposed direct form 2. The numerator coefficients are b0,
  2521. b1 and b2, and the denominator coefficients are a0, a1 and a2. The a0 coefficient is required and
  2522. coefficients must not be pre-normalized.
  2523. Supported formats are `ma_format_s16` and `ma_format_f32`. If you need to use a different format
  2524. you need to convert it yourself beforehand. When using `ma_format_s16` the biquad filter will use
  2525. fixed point arithmetic. When using `ma_format_f32`, floating point arithmetic will be used.
  2526. Input and output frames are always interleaved.
  2527. Filtering can be applied in-place by passing in the same pointer for both the input and output
  2528. buffers, like so:
  2529. ```c
  2530. ma_biquad_process_pcm_frames(&biquad, pMyData, pMyData, frameCount);
  2531. ```
  2532. If you need to change the values of the coefficients, but maintain the values in the registers you
  2533. can do so with `ma_biquad_reinit()`. This is useful if you need to change the properties of the
  2534. filter while keeping the values of registers valid to avoid glitching. Do not use
  2535. `ma_biquad_init()` for this as it will do a full initialization which involves clearing the
  2536. registers to 0. Note that changing the format or channel count after initialization is invalid and
  2537. will result in an error.
  2538. 11.2. Low-Pass Filtering
  2539. ------------------------
  2540. Low-pass filtering is achieved with the following APIs:
  2541. +---------+------------------------------------------+
  2542. | API | Description |
  2543. +---------+------------------------------------------+
  2544. | ma_lpf1 | First order low-pass filter |
  2545. | ma_lpf2 | Second order low-pass filter |
  2546. | ma_lpf | High order low-pass filter (Butterworth) |
  2547. +---------+------------------------------------------+
  2548. Low-pass filter example:
  2549. ```c
  2550. ma_lpf_config config = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  2551. ma_result result = ma_lpf_init(&config, &lpf);
  2552. if (result != MA_SUCCESS) {
  2553. // Error.
  2554. }
  2555. ...
  2556. ma_lpf_process_pcm_frames(&lpf, pFramesOut, pFramesIn, frameCount);
  2557. ```
  2558. Supported formats are `ma_format_s16` and` ma_format_f32`. If you need to use a different format
  2559. you need to convert it yourself beforehand. Input and output frames are always interleaved.
  2560. Filtering can be applied in-place by passing in the same pointer for both the input and output
  2561. buffers, like so:
  2562. ```c
  2563. ma_lpf_process_pcm_frames(&lpf, pMyData, pMyData, frameCount);
  2564. ```
  2565. The maximum filter order is limited to `MA_MAX_FILTER_ORDER` which is set to 8. If you need more,
  2566. you can chain first and second order filters together.
  2567. ```c
  2568. for (iFilter = 0; iFilter < filterCount; iFilter += 1) {
  2569. ma_lpf2_process_pcm_frames(&lpf2[iFilter], pMyData, pMyData, frameCount);
  2570. }
  2571. ```
  2572. If you need to change the configuration of the filter, but need to maintain the state of internal
  2573. registers you can do so with `ma_lpf_reinit()`. This may be useful if you need to change the sample
  2574. rate and/or cutoff frequency dynamically while maintaining smooth transitions. Note that changing the
  2575. format or channel count after initialization is invalid and will result in an error.
  2576. The `ma_lpf` object supports a configurable order, but if you only need a first order filter you
  2577. may want to consider using `ma_lpf1`. Likewise, if you only need a second order filter you can use
  2578. `ma_lpf2`. The advantage of this is that they're lighter weight and a bit more efficient.
  2579. If an even filter order is specified, a series of second order filters will be processed in a
  2580. chain. If an odd filter order is specified, a first order filter will be applied, followed by a
  2581. series of second order filters in a chain.
  2582. 11.3. High-Pass Filtering
  2583. -------------------------
  2584. High-pass filtering is achieved with the following APIs:
  2585. +---------+-------------------------------------------+
  2586. | API | Description |
  2587. +---------+-------------------------------------------+
  2588. | ma_hpf1 | First order high-pass filter |
  2589. | ma_hpf2 | Second order high-pass filter |
  2590. | ma_hpf | High order high-pass filter (Butterworth) |
  2591. +---------+-------------------------------------------+
  2592. High-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_hpf1`,
  2593. `ma_hpf2` and `ma_hpf`. See example code for low-pass filters for example usage.
  2594. 11.4. Band-Pass Filtering
  2595. -------------------------
  2596. Band-pass filtering is achieved with the following APIs:
  2597. +---------+-------------------------------+
  2598. | API | Description |
  2599. +---------+-------------------------------+
  2600. | ma_bpf2 | Second order band-pass filter |
  2601. | ma_bpf | High order band-pass filter |
  2602. +---------+-------------------------------+
  2603. Band-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_bpf2` and
  2604. `ma_hpf`. See example code for low-pass filters for example usage. Note that the order for
  2605. band-pass filters must be an even number which means there is no first order band-pass filter,
  2606. unlike low-pass and high-pass filters.
  2607. 11.5. Notch Filtering
  2608. ---------------------
  2609. Notch filtering is achieved with the following APIs:
  2610. +-----------+------------------------------------------+
  2611. | API | Description |
  2612. +-----------+------------------------------------------+
  2613. | ma_notch2 | Second order notching filter |
  2614. +-----------+------------------------------------------+
  2615. 11.6. Peaking EQ Filtering
  2616. -------------------------
  2617. Peaking filtering is achieved with the following APIs:
  2618. +----------+------------------------------------------+
  2619. | API | Description |
  2620. +----------+------------------------------------------+
  2621. | ma_peak2 | Second order peaking filter |
  2622. +----------+------------------------------------------+
  2623. 11.7. Low Shelf Filtering
  2624. -------------------------
  2625. Low shelf filtering is achieved with the following APIs:
  2626. +-------------+------------------------------------------+
  2627. | API | Description |
  2628. +-------------+------------------------------------------+
  2629. | ma_loshelf2 | Second order low shelf filter |
  2630. +-------------+------------------------------------------+
  2631. Where a high-pass filter is used to eliminate lower frequencies, a low shelf filter can be used to
  2632. just turn them down rather than eliminate them entirely.
  2633. 11.8. High Shelf Filtering
  2634. --------------------------
  2635. High shelf filtering is achieved with the following APIs:
  2636. +-------------+------------------------------------------+
  2637. | API | Description |
  2638. +-------------+------------------------------------------+
  2639. | ma_hishelf2 | Second order high shelf filter |
  2640. +-------------+------------------------------------------+
  2641. The high shelf filter has the same API as the low shelf filter, only you would use `ma_hishelf`
  2642. instead of `ma_loshelf`. Where a low shelf filter is used to adjust the volume of low frequencies,
  2643. the high shelf filter does the same thing for high frequencies.
  2644. 12. Waveform and Noise Generation
  2645. =================================
  2646. 12.1. Waveforms
  2647. ---------------
  2648. miniaudio supports generation of sine, square, triangle and sawtooth waveforms. This is achieved
  2649. with the `ma_waveform` API. Example:
  2650. ```c
  2651. ma_waveform_config config = ma_waveform_config_init(
  2652. FORMAT,
  2653. CHANNELS,
  2654. SAMPLE_RATE,
  2655. ma_waveform_type_sine,
  2656. amplitude,
  2657. frequency);
  2658. ma_waveform waveform;
  2659. ma_result result = ma_waveform_init(&config, &waveform);
  2660. if (result != MA_SUCCESS) {
  2661. // Error.
  2662. }
  2663. ...
  2664. ma_waveform_read_pcm_frames(&waveform, pOutput, frameCount);
  2665. ```
  2666. The amplitude, frequency, type, and sample rate can be changed dynamically with
  2667. `ma_waveform_set_amplitude()`, `ma_waveform_set_frequency()`, `ma_waveform_set_type()`, and
  2668. `ma_waveform_set_sample_rate()` respectively.
  2669. You can invert the waveform by setting the amplitude to a negative value. You can use this to
  2670. control whether or not a sawtooth has a positive or negative ramp, for example.
  2671. Below are the supported waveform types:
  2672. +---------------------------+
  2673. | Enum Name |
  2674. +---------------------------+
  2675. | ma_waveform_type_sine |
  2676. | ma_waveform_type_square |
  2677. | ma_waveform_type_triangle |
  2678. | ma_waveform_type_sawtooth |
  2679. +---------------------------+
  2680. 12.2. Noise
  2681. -----------
  2682. miniaudio supports generation of white, pink and Brownian noise via the `ma_noise` API. Example:
  2683. ```c
  2684. ma_noise_config config = ma_noise_config_init(
  2685. FORMAT,
  2686. CHANNELS,
  2687. ma_noise_type_white,
  2688. SEED,
  2689. amplitude);
  2690. ma_noise noise;
  2691. ma_result result = ma_noise_init(&config, &noise);
  2692. if (result != MA_SUCCESS) {
  2693. // Error.
  2694. }
  2695. ...
  2696. ma_noise_read_pcm_frames(&noise, pOutput, frameCount);
  2697. ```
  2698. The noise API uses simple LCG random number generation. It supports a custom seed which is useful
  2699. for things like automated testing requiring reproducibility. Setting the seed to zero will default
  2700. to `MA_DEFAULT_LCG_SEED`.
  2701. The amplitude and seed can be changed dynamically with `ma_noise_set_amplitude()` and
  2702. `ma_noise_set_seed()` respectively.
  2703. By default, the noise API will use different values for different channels. So, for example, the
  2704. left side in a stereo stream will be different to the right side. To instead have each channel use
  2705. the same random value, set the `duplicateChannels` member of the noise config to true, like so:
  2706. ```c
  2707. config.duplicateChannels = MA_TRUE;
  2708. ```
  2709. Below are the supported noise types.
  2710. +------------------------+
  2711. | Enum Name |
  2712. +------------------------+
  2713. | ma_noise_type_white |
  2714. | ma_noise_type_pink |
  2715. | ma_noise_type_brownian |
  2716. +------------------------+
  2717. 13. Audio Buffers
  2718. =================
  2719. miniaudio supports reading from a buffer of raw audio data via the `ma_audio_buffer` API. This can
  2720. read from memory that's managed by the application, but can also handle the memory management for
  2721. you internally. Memory management is flexible and should support most use cases.
  2722. Audio buffers are initialised using the standard configuration system used everywhere in miniaudio:
  2723. ```c
  2724. ma_audio_buffer_config config = ma_audio_buffer_config_init(
  2725. format,
  2726. channels,
  2727. sizeInFrames,
  2728. pExistingData,
  2729. &allocationCallbacks);
  2730. ma_audio_buffer buffer;
  2731. result = ma_audio_buffer_init(&config, &buffer);
  2732. if (result != MA_SUCCESS) {
  2733. // Error.
  2734. }
  2735. ...
  2736. ma_audio_buffer_uninit(&buffer);
  2737. ```
  2738. In the example above, the memory pointed to by `pExistingData` will *not* be copied and is how an
  2739. application can do self-managed memory allocation. If you would rather make a copy of the data, use
  2740. `ma_audio_buffer_init_copy()`. To uninitialize the buffer, use `ma_audio_buffer_uninit()`.
  2741. Sometimes it can be convenient to allocate the memory for the `ma_audio_buffer` structure and the
  2742. raw audio data in a contiguous block of memory. That is, the raw audio data will be located
  2743. immediately after the `ma_audio_buffer` structure. To do this, use
  2744. `ma_audio_buffer_alloc_and_init()`:
  2745. ```c
  2746. ma_audio_buffer_config config = ma_audio_buffer_config_init(
  2747. format,
  2748. channels,
  2749. sizeInFrames,
  2750. pExistingData,
  2751. &allocationCallbacks);
  2752. ma_audio_buffer* pBuffer
  2753. result = ma_audio_buffer_alloc_and_init(&config, &pBuffer);
  2754. if (result != MA_SUCCESS) {
  2755. // Error
  2756. }
  2757. ...
  2758. ma_audio_buffer_uninit_and_free(&buffer);
  2759. ```
  2760. If you initialize the buffer with `ma_audio_buffer_alloc_and_init()` you should uninitialize it
  2761. with `ma_audio_buffer_uninit_and_free()`. In the example above, the memory pointed to by
  2762. `pExistingData` will be copied into the buffer, which is contrary to the behavior of
  2763. `ma_audio_buffer_init()`.
  2764. An audio buffer has a playback cursor just like a decoder. As you read frames from the buffer, the
  2765. cursor moves forward. The last parameter (`loop`) can be used to determine if the buffer should
  2766. loop. The return value is the number of frames actually read. If this is less than the number of
  2767. frames requested it means the end has been reached. This should never happen if the `loop`
  2768. parameter is set to true. If you want to manually loop back to the start, you can do so with with
  2769. `ma_audio_buffer_seek_to_pcm_frame(pAudioBuffer, 0)`. Below is an example for reading data from an
  2770. audio buffer.
  2771. ```c
  2772. ma_uint64 framesRead = ma_audio_buffer_read_pcm_frames(pAudioBuffer, pFramesOut, desiredFrameCount, isLooping);
  2773. if (framesRead < desiredFrameCount) {
  2774. // If not looping, this means the end has been reached. This should never happen in looping mode with valid input.
  2775. }
  2776. ```
  2777. Sometimes you may want to avoid the cost of data movement between the internal buffer and the
  2778. output buffer. Instead you can use memory mapping to retrieve a pointer to a segment of data:
  2779. ```c
  2780. void* pMappedFrames;
  2781. ma_uint64 frameCount = frameCountToTryMapping;
  2782. ma_result result = ma_audio_buffer_map(pAudioBuffer, &pMappedFrames, &frameCount);
  2783. if (result == MA_SUCCESS) {
  2784. // Map was successful. The value in frameCount will be how many frames were _actually_ mapped, which may be
  2785. // less due to the end of the buffer being reached.
  2786. ma_copy_pcm_frames(pFramesOut, pMappedFrames, frameCount, pAudioBuffer->format, pAudioBuffer->channels);
  2787. // You must unmap the buffer.
  2788. ma_audio_buffer_unmap(pAudioBuffer, frameCount);
  2789. }
  2790. ```
  2791. When you use memory mapping, the read cursor is increment by the frame count passed in to
  2792. `ma_audio_buffer_unmap()`. If you decide not to process every frame you can pass in a value smaller
  2793. than the value returned by `ma_audio_buffer_map()`. The disadvantage to using memory mapping is
  2794. that it does not handle looping for you. You can determine if the buffer is at the end for the
  2795. purpose of looping with `ma_audio_buffer_at_end()` or by inspecting the return value of
  2796. `ma_audio_buffer_unmap()` and checking if it equals `MA_AT_END`. You should not treat `MA_AT_END`
  2797. as an error when returned by `ma_audio_buffer_unmap()`.
  2798. 14. Ring Buffers
  2799. ================
  2800. miniaudio supports lock free (single producer, single consumer) ring buffers which are exposed via
  2801. the `ma_rb` and `ma_pcm_rb` APIs. The `ma_rb` API operates on bytes, whereas the `ma_pcm_rb`
  2802. operates on PCM frames. They are otherwise identical as `ma_pcm_rb` is just a wrapper around
  2803. `ma_rb`.
  2804. Unlike most other APIs in miniaudio, ring buffers support both interleaved and deinterleaved
  2805. streams. The caller can also allocate their own backing memory for the ring buffer to use
  2806. internally for added flexibility. Otherwise the ring buffer will manage it's internal memory for
  2807. you.
  2808. The examples below use the PCM frame variant of the ring buffer since that's most likely the one
  2809. you will want to use. To initialize a ring buffer, do something like the following:
  2810. ```c
  2811. ma_pcm_rb rb;
  2812. ma_result result = ma_pcm_rb_init(FORMAT, CHANNELS, BUFFER_SIZE_IN_FRAMES, NULL, NULL, &rb);
  2813. if (result != MA_SUCCESS) {
  2814. // Error
  2815. }
  2816. ```
  2817. The `ma_pcm_rb_init()` function takes the sample format and channel count as parameters because
  2818. it's the PCM variant of the ring buffer API. For the regular ring buffer that operates on bytes you
  2819. would call `ma_rb_init()` which leaves these out and just takes the size of the buffer in bytes
  2820. instead of frames. The fourth parameter is an optional pre-allocated buffer and the fifth parameter
  2821. is a pointer to a `ma_allocation_callbacks` structure for custom memory allocation routines.
  2822. Passing in `NULL` for this results in `MA_MALLOC()` and `MA_FREE()` being used.
  2823. Use `ma_pcm_rb_init_ex()` if you need a deinterleaved buffer. The data for each sub-buffer is
  2824. offset from each other based on the stride. To manage your sub-buffers you can use
  2825. `ma_pcm_rb_get_subbuffer_stride()`, `ma_pcm_rb_get_subbuffer_offset()` and
  2826. `ma_pcm_rb_get_subbuffer_ptr()`.
  2827. Use `ma_pcm_rb_acquire_read()` and `ma_pcm_rb_acquire_write()` to retrieve a pointer to a section
  2828. of the ring buffer. You specify the number of frames you need, and on output it will set to what
  2829. was actually acquired. If the read or write pointer is positioned such that the number of frames
  2830. requested will require a loop, it will be clamped to the end of the buffer. Therefore, the number
  2831. of frames you're given may be less than the number you requested.
  2832. After calling `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()`, you do your work on the
  2833. buffer and then "commit" it with `ma_pcm_rb_commit_read()` or `ma_pcm_rb_commit_write()`. This is
  2834. where the read/write pointers are updated. When you commit you need to pass in the buffer that was
  2835. returned by the earlier call to `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()` and is
  2836. only used for validation. The number of frames passed to `ma_pcm_rb_commit_read()` and
  2837. `ma_pcm_rb_commit_write()` is what's used to increment the pointers, and can be less that what was
  2838. originally requested.
  2839. If you want to correct for drift between the write pointer and the read pointer you can use a
  2840. combination of `ma_pcm_rb_pointer_distance()`, `ma_pcm_rb_seek_read()` and
  2841. `ma_pcm_rb_seek_write()`. Note that you can only move the pointers forward, and you should only
  2842. move the read pointer forward via the consumer thread, and the write pointer forward by the
  2843. producer thread. If there is too much space between the pointers, move the read pointer forward. If
  2844. there is too little space between the pointers, move the write pointer forward.
  2845. You can use a ring buffer at the byte level instead of the PCM frame level by using the `ma_rb`
  2846. API. This is exactly the same, only you will use the `ma_rb` functions instead of `ma_pcm_rb` and
  2847. instead of frame counts you will pass around byte counts.
  2848. The maximum size of the buffer in bytes is `0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1)` due to the most
  2849. significant bit being used to encode a loop flag and the internally managed buffers always being
  2850. aligned to `MA_SIMD_ALIGNMENT`.
  2851. Note that the ring buffer is only thread safe when used by a single consumer thread and single
  2852. producer thread.
  2853. 15. Backends
  2854. ============
  2855. The following backends are supported by miniaudio. These are listed in order of default priority.
  2856. When no backend is specified when initializing a context or device, miniaudio will attempt to use
  2857. each of these backends in the order listed in the table below.
  2858. Note that backends that are not usable by the build target will not be included in the build. For
  2859. example, ALSA, which is specific to Linux, will not be included in the Windows build.
  2860. +-------------+-----------------------+--------------------------------------------------------+
  2861. | Name | Enum Name | Supported Operating Systems |
  2862. +-------------+-----------------------+--------------------------------------------------------+
  2863. | WASAPI | ma_backend_wasapi | Windows Vista+ |
  2864. | DirectSound | ma_backend_dsound | Windows XP+ |
  2865. | WinMM | ma_backend_winmm | Windows 95+ |
  2866. | Core Audio | ma_backend_coreaudio | macOS, iOS |
  2867. | sndio | ma_backend_sndio | OpenBSD |
  2868. | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
  2869. | OSS | ma_backend_oss | FreeBSD |
  2870. | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
  2871. | ALSA | ma_backend_alsa | Linux |
  2872. | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
  2873. | AAudio | ma_backend_aaudio | Android 8+ |
  2874. | OpenSL ES | ma_backend_opensl | Android (API level 16+) |
  2875. | Web Audio | ma_backend_webaudio | Web (via Emscripten) |
  2876. | Custom | ma_backend_custom | Cross Platform |
  2877. | Null | ma_backend_null | Cross Platform (not used on Web) |
  2878. +-------------+-----------------------+--------------------------------------------------------+
  2879. Some backends have some nuance details you may want to be aware of.
  2880. 15.1. WASAPI
  2881. ------------
  2882. - Low-latency shared mode will be disabled when using an application-defined sample rate which is
  2883. different to the device's native sample rate. To work around this, set `wasapi.noAutoConvertSRC`
  2884. to true in the device config. This is due to IAudioClient3_InitializeSharedAudioStream() failing
  2885. when the `AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM` flag is specified. Setting wasapi.noAutoConvertSRC
  2886. will result in miniaudio's internal resampler being used instead which will in turn enable the
  2887. use of low-latency shared mode.
  2888. 15.2. PulseAudio
  2889. ----------------
  2890. - If you experience bad glitching/noise on Arch Linux, consider this fix from the Arch wiki:
  2891. https://wiki.archlinux.org/index.php/PulseAudio/Troubleshooting#Glitches,_skips_or_crackling.
  2892. Alternatively, consider using a different backend such as ALSA.
  2893. 15.3. Android
  2894. -------------
  2895. - To capture audio on Android, remember to add the RECORD_AUDIO permission to your manifest:
  2896. `<uses-permission android:name="android.permission.RECORD_AUDIO" />`
  2897. - With OpenSL|ES, only a single ma_context can be active at any given time. This is due to a
  2898. limitation with OpenSL|ES.
  2899. - With AAudio, only default devices are enumerated. This is due to AAudio not having an enumeration
  2900. API (devices are enumerated through Java). You can however perform your own device enumeration
  2901. through Java and then set the ID in the ma_device_id structure (ma_device_id.aaudio) and pass it
  2902. to ma_device_init().
  2903. - The backend API will perform resampling where possible. The reason for this as opposed to using
  2904. miniaudio's built-in resampler is to take advantage of any potential device-specific
  2905. optimizations the driver may implement.
  2906. BSD
  2907. ---
  2908. - The sndio backend is currently only enabled on OpenBSD builds.
  2909. - The audio(4) backend is supported on OpenBSD, but you may need to disable sndiod before you can
  2910. use it.
  2911. 15.4. UWP
  2912. ---------
  2913. - UWP only supports default playback and capture devices.
  2914. - UWP requires the Microphone capability to be enabled in the application's manifest (Package.appxmanifest):
  2915. ```
  2916. <Package ...>
  2917. ...
  2918. <Capabilities>
  2919. <DeviceCapability Name="microphone" />
  2920. </Capabilities>
  2921. </Package>
  2922. ```
  2923. 15.5. Web Audio / Emscripten
  2924. ----------------------------
  2925. - You cannot use `-std=c*` compiler flags, nor `-ansi`. This only applies to the Emscripten build.
  2926. - The first time a context is initialized it will create a global object called "miniaudio" whose
  2927. primary purpose is to act as a factory for device objects.
  2928. - Currently the Web Audio backend uses ScriptProcessorNode's, but this may need to change later as
  2929. they've been deprecated.
  2930. - Google has implemented a policy in their browsers that prevent automatic media output without
  2931. first receiving some kind of user input. The following web page has additional details:
  2932. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes. Starting the device
  2933. may fail if you try to start playback without first handling some kind of user input.
  2934. 16. Optimization Tips
  2935. =====================
  2936. See below for some tips on improving performance.
  2937. 16.1. Low Level API
  2938. -------------------
  2939. - In the data callback, if your data is already clipped prior to copying it into the output buffer,
  2940. set the `noClip` config option in the device config to true. This will disable miniaudio's built
  2941. in clipping function.
  2942. - By default, miniaudio will pre-silence the data callback's output buffer. If you know that you
  2943. will always write valid data to the output buffer you can disable pre-silencing by setting the
  2944. `noPreSilence` config option in the device config to true.
  2945. 16.2. High Level API
  2946. --------------------
  2947. - If a sound does not require doppler or pitch shifting, consider disabling pitching by
  2948. initializing the sound with the `MA_SOUND_FLAG_NO_PITCH` flag.
  2949. - If a sound does not require spatialization, disable it by initializing the sound with the
  2950. `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. It can be re-enabled again post-initialization with
  2951. `ma_sound_set_spatialization_enabled()`.
  2952. - If you know all of your sounds will always be the same sample rate, set the engine's sample
  2953. rate to match that of the sounds. Likewise, if you're using a self-managed resource manager,
  2954. consider setting the decoded sample rate to match your sounds. By configuring everything to
  2955. use a consistent sample rate, sample rate conversion can be avoided.
  2956. 17. Miscellaneous Notes
  2957. =======================
  2958. - Automatic stream routing is enabled on a per-backend basis. Support is explicitly enabled for
  2959. WASAPI and Core Audio, however other backends such as PulseAudio may naturally support it, though
  2960. not all have been tested.
  2961. - When compiling with VC6 and earlier, decoding is restricted to files less than 2GB in size. This
  2962. is due to 64-bit file APIs not being available.
  2963. */
  2964. #ifndef miniaudio_h
  2965. #define miniaudio_h
  2966. #ifdef __cplusplus
  2967. extern "C" {
  2968. #endif
  2969. #define MA_STRINGIFY(x) #x
  2970. #define MA_XSTRINGIFY(x) MA_STRINGIFY(x)
  2971. #define MA_VERSION_MAJOR 0
  2972. #define MA_VERSION_MINOR 11
  2973. #define MA_VERSION_REVISION 15
  2974. #define MA_VERSION_STRING MA_XSTRINGIFY(MA_VERSION_MAJOR) "." MA_XSTRINGIFY(MA_VERSION_MINOR) "." MA_XSTRINGIFY(MA_VERSION_REVISION)
  2975. #if defined(_MSC_VER) && !defined(__clang__)
  2976. #pragma warning(push)
  2977. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  2978. #pragma warning(disable:4214) /* nonstandard extension used: bit field types other than int */
  2979. #pragma warning(disable:4324) /* structure was padded due to alignment specifier */
  2980. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  2981. #pragma GCC diagnostic push
  2982. #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  2983. #if defined(__clang__)
  2984. #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
  2985. #endif
  2986. #endif
  2987. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined(_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__)
  2988. #define MA_SIZEOF_PTR 8
  2989. #else
  2990. #define MA_SIZEOF_PTR 4
  2991. #endif
  2992. #include <stddef.h> /* For size_t. */
  2993. /* Sized types. */
  2994. #if defined(MA_USE_STDINT)
  2995. #include <stdint.h>
  2996. typedef int8_t ma_int8;
  2997. typedef uint8_t ma_uint8;
  2998. typedef int16_t ma_int16;
  2999. typedef uint16_t ma_uint16;
  3000. typedef int32_t ma_int32;
  3001. typedef uint32_t ma_uint32;
  3002. typedef int64_t ma_int64;
  3003. typedef uint64_t ma_uint64;
  3004. #else
  3005. typedef signed char ma_int8;
  3006. typedef unsigned char ma_uint8;
  3007. typedef signed short ma_int16;
  3008. typedef unsigned short ma_uint16;
  3009. typedef signed int ma_int32;
  3010. typedef unsigned int ma_uint32;
  3011. #if defined(_MSC_VER) && !defined(__clang__)
  3012. typedef signed __int64 ma_int64;
  3013. typedef unsigned __int64 ma_uint64;
  3014. #else
  3015. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  3016. #pragma GCC diagnostic push
  3017. #pragma GCC diagnostic ignored "-Wlong-long"
  3018. #if defined(__clang__)
  3019. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  3020. #endif
  3021. #endif
  3022. typedef signed long long ma_int64;
  3023. typedef unsigned long long ma_uint64;
  3024. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  3025. #pragma GCC diagnostic pop
  3026. #endif
  3027. #endif
  3028. #endif /* MA_USE_STDINT */
  3029. #if MA_SIZEOF_PTR == 8
  3030. typedef ma_uint64 ma_uintptr;
  3031. #else
  3032. typedef ma_uint32 ma_uintptr;
  3033. #endif
  3034. typedef ma_uint8 ma_bool8;
  3035. typedef ma_uint32 ma_bool32;
  3036. #define MA_TRUE 1
  3037. #define MA_FALSE 0
  3038. /* These float types are not used universally by miniaudio. It's to simplify some macro expansion for atomic types. */
  3039. typedef float ma_float;
  3040. typedef double ma_double;
  3041. typedef void* ma_handle;
  3042. typedef void* ma_ptr;
  3043. /*
  3044. ma_proc is annoying because when compiling with GCC we get pendantic warnings about converting
  3045. between `void*` and `void (*)()`. We can't use `void (*)()` with MSVC however, because we'll get
  3046. warning C4191 about "type cast between incompatible function types". To work around this I'm going
  3047. to use a different data type depending on the compiler.
  3048. */
  3049. #if defined(__GNUC__)
  3050. typedef void (*ma_proc)(void);
  3051. #else
  3052. typedef void* ma_proc;
  3053. #endif
  3054. #if defined(_MSC_VER) && !defined(_WCHAR_T_DEFINED)
  3055. typedef ma_uint16 wchar_t;
  3056. #endif
  3057. /* Define NULL for some compilers. */
  3058. #ifndef NULL
  3059. #define NULL 0
  3060. #endif
  3061. #if defined(SIZE_MAX)
  3062. #define MA_SIZE_MAX SIZE_MAX
  3063. #else
  3064. #define MA_SIZE_MAX 0xFFFFFFFF /* When SIZE_MAX is not defined by the standard library just default to the maximum 32-bit unsigned integer. */
  3065. #endif
  3066. /* Platform/backend detection. */
  3067. #if defined(_WIN32) || defined(__COSMOPOLITAN__)
  3068. #define MA_WIN32
  3069. #if defined(MA_FORCE_UWP) || (defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_PC_APP) && WINAPI_FAMILY == WINAPI_FAMILY_PC_APP) || (defined(WINAPI_FAMILY_PHONE_APP) && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)))
  3070. #define MA_WIN32_UWP
  3071. #elif defined(WINAPI_FAMILY) && (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
  3072. #define MA_WIN32_GDK
  3073. #else
  3074. #define MA_WIN32_DESKTOP
  3075. #endif
  3076. #endif
  3077. #if !defined(_WIN32) /* If it's not Win32, assume POSIX. */
  3078. #define MA_POSIX
  3079. /*
  3080. Use the MA_NO_PTHREAD_IN_HEADER option at your own risk. This is intentionally undocumented.
  3081. You can use this to avoid including pthread.h in the header section. The downside is that it
  3082. results in some fixed sized structures being declared for the various types that are used in
  3083. miniaudio. The risk here is that these types might be too small for a given platform. This
  3084. risk is yours to take and no support will be offered if you enable this option.
  3085. */
  3086. #ifndef MA_NO_PTHREAD_IN_HEADER
  3087. #include <pthread.h> /* Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. */
  3088. typedef pthread_t ma_pthread_t;
  3089. typedef pthread_mutex_t ma_pthread_mutex_t;
  3090. typedef pthread_cond_t ma_pthread_cond_t;
  3091. #else
  3092. typedef ma_uintptr ma_pthread_t;
  3093. typedef union ma_pthread_mutex_t { char __data[40]; ma_uint64 __alignment; } ma_pthread_mutex_t;
  3094. typedef union ma_pthread_cond_t { char __data[48]; ma_uint64 __alignment; } ma_pthread_cond_t;
  3095. #endif
  3096. #if defined(__unix__)
  3097. #define MA_UNIX
  3098. #endif
  3099. #if defined(__linux__)
  3100. #define MA_LINUX
  3101. #endif
  3102. #if defined(__APPLE__)
  3103. #define MA_APPLE
  3104. #endif
  3105. #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
  3106. #define MA_BSD
  3107. #endif
  3108. #if defined(__ANDROID__)
  3109. #define MA_ANDROID
  3110. #endif
  3111. #if defined(__EMSCRIPTEN__)
  3112. #define MA_EMSCRIPTEN
  3113. #endif
  3114. #if defined(__ORBIS__)
  3115. #define MA_ORBIS
  3116. #endif
  3117. #if defined(__PROSPERO__)
  3118. #define MA_PROSPERO
  3119. #endif
  3120. #if defined(__NX__)
  3121. #define MA_NX
  3122. #endif
  3123. #if defined(__BEOS__) || defined(__HAIKU__)
  3124. #define MA_BEOS
  3125. #endif
  3126. #if defined(__HAIKU__)
  3127. #define MA_HAIKU
  3128. #endif
  3129. #endif
  3130. #if defined(__has_c_attribute)
  3131. #if __has_c_attribute(fallthrough)
  3132. #define MA_FALLTHROUGH [[fallthrough]]
  3133. #endif
  3134. #endif
  3135. #if !defined(MA_FALLTHROUGH) && defined(__has_attribute) && (defined(__clang__) || defined(__GNUC__))
  3136. #if __has_attribute(fallthrough)
  3137. #define MA_FALLTHROUGH __attribute__((fallthrough))
  3138. #endif
  3139. #endif
  3140. #if !defined(MA_FALLTHROUGH)
  3141. #define MA_FALLTHROUGH ((void)0)
  3142. #endif
  3143. #ifdef _MSC_VER
  3144. #define MA_INLINE __forceinline
  3145. #elif defined(__GNUC__)
  3146. /*
  3147. I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
  3148. the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
  3149. case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
  3150. command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
  3151. I am using "__inline__" only when we're compiling in strict ANSI mode.
  3152. */
  3153. #if defined(__STRICT_ANSI__)
  3154. #define MA_GNUC_INLINE_HINT __inline__
  3155. #else
  3156. #define MA_GNUC_INLINE_HINT inline
  3157. #endif
  3158. #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
  3159. #define MA_INLINE MA_GNUC_INLINE_HINT __attribute__((always_inline))
  3160. #else
  3161. #define MA_INLINE MA_GNUC_INLINE_HINT
  3162. #endif
  3163. #elif defined(__WATCOMC__)
  3164. #define MA_INLINE __inline
  3165. #else
  3166. #define MA_INLINE
  3167. #endif
  3168. #if !defined(MA_API)
  3169. #if defined(MA_DLL)
  3170. #if defined(_WIN32)
  3171. #define MA_DLL_IMPORT __declspec(dllimport)
  3172. #define MA_DLL_EXPORT __declspec(dllexport)
  3173. #define MA_DLL_PRIVATE static
  3174. #else
  3175. #if defined(__GNUC__) && __GNUC__ >= 4
  3176. #define MA_DLL_IMPORT __attribute__((visibility("default")))
  3177. #define MA_DLL_EXPORT __attribute__((visibility("default")))
  3178. #define MA_DLL_PRIVATE __attribute__((visibility("hidden")))
  3179. #else
  3180. #define MA_DLL_IMPORT
  3181. #define MA_DLL_EXPORT
  3182. #define MA_DLL_PRIVATE static
  3183. #endif
  3184. #endif
  3185. #if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION)
  3186. #define MA_API MA_DLL_EXPORT
  3187. #else
  3188. #define MA_API MA_DLL_IMPORT
  3189. #endif
  3190. #define MA_PRIVATE MA_DLL_PRIVATE
  3191. #else
  3192. #define MA_API extern
  3193. #define MA_PRIVATE static
  3194. #endif
  3195. #endif
  3196. /* SIMD alignment in bytes. Currently set to 32 bytes in preparation for future AVX optimizations. */
  3197. #define MA_SIMD_ALIGNMENT 32
  3198. /*
  3199. Special wchar_t type to ensure any structures in the public sections that reference it have a
  3200. consistent size across all platforms.
  3201. On Windows, wchar_t is 2 bytes, whereas everywhere else it's 4 bytes. Since Windows likes to use
  3202. wchar_t for it's IDs, we need a special explicitly sized wchar type that is always 2 bytes on all
  3203. platforms.
  3204. */
  3205. #if !defined(MA_POSIX) && defined(MA_WIN32)
  3206. typedef wchar_t ma_wchar_win32;
  3207. #else
  3208. typedef ma_uint16 ma_wchar_win32;
  3209. #endif
  3210. /*
  3211. Logging Levels
  3212. ==============
  3213. Log levels are only used to give logging callbacks some context as to the severity of a log message
  3214. so they can do filtering. All log levels will be posted to registered logging callbacks. If you
  3215. don't want to output a certain log level you can discriminate against the log level in the callback.
  3216. MA_LOG_LEVEL_DEBUG
  3217. Used for debugging. Useful for debug and test builds, but should be disabled in release builds.
  3218. MA_LOG_LEVEL_INFO
  3219. Informational logging. Useful for debugging. This will never be called from within the data
  3220. callback.
  3221. MA_LOG_LEVEL_WARNING
  3222. Warnings. You should enable this in you development builds and action them when encounted. These
  3223. logs usually indicate a potential problem or misconfiguration, but still allow you to keep
  3224. running. This will never be called from within the data callback.
  3225. MA_LOG_LEVEL_ERROR
  3226. Error logging. This will be fired when an operation fails and is subsequently aborted. This can
  3227. be fired from within the data callback, in which case the device will be stopped. You should
  3228. always have this log level enabled.
  3229. */
  3230. typedef enum
  3231. {
  3232. MA_LOG_LEVEL_DEBUG = 4,
  3233. MA_LOG_LEVEL_INFO = 3,
  3234. MA_LOG_LEVEL_WARNING = 2,
  3235. MA_LOG_LEVEL_ERROR = 1
  3236. } ma_log_level;
  3237. /*
  3238. Variables needing to be accessed atomically should be declared with this macro for two reasons:
  3239. 1) It allows people who read the code to identify a variable as such; and
  3240. 2) It forces alignment on platforms where it's required or optimal.
  3241. Note that for x86/64, alignment is not strictly necessary, but does have some performance
  3242. implications. Where supported by the compiler, alignment will be used, but otherwise if the CPU
  3243. architecture does not require it, it will simply leave it unaligned. This is the case with old
  3244. versions of Visual Studio, which I've confirmed with at least VC6.
  3245. */
  3246. #if !defined(_MSC_VER) && defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  3247. #include <stdalign.h>
  3248. #define MA_ATOMIC(alignment, type) _Alignas(alignment) type
  3249. #else
  3250. #if defined(__GNUC__)
  3251. /* GCC-style compilers. */
  3252. #define MA_ATOMIC(alignment, type) type __attribute__((aligned(alignment)))
  3253. #elif defined(_MSC_VER) && _MSC_VER > 1200 /* 1200 = VC6. Alignment not supported, but not necessary because x86 is the only supported target. */
  3254. /* MSVC. */
  3255. #define MA_ATOMIC(alignment, type) __declspec(align(alignment)) type
  3256. #else
  3257. /* Other compilers. */
  3258. #define MA_ATOMIC(alignment, type) type
  3259. #endif
  3260. #endif
  3261. typedef struct ma_context ma_context;
  3262. typedef struct ma_device ma_device;
  3263. typedef ma_uint8 ma_channel;
  3264. typedef enum
  3265. {
  3266. MA_CHANNEL_NONE = 0,
  3267. MA_CHANNEL_MONO = 1,
  3268. MA_CHANNEL_FRONT_LEFT = 2,
  3269. MA_CHANNEL_FRONT_RIGHT = 3,
  3270. MA_CHANNEL_FRONT_CENTER = 4,
  3271. MA_CHANNEL_LFE = 5,
  3272. MA_CHANNEL_BACK_LEFT = 6,
  3273. MA_CHANNEL_BACK_RIGHT = 7,
  3274. MA_CHANNEL_FRONT_LEFT_CENTER = 8,
  3275. MA_CHANNEL_FRONT_RIGHT_CENTER = 9,
  3276. MA_CHANNEL_BACK_CENTER = 10,
  3277. MA_CHANNEL_SIDE_LEFT = 11,
  3278. MA_CHANNEL_SIDE_RIGHT = 12,
  3279. MA_CHANNEL_TOP_CENTER = 13,
  3280. MA_CHANNEL_TOP_FRONT_LEFT = 14,
  3281. MA_CHANNEL_TOP_FRONT_CENTER = 15,
  3282. MA_CHANNEL_TOP_FRONT_RIGHT = 16,
  3283. MA_CHANNEL_TOP_BACK_LEFT = 17,
  3284. MA_CHANNEL_TOP_BACK_CENTER = 18,
  3285. MA_CHANNEL_TOP_BACK_RIGHT = 19,
  3286. MA_CHANNEL_AUX_0 = 20,
  3287. MA_CHANNEL_AUX_1 = 21,
  3288. MA_CHANNEL_AUX_2 = 22,
  3289. MA_CHANNEL_AUX_3 = 23,
  3290. MA_CHANNEL_AUX_4 = 24,
  3291. MA_CHANNEL_AUX_5 = 25,
  3292. MA_CHANNEL_AUX_6 = 26,
  3293. MA_CHANNEL_AUX_7 = 27,
  3294. MA_CHANNEL_AUX_8 = 28,
  3295. MA_CHANNEL_AUX_9 = 29,
  3296. MA_CHANNEL_AUX_10 = 30,
  3297. MA_CHANNEL_AUX_11 = 31,
  3298. MA_CHANNEL_AUX_12 = 32,
  3299. MA_CHANNEL_AUX_13 = 33,
  3300. MA_CHANNEL_AUX_14 = 34,
  3301. MA_CHANNEL_AUX_15 = 35,
  3302. MA_CHANNEL_AUX_16 = 36,
  3303. MA_CHANNEL_AUX_17 = 37,
  3304. MA_CHANNEL_AUX_18 = 38,
  3305. MA_CHANNEL_AUX_19 = 39,
  3306. MA_CHANNEL_AUX_20 = 40,
  3307. MA_CHANNEL_AUX_21 = 41,
  3308. MA_CHANNEL_AUX_22 = 42,
  3309. MA_CHANNEL_AUX_23 = 43,
  3310. MA_CHANNEL_AUX_24 = 44,
  3311. MA_CHANNEL_AUX_25 = 45,
  3312. MA_CHANNEL_AUX_26 = 46,
  3313. MA_CHANNEL_AUX_27 = 47,
  3314. MA_CHANNEL_AUX_28 = 48,
  3315. MA_CHANNEL_AUX_29 = 49,
  3316. MA_CHANNEL_AUX_30 = 50,
  3317. MA_CHANNEL_AUX_31 = 51,
  3318. MA_CHANNEL_LEFT = MA_CHANNEL_FRONT_LEFT,
  3319. MA_CHANNEL_RIGHT = MA_CHANNEL_FRONT_RIGHT,
  3320. MA_CHANNEL_POSITION_COUNT = (MA_CHANNEL_AUX_31 + 1)
  3321. } _ma_channel_position; /* Do not use `_ma_channel_position` directly. Use `ma_channel` instead. */
  3322. typedef enum
  3323. {
  3324. MA_SUCCESS = 0,
  3325. MA_ERROR = -1, /* A generic error. */
  3326. MA_INVALID_ARGS = -2,
  3327. MA_INVALID_OPERATION = -3,
  3328. MA_OUT_OF_MEMORY = -4,
  3329. MA_OUT_OF_RANGE = -5,
  3330. MA_ACCESS_DENIED = -6,
  3331. MA_DOES_NOT_EXIST = -7,
  3332. MA_ALREADY_EXISTS = -8,
  3333. MA_TOO_MANY_OPEN_FILES = -9,
  3334. MA_INVALID_FILE = -10,
  3335. MA_TOO_BIG = -11,
  3336. MA_PATH_TOO_LONG = -12,
  3337. MA_NAME_TOO_LONG = -13,
  3338. MA_NOT_DIRECTORY = -14,
  3339. MA_IS_DIRECTORY = -15,
  3340. MA_DIRECTORY_NOT_EMPTY = -16,
  3341. MA_AT_END = -17,
  3342. MA_NO_SPACE = -18,
  3343. MA_BUSY = -19,
  3344. MA_IO_ERROR = -20,
  3345. MA_INTERRUPT = -21,
  3346. MA_UNAVAILABLE = -22,
  3347. MA_ALREADY_IN_USE = -23,
  3348. MA_BAD_ADDRESS = -24,
  3349. MA_BAD_SEEK = -25,
  3350. MA_BAD_PIPE = -26,
  3351. MA_DEADLOCK = -27,
  3352. MA_TOO_MANY_LINKS = -28,
  3353. MA_NOT_IMPLEMENTED = -29,
  3354. MA_NO_MESSAGE = -30,
  3355. MA_BAD_MESSAGE = -31,
  3356. MA_NO_DATA_AVAILABLE = -32,
  3357. MA_INVALID_DATA = -33,
  3358. MA_TIMEOUT = -34,
  3359. MA_NO_NETWORK = -35,
  3360. MA_NOT_UNIQUE = -36,
  3361. MA_NOT_SOCKET = -37,
  3362. MA_NO_ADDRESS = -38,
  3363. MA_BAD_PROTOCOL = -39,
  3364. MA_PROTOCOL_UNAVAILABLE = -40,
  3365. MA_PROTOCOL_NOT_SUPPORTED = -41,
  3366. MA_PROTOCOL_FAMILY_NOT_SUPPORTED = -42,
  3367. MA_ADDRESS_FAMILY_NOT_SUPPORTED = -43,
  3368. MA_SOCKET_NOT_SUPPORTED = -44,
  3369. MA_CONNECTION_RESET = -45,
  3370. MA_ALREADY_CONNECTED = -46,
  3371. MA_NOT_CONNECTED = -47,
  3372. MA_CONNECTION_REFUSED = -48,
  3373. MA_NO_HOST = -49,
  3374. MA_IN_PROGRESS = -50,
  3375. MA_CANCELLED = -51,
  3376. MA_MEMORY_ALREADY_MAPPED = -52,
  3377. /* General miniaudio-specific errors. */
  3378. MA_FORMAT_NOT_SUPPORTED = -100,
  3379. MA_DEVICE_TYPE_NOT_SUPPORTED = -101,
  3380. MA_SHARE_MODE_NOT_SUPPORTED = -102,
  3381. MA_NO_BACKEND = -103,
  3382. MA_NO_DEVICE = -104,
  3383. MA_API_NOT_FOUND = -105,
  3384. MA_INVALID_DEVICE_CONFIG = -106,
  3385. MA_LOOP = -107,
  3386. MA_BACKEND_NOT_ENABLED = -108,
  3387. /* State errors. */
  3388. MA_DEVICE_NOT_INITIALIZED = -200,
  3389. MA_DEVICE_ALREADY_INITIALIZED = -201,
  3390. MA_DEVICE_NOT_STARTED = -202,
  3391. MA_DEVICE_NOT_STOPPED = -203,
  3392. /* Operation errors. */
  3393. MA_FAILED_TO_INIT_BACKEND = -300,
  3394. MA_FAILED_TO_OPEN_BACKEND_DEVICE = -301,
  3395. MA_FAILED_TO_START_BACKEND_DEVICE = -302,
  3396. MA_FAILED_TO_STOP_BACKEND_DEVICE = -303
  3397. } ma_result;
  3398. #define MA_MIN_CHANNELS 1
  3399. #ifndef MA_MAX_CHANNELS
  3400. #define MA_MAX_CHANNELS 254
  3401. #endif
  3402. #ifndef MA_MAX_FILTER_ORDER
  3403. #define MA_MAX_FILTER_ORDER 8
  3404. #endif
  3405. typedef enum
  3406. {
  3407. ma_stream_format_pcm = 0
  3408. } ma_stream_format;
  3409. typedef enum
  3410. {
  3411. ma_stream_layout_interleaved = 0,
  3412. ma_stream_layout_deinterleaved
  3413. } ma_stream_layout;
  3414. typedef enum
  3415. {
  3416. ma_dither_mode_none = 0,
  3417. ma_dither_mode_rectangle,
  3418. ma_dither_mode_triangle
  3419. } ma_dither_mode;
  3420. typedef enum
  3421. {
  3422. /*
  3423. I like to keep these explicitly defined because they're used as a key into a lookup table. When items are
  3424. added to this, make sure there are no gaps and that they're added to the lookup table in ma_get_bytes_per_sample().
  3425. */
  3426. ma_format_unknown = 0, /* Mainly used for indicating an error, but also used as the default for the output format for decoders. */
  3427. ma_format_u8 = 1,
  3428. ma_format_s16 = 2, /* Seems to be the most widely supported format. */
  3429. ma_format_s24 = 3, /* Tightly packed. 3 bytes per sample. */
  3430. ma_format_s32 = 4,
  3431. ma_format_f32 = 5,
  3432. ma_format_count
  3433. } ma_format;
  3434. typedef enum
  3435. {
  3436. /* Standard rates need to be in priority order. */
  3437. ma_standard_sample_rate_48000 = 48000, /* Most common */
  3438. ma_standard_sample_rate_44100 = 44100,
  3439. ma_standard_sample_rate_32000 = 32000, /* Lows */
  3440. ma_standard_sample_rate_24000 = 24000,
  3441. ma_standard_sample_rate_22050 = 22050,
  3442. ma_standard_sample_rate_88200 = 88200, /* Highs */
  3443. ma_standard_sample_rate_96000 = 96000,
  3444. ma_standard_sample_rate_176400 = 176400,
  3445. ma_standard_sample_rate_192000 = 192000,
  3446. ma_standard_sample_rate_16000 = 16000, /* Extreme lows */
  3447. ma_standard_sample_rate_11025 = 11250,
  3448. ma_standard_sample_rate_8000 = 8000,
  3449. ma_standard_sample_rate_352800 = 352800, /* Extreme highs */
  3450. ma_standard_sample_rate_384000 = 384000,
  3451. ma_standard_sample_rate_min = ma_standard_sample_rate_8000,
  3452. ma_standard_sample_rate_max = ma_standard_sample_rate_384000,
  3453. ma_standard_sample_rate_count = 14 /* Need to maintain the count manually. Make sure this is updated if items are added to enum. */
  3454. } ma_standard_sample_rate;
  3455. typedef enum
  3456. {
  3457. ma_channel_mix_mode_rectangular = 0, /* Simple averaging based on the plane(s) the channel is sitting on. */
  3458. ma_channel_mix_mode_simple, /* Drop excess channels; zeroed out extra channels. */
  3459. ma_channel_mix_mode_custom_weights, /* Use custom weights specified in ma_channel_converter_config. */
  3460. ma_channel_mix_mode_default = ma_channel_mix_mode_rectangular
  3461. } ma_channel_mix_mode;
  3462. typedef enum
  3463. {
  3464. ma_standard_channel_map_microsoft,
  3465. ma_standard_channel_map_alsa,
  3466. ma_standard_channel_map_rfc3551, /* Based off AIFF. */
  3467. ma_standard_channel_map_flac,
  3468. ma_standard_channel_map_vorbis,
  3469. ma_standard_channel_map_sound4, /* FreeBSD's sound(4). */
  3470. ma_standard_channel_map_sndio, /* www.sndio.org/tips.html */
  3471. ma_standard_channel_map_webaudio = ma_standard_channel_map_flac, /* https://webaudio.github.io/web-audio-api/#ChannelOrdering. Only 1, 2, 4 and 6 channels are defined, but can fill in the gaps with logical assumptions. */
  3472. ma_standard_channel_map_default = ma_standard_channel_map_microsoft
  3473. } ma_standard_channel_map;
  3474. typedef enum
  3475. {
  3476. ma_performance_profile_low_latency = 0,
  3477. ma_performance_profile_conservative
  3478. } ma_performance_profile;
  3479. typedef struct
  3480. {
  3481. void* pUserData;
  3482. void* (* onMalloc)(size_t sz, void* pUserData);
  3483. void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  3484. void (* onFree)(void* p, void* pUserData);
  3485. } ma_allocation_callbacks;
  3486. typedef struct
  3487. {
  3488. ma_int32 state;
  3489. } ma_lcg;
  3490. /*
  3491. Atomics.
  3492. These are typesafe structures to prevent errors as a result of forgetting to reference variables atomically. It's too
  3493. easy to introduce subtle bugs where you accidentally do a regular assignment instead of an atomic load/store, etc. By
  3494. using a struct we can enforce the use of atomics at compile time.
  3495. These types are declared in the header section because we need to reference them in structs below, but functions for
  3496. using them are only exposed in the implementation section. I do not want these to be part of the public API.
  3497. There's a few downsides to this system. The first is that you need to declare a new struct for each type. Below are
  3498. some macros to help with the declarations. They will be named like so:
  3499. ma_atomic_uint32 - atomic ma_uint32
  3500. ma_atomic_int32 - atomic ma_int32
  3501. ma_atomic_uint64 - atomic ma_uint64
  3502. ma_atomic_float - atomic float
  3503. ma_atomic_bool32 - atomic ma_bool32
  3504. The other downside is that atomic pointers are extremely messy. You need to declare a new struct for each specific
  3505. type of pointer you need to make atomic. For example, an atomic ma_node* will look like this:
  3506. MA_ATOMIC_SAFE_TYPE_IMPL_PTR(node)
  3507. Which will declare a type struct that's named like so:
  3508. ma_atomic_ptr_node
  3509. Functions to use the atomic types are declared in the implementation section. All atomic functions are prefixed with
  3510. the name of the struct. For example:
  3511. ma_atomic_uint32_set() - Atomic store of ma_uint32
  3512. ma_atomic_uint32_get() - Atomic load of ma_uint32
  3513. etc.
  3514. For pointer types it's the same, which makes them a bit messy to use due to the length of each function name, but in
  3515. return you get type safety and enforcement of atomic operations.
  3516. */
  3517. #define MA_ATOMIC_SAFE_TYPE_DECL(c89TypeExtension, typeSize, type) \
  3518. typedef struct \
  3519. { \
  3520. MA_ATOMIC(typeSize, ma_##type) value; \
  3521. } ma_atomic_##type; \
  3522. #define MA_ATOMIC_SAFE_TYPE_DECL_PTR(type) \
  3523. typedef struct \
  3524. { \
  3525. MA_ATOMIC(MA_SIZEOF_PTR, ma_##type*) value; \
  3526. } ma_atomic_ptr_##type; \
  3527. MA_ATOMIC_SAFE_TYPE_DECL(32, 4, uint32)
  3528. MA_ATOMIC_SAFE_TYPE_DECL(i32, 4, int32)
  3529. MA_ATOMIC_SAFE_TYPE_DECL(64, 8, uint64)
  3530. MA_ATOMIC_SAFE_TYPE_DECL(f32, 4, float)
  3531. MA_ATOMIC_SAFE_TYPE_DECL(32, 4, bool32)
  3532. /* Spinlocks are 32-bit for compatibility reasons. */
  3533. typedef ma_uint32 ma_spinlock;
  3534. #ifndef MA_NO_THREADING
  3535. /* Thread priorities should be ordered such that the default priority of the worker thread is 0. */
  3536. typedef enum
  3537. {
  3538. ma_thread_priority_idle = -5,
  3539. ma_thread_priority_lowest = -4,
  3540. ma_thread_priority_low = -3,
  3541. ma_thread_priority_normal = -2,
  3542. ma_thread_priority_high = -1,
  3543. ma_thread_priority_highest = 0,
  3544. ma_thread_priority_realtime = 1,
  3545. ma_thread_priority_default = 0
  3546. } ma_thread_priority;
  3547. #if defined(MA_POSIX)
  3548. typedef ma_pthread_t ma_thread;
  3549. #elif defined(MA_WIN32)
  3550. typedef ma_handle ma_thread;
  3551. #endif
  3552. #if defined(MA_POSIX)
  3553. typedef ma_pthread_mutex_t ma_mutex;
  3554. #elif defined(MA_WIN32)
  3555. typedef ma_handle ma_mutex;
  3556. #endif
  3557. #if defined(MA_POSIX)
  3558. typedef struct
  3559. {
  3560. ma_uint32 value;
  3561. ma_pthread_mutex_t lock;
  3562. ma_pthread_cond_t cond;
  3563. } ma_event;
  3564. #elif defined(MA_WIN32)
  3565. typedef ma_handle ma_event;
  3566. #endif
  3567. #if defined(MA_POSIX)
  3568. typedef struct
  3569. {
  3570. int value;
  3571. ma_pthread_mutex_t lock;
  3572. ma_pthread_cond_t cond;
  3573. } ma_semaphore;
  3574. #elif defined(MA_WIN32)
  3575. typedef ma_handle ma_semaphore;
  3576. #endif
  3577. #else
  3578. /* MA_NO_THREADING is set which means threading is disabled. Threading is required by some API families. If any of these are enabled we need to throw an error. */
  3579. #ifndef MA_NO_DEVICE_IO
  3580. #error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO";
  3581. #endif
  3582. #endif /* MA_NO_THREADING */
  3583. /*
  3584. Retrieves the version of miniaudio as separated integers. Each component can be NULL if it's not required.
  3585. */
  3586. MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision);
  3587. /*
  3588. Retrieves the version of miniaudio as a string which can be useful for logging purposes.
  3589. */
  3590. MA_API const char* ma_version_string(void);
  3591. /**************************************************************************************************************************************************************
  3592. Logging
  3593. **************************************************************************************************************************************************************/
  3594. #include <stdarg.h> /* For va_list. */
  3595. #if defined(__has_attribute)
  3596. #if __has_attribute(format)
  3597. #define MA_ATTRIBUTE_FORMAT(fmt, va) __attribute__((format(printf, fmt, va)))
  3598. #endif
  3599. #endif
  3600. #ifndef MA_ATTRIBUTE_FORMAT
  3601. #define MA_ATTRIBUTE_FORMAT(fmt, va)
  3602. #endif
  3603. #ifndef MA_MAX_LOG_CALLBACKS
  3604. #define MA_MAX_LOG_CALLBACKS 4
  3605. #endif
  3606. /*
  3607. The callback for handling log messages.
  3608. Parameters
  3609. ----------
  3610. pUserData (in)
  3611. The user data pointer that was passed into ma_log_register_callback().
  3612. logLevel (in)
  3613. The log level. This can be one of the following:
  3614. +----------------------+
  3615. | Log Level |
  3616. +----------------------+
  3617. | MA_LOG_LEVEL_DEBUG |
  3618. | MA_LOG_LEVEL_INFO |
  3619. | MA_LOG_LEVEL_WARNING |
  3620. | MA_LOG_LEVEL_ERROR |
  3621. +----------------------+
  3622. pMessage (in)
  3623. The log message.
  3624. */
  3625. typedef void (* ma_log_callback_proc)(void* pUserData, ma_uint32 level, const char* pMessage);
  3626. typedef struct
  3627. {
  3628. ma_log_callback_proc onLog;
  3629. void* pUserData;
  3630. } ma_log_callback;
  3631. MA_API ma_log_callback ma_log_callback_init(ma_log_callback_proc onLog, void* pUserData);
  3632. typedef struct
  3633. {
  3634. ma_log_callback callbacks[MA_MAX_LOG_CALLBACKS];
  3635. ma_uint32 callbackCount;
  3636. ma_allocation_callbacks allocationCallbacks; /* Need to store these persistently because ma_log_postv() might need to allocate a buffer on the heap. */
  3637. #ifndef MA_NO_THREADING
  3638. ma_mutex lock; /* For thread safety just to make it easier and safer for the logging implementation. */
  3639. #endif
  3640. } ma_log;
  3641. MA_API ma_result ma_log_init(const ma_allocation_callbacks* pAllocationCallbacks, ma_log* pLog);
  3642. MA_API void ma_log_uninit(ma_log* pLog);
  3643. MA_API ma_result ma_log_register_callback(ma_log* pLog, ma_log_callback callback);
  3644. MA_API ma_result ma_log_unregister_callback(ma_log* pLog, ma_log_callback callback);
  3645. MA_API ma_result ma_log_post(ma_log* pLog, ma_uint32 level, const char* pMessage);
  3646. MA_API ma_result ma_log_postv(ma_log* pLog, ma_uint32 level, const char* pFormat, va_list args);
  3647. MA_API ma_result ma_log_postf(ma_log* pLog, ma_uint32 level, const char* pFormat, ...) MA_ATTRIBUTE_FORMAT(3, 4);
  3648. /**************************************************************************************************************************************************************
  3649. Biquad Filtering
  3650. **************************************************************************************************************************************************************/
  3651. typedef union
  3652. {
  3653. float f32;
  3654. ma_int32 s32;
  3655. } ma_biquad_coefficient;
  3656. typedef struct
  3657. {
  3658. ma_format format;
  3659. ma_uint32 channels;
  3660. double b0;
  3661. double b1;
  3662. double b2;
  3663. double a0;
  3664. double a1;
  3665. double a2;
  3666. } ma_biquad_config;
  3667. MA_API ma_biquad_config ma_biquad_config_init(ma_format format, ma_uint32 channels, double b0, double b1, double b2, double a0, double a1, double a2);
  3668. typedef struct
  3669. {
  3670. ma_format format;
  3671. ma_uint32 channels;
  3672. ma_biquad_coefficient b0;
  3673. ma_biquad_coefficient b1;
  3674. ma_biquad_coefficient b2;
  3675. ma_biquad_coefficient a1;
  3676. ma_biquad_coefficient a2;
  3677. ma_biquad_coefficient* pR1;
  3678. ma_biquad_coefficient* pR2;
  3679. /* Memory management. */
  3680. void* _pHeap;
  3681. ma_bool32 _ownsHeap;
  3682. } ma_biquad;
  3683. MA_API ma_result ma_biquad_get_heap_size(const ma_biquad_config* pConfig, size_t* pHeapSizeInBytes);
  3684. MA_API ma_result ma_biquad_init_preallocated(const ma_biquad_config* pConfig, void* pHeap, ma_biquad* pBQ);
  3685. MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad* pBQ);
  3686. MA_API void ma_biquad_uninit(ma_biquad* pBQ, const ma_allocation_callbacks* pAllocationCallbacks);
  3687. MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ);
  3688. MA_API ma_result ma_biquad_clear_cache(ma_biquad* pBQ);
  3689. MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3690. MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ);
  3691. /**************************************************************************************************************************************************************
  3692. Low-Pass Filtering
  3693. **************************************************************************************************************************************************************/
  3694. typedef struct
  3695. {
  3696. ma_format format;
  3697. ma_uint32 channels;
  3698. ma_uint32 sampleRate;
  3699. double cutoffFrequency;
  3700. double q;
  3701. } ma_lpf1_config, ma_lpf2_config;
  3702. MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
  3703. MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
  3704. typedef struct
  3705. {
  3706. ma_format format;
  3707. ma_uint32 channels;
  3708. ma_biquad_coefficient a;
  3709. ma_biquad_coefficient* pR1;
  3710. /* Memory management. */
  3711. void* _pHeap;
  3712. ma_bool32 _ownsHeap;
  3713. } ma_lpf1;
  3714. MA_API ma_result ma_lpf1_get_heap_size(const ma_lpf1_config* pConfig, size_t* pHeapSizeInBytes);
  3715. MA_API ma_result ma_lpf1_init_preallocated(const ma_lpf1_config* pConfig, void* pHeap, ma_lpf1* pLPF);
  3716. MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf1* pLPF);
  3717. MA_API void ma_lpf1_uninit(ma_lpf1* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3718. MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF);
  3719. MA_API ma_result ma_lpf1_clear_cache(ma_lpf1* pLPF);
  3720. MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3721. MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF);
  3722. typedef struct
  3723. {
  3724. ma_biquad bq; /* The second order low-pass filter is implemented as a biquad filter. */
  3725. } ma_lpf2;
  3726. MA_API ma_result ma_lpf2_get_heap_size(const ma_lpf2_config* pConfig, size_t* pHeapSizeInBytes);
  3727. MA_API ma_result ma_lpf2_init_preallocated(const ma_lpf2_config* pConfig, void* pHeap, ma_lpf2* pHPF);
  3728. MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf2* pLPF);
  3729. MA_API void ma_lpf2_uninit(ma_lpf2* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3730. MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF);
  3731. MA_API ma_result ma_lpf2_clear_cache(ma_lpf2* pLPF);
  3732. MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3733. MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF);
  3734. typedef struct
  3735. {
  3736. ma_format format;
  3737. ma_uint32 channels;
  3738. ma_uint32 sampleRate;
  3739. double cutoffFrequency;
  3740. ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
  3741. } ma_lpf_config;
  3742. MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  3743. typedef struct
  3744. {
  3745. ma_format format;
  3746. ma_uint32 channels;
  3747. ma_uint32 sampleRate;
  3748. ma_uint32 lpf1Count;
  3749. ma_uint32 lpf2Count;
  3750. ma_lpf1* pLPF1;
  3751. ma_lpf2* pLPF2;
  3752. /* Memory management. */
  3753. void* _pHeap;
  3754. ma_bool32 _ownsHeap;
  3755. } ma_lpf;
  3756. MA_API ma_result ma_lpf_get_heap_size(const ma_lpf_config* pConfig, size_t* pHeapSizeInBytes);
  3757. MA_API ma_result ma_lpf_init_preallocated(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF);
  3758. MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf* pLPF);
  3759. MA_API void ma_lpf_uninit(ma_lpf* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3760. MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF);
  3761. MA_API ma_result ma_lpf_clear_cache(ma_lpf* pLPF);
  3762. MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3763. MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF);
  3764. /**************************************************************************************************************************************************************
  3765. High-Pass Filtering
  3766. **************************************************************************************************************************************************************/
  3767. typedef struct
  3768. {
  3769. ma_format format;
  3770. ma_uint32 channels;
  3771. ma_uint32 sampleRate;
  3772. double cutoffFrequency;
  3773. double q;
  3774. } ma_hpf1_config, ma_hpf2_config;
  3775. MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
  3776. MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
  3777. typedef struct
  3778. {
  3779. ma_format format;
  3780. ma_uint32 channels;
  3781. ma_biquad_coefficient a;
  3782. ma_biquad_coefficient* pR1;
  3783. /* Memory management. */
  3784. void* _pHeap;
  3785. ma_bool32 _ownsHeap;
  3786. } ma_hpf1;
  3787. MA_API ma_result ma_hpf1_get_heap_size(const ma_hpf1_config* pConfig, size_t* pHeapSizeInBytes);
  3788. MA_API ma_result ma_hpf1_init_preallocated(const ma_hpf1_config* pConfig, void* pHeap, ma_hpf1* pLPF);
  3789. MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf1* pHPF);
  3790. MA_API void ma_hpf1_uninit(ma_hpf1* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3791. MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF);
  3792. MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3793. MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF);
  3794. typedef struct
  3795. {
  3796. ma_biquad bq; /* The second order high-pass filter is implemented as a biquad filter. */
  3797. } ma_hpf2;
  3798. MA_API ma_result ma_hpf2_get_heap_size(const ma_hpf2_config* pConfig, size_t* pHeapSizeInBytes);
  3799. MA_API ma_result ma_hpf2_init_preallocated(const ma_hpf2_config* pConfig, void* pHeap, ma_hpf2* pHPF);
  3800. MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf2* pHPF);
  3801. MA_API void ma_hpf2_uninit(ma_hpf2* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3802. MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF);
  3803. MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3804. MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF);
  3805. typedef struct
  3806. {
  3807. ma_format format;
  3808. ma_uint32 channels;
  3809. ma_uint32 sampleRate;
  3810. double cutoffFrequency;
  3811. ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
  3812. } ma_hpf_config;
  3813. MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  3814. typedef struct
  3815. {
  3816. ma_format format;
  3817. ma_uint32 channels;
  3818. ma_uint32 sampleRate;
  3819. ma_uint32 hpf1Count;
  3820. ma_uint32 hpf2Count;
  3821. ma_hpf1* pHPF1;
  3822. ma_hpf2* pHPF2;
  3823. /* Memory management. */
  3824. void* _pHeap;
  3825. ma_bool32 _ownsHeap;
  3826. } ma_hpf;
  3827. MA_API ma_result ma_hpf_get_heap_size(const ma_hpf_config* pConfig, size_t* pHeapSizeInBytes);
  3828. MA_API ma_result ma_hpf_init_preallocated(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pLPF);
  3829. MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf* pHPF);
  3830. MA_API void ma_hpf_uninit(ma_hpf* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3831. MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF);
  3832. MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3833. MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF);
  3834. /**************************************************************************************************************************************************************
  3835. Band-Pass Filtering
  3836. **************************************************************************************************************************************************************/
  3837. typedef struct
  3838. {
  3839. ma_format format;
  3840. ma_uint32 channels;
  3841. ma_uint32 sampleRate;
  3842. double cutoffFrequency;
  3843. double q;
  3844. } ma_bpf2_config;
  3845. MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
  3846. typedef struct
  3847. {
  3848. ma_biquad bq; /* The second order band-pass filter is implemented as a biquad filter. */
  3849. } ma_bpf2;
  3850. MA_API ma_result ma_bpf2_get_heap_size(const ma_bpf2_config* pConfig, size_t* pHeapSizeInBytes);
  3851. MA_API ma_result ma_bpf2_init_preallocated(const ma_bpf2_config* pConfig, void* pHeap, ma_bpf2* pBPF);
  3852. MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf2* pBPF);
  3853. MA_API void ma_bpf2_uninit(ma_bpf2* pBPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3854. MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF);
  3855. MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3856. MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF);
  3857. typedef struct
  3858. {
  3859. ma_format format;
  3860. ma_uint32 channels;
  3861. ma_uint32 sampleRate;
  3862. double cutoffFrequency;
  3863. ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
  3864. } ma_bpf_config;
  3865. MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  3866. typedef struct
  3867. {
  3868. ma_format format;
  3869. ma_uint32 channels;
  3870. ma_uint32 bpf2Count;
  3871. ma_bpf2* pBPF2;
  3872. /* Memory management. */
  3873. void* _pHeap;
  3874. ma_bool32 _ownsHeap;
  3875. } ma_bpf;
  3876. MA_API ma_result ma_bpf_get_heap_size(const ma_bpf_config* pConfig, size_t* pHeapSizeInBytes);
  3877. MA_API ma_result ma_bpf_init_preallocated(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF);
  3878. MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf* pBPF);
  3879. MA_API void ma_bpf_uninit(ma_bpf* pBPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3880. MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF);
  3881. MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3882. MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF);
  3883. /**************************************************************************************************************************************************************
  3884. Notching Filter
  3885. **************************************************************************************************************************************************************/
  3886. typedef struct
  3887. {
  3888. ma_format format;
  3889. ma_uint32 channels;
  3890. ma_uint32 sampleRate;
  3891. double q;
  3892. double frequency;
  3893. } ma_notch2_config, ma_notch_config;
  3894. MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency);
  3895. typedef struct
  3896. {
  3897. ma_biquad bq;
  3898. } ma_notch2;
  3899. MA_API ma_result ma_notch2_get_heap_size(const ma_notch2_config* pConfig, size_t* pHeapSizeInBytes);
  3900. MA_API ma_result ma_notch2_init_preallocated(const ma_notch2_config* pConfig, void* pHeap, ma_notch2* pFilter);
  3901. MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch2* pFilter);
  3902. MA_API void ma_notch2_uninit(ma_notch2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3903. MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter);
  3904. MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3905. MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter);
  3906. /**************************************************************************************************************************************************************
  3907. Peaking EQ Filter
  3908. **************************************************************************************************************************************************************/
  3909. typedef struct
  3910. {
  3911. ma_format format;
  3912. ma_uint32 channels;
  3913. ma_uint32 sampleRate;
  3914. double gainDB;
  3915. double q;
  3916. double frequency;
  3917. } ma_peak2_config, ma_peak_config;
  3918. MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  3919. typedef struct
  3920. {
  3921. ma_biquad bq;
  3922. } ma_peak2;
  3923. MA_API ma_result ma_peak2_get_heap_size(const ma_peak2_config* pConfig, size_t* pHeapSizeInBytes);
  3924. MA_API ma_result ma_peak2_init_preallocated(const ma_peak2_config* pConfig, void* pHeap, ma_peak2* pFilter);
  3925. MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak2* pFilter);
  3926. MA_API void ma_peak2_uninit(ma_peak2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3927. MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter);
  3928. MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3929. MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter);
  3930. /**************************************************************************************************************************************************************
  3931. Low Shelf Filter
  3932. **************************************************************************************************************************************************************/
  3933. typedef struct
  3934. {
  3935. ma_format format;
  3936. ma_uint32 channels;
  3937. ma_uint32 sampleRate;
  3938. double gainDB;
  3939. double shelfSlope;
  3940. double frequency;
  3941. } ma_loshelf2_config, ma_loshelf_config;
  3942. MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
  3943. typedef struct
  3944. {
  3945. ma_biquad bq;
  3946. } ma_loshelf2;
  3947. MA_API ma_result ma_loshelf2_get_heap_size(const ma_loshelf2_config* pConfig, size_t* pHeapSizeInBytes);
  3948. MA_API ma_result ma_loshelf2_init_preallocated(const ma_loshelf2_config* pConfig, void* pHeap, ma_loshelf2* pFilter);
  3949. MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf2* pFilter);
  3950. MA_API void ma_loshelf2_uninit(ma_loshelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3951. MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter);
  3952. MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3953. MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter);
  3954. /**************************************************************************************************************************************************************
  3955. High Shelf Filter
  3956. **************************************************************************************************************************************************************/
  3957. typedef struct
  3958. {
  3959. ma_format format;
  3960. ma_uint32 channels;
  3961. ma_uint32 sampleRate;
  3962. double gainDB;
  3963. double shelfSlope;
  3964. double frequency;
  3965. } ma_hishelf2_config, ma_hishelf_config;
  3966. MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
  3967. typedef struct
  3968. {
  3969. ma_biquad bq;
  3970. } ma_hishelf2;
  3971. MA_API ma_result ma_hishelf2_get_heap_size(const ma_hishelf2_config* pConfig, size_t* pHeapSizeInBytes);
  3972. MA_API ma_result ma_hishelf2_init_preallocated(const ma_hishelf2_config* pConfig, void* pHeap, ma_hishelf2* pFilter);
  3973. MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf2* pFilter);
  3974. MA_API void ma_hishelf2_uninit(ma_hishelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3975. MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter);
  3976. MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3977. MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter);
  3978. /*
  3979. Delay
  3980. */
  3981. typedef struct
  3982. {
  3983. ma_uint32 channels;
  3984. ma_uint32 sampleRate;
  3985. ma_uint32 delayInFrames;
  3986. ma_bool32 delayStart; /* Set to true to delay the start of the output; false otherwise. */
  3987. float wet; /* 0..1. Default = 1. */
  3988. float dry; /* 0..1. Default = 1. */
  3989. float decay; /* 0..1. Default = 0 (no feedback). Feedback decay. Use this for echo. */
  3990. } ma_delay_config;
  3991. MA_API ma_delay_config ma_delay_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay);
  3992. typedef struct
  3993. {
  3994. ma_delay_config config;
  3995. ma_uint32 cursor; /* Feedback is written to this cursor. Always equal or in front of the read cursor. */
  3996. ma_uint32 bufferSizeInFrames;
  3997. float* pBuffer;
  3998. } ma_delay;
  3999. MA_API ma_result ma_delay_init(const ma_delay_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay* pDelay);
  4000. MA_API void ma_delay_uninit(ma_delay* pDelay, const ma_allocation_callbacks* pAllocationCallbacks);
  4001. MA_API ma_result ma_delay_process_pcm_frames(ma_delay* pDelay, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount);
  4002. MA_API void ma_delay_set_wet(ma_delay* pDelay, float value);
  4003. MA_API float ma_delay_get_wet(const ma_delay* pDelay);
  4004. MA_API void ma_delay_set_dry(ma_delay* pDelay, float value);
  4005. MA_API float ma_delay_get_dry(const ma_delay* pDelay);
  4006. MA_API void ma_delay_set_decay(ma_delay* pDelay, float value);
  4007. MA_API float ma_delay_get_decay(const ma_delay* pDelay);
  4008. /* Gainer for smooth volume changes. */
  4009. typedef struct
  4010. {
  4011. ma_uint32 channels;
  4012. ma_uint32 smoothTimeInFrames;
  4013. } ma_gainer_config;
  4014. MA_API ma_gainer_config ma_gainer_config_init(ma_uint32 channels, ma_uint32 smoothTimeInFrames);
  4015. typedef struct
  4016. {
  4017. ma_gainer_config config;
  4018. ma_uint32 t;
  4019. float masterVolume;
  4020. float* pOldGains;
  4021. float* pNewGains;
  4022. /* Memory management. */
  4023. void* _pHeap;
  4024. ma_bool32 _ownsHeap;
  4025. } ma_gainer;
  4026. MA_API ma_result ma_gainer_get_heap_size(const ma_gainer_config* pConfig, size_t* pHeapSizeInBytes);
  4027. MA_API ma_result ma_gainer_init_preallocated(const ma_gainer_config* pConfig, void* pHeap, ma_gainer* pGainer);
  4028. MA_API ma_result ma_gainer_init(const ma_gainer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_gainer* pGainer);
  4029. MA_API void ma_gainer_uninit(ma_gainer* pGainer, const ma_allocation_callbacks* pAllocationCallbacks);
  4030. MA_API ma_result ma_gainer_process_pcm_frames(ma_gainer* pGainer, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4031. MA_API ma_result ma_gainer_set_gain(ma_gainer* pGainer, float newGain);
  4032. MA_API ma_result ma_gainer_set_gains(ma_gainer* pGainer, float* pNewGains);
  4033. MA_API ma_result ma_gainer_set_master_volume(ma_gainer* pGainer, float volume);
  4034. MA_API ma_result ma_gainer_get_master_volume(const ma_gainer* pGainer, float* pVolume);
  4035. /* Stereo panner. */
  4036. typedef enum
  4037. {
  4038. ma_pan_mode_balance = 0, /* Does not blend one side with the other. Technically just a balance. Compatible with other popular audio engines and therefore the default. */
  4039. ma_pan_mode_pan /* A true pan. The sound from one side will "move" to the other side and blend with it. */
  4040. } ma_pan_mode;
  4041. typedef struct
  4042. {
  4043. ma_format format;
  4044. ma_uint32 channels;
  4045. ma_pan_mode mode;
  4046. float pan;
  4047. } ma_panner_config;
  4048. MA_API ma_panner_config ma_panner_config_init(ma_format format, ma_uint32 channels);
  4049. typedef struct
  4050. {
  4051. ma_format format;
  4052. ma_uint32 channels;
  4053. ma_pan_mode mode;
  4054. float pan; /* -1..1 where 0 is no pan, -1 is left side, +1 is right side. Defaults to 0. */
  4055. } ma_panner;
  4056. MA_API ma_result ma_panner_init(const ma_panner_config* pConfig, ma_panner* pPanner);
  4057. MA_API ma_result ma_panner_process_pcm_frames(ma_panner* pPanner, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4058. MA_API void ma_panner_set_mode(ma_panner* pPanner, ma_pan_mode mode);
  4059. MA_API ma_pan_mode ma_panner_get_mode(const ma_panner* pPanner);
  4060. MA_API void ma_panner_set_pan(ma_panner* pPanner, float pan);
  4061. MA_API float ma_panner_get_pan(const ma_panner* pPanner);
  4062. /* Fader. */
  4063. typedef struct
  4064. {
  4065. ma_format format;
  4066. ma_uint32 channels;
  4067. ma_uint32 sampleRate;
  4068. } ma_fader_config;
  4069. MA_API ma_fader_config ma_fader_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate);
  4070. typedef struct
  4071. {
  4072. ma_fader_config config;
  4073. float volumeBeg; /* If volumeBeg and volumeEnd is equal to 1, no fading happens (ma_fader_process_pcm_frames() will run as a passthrough). */
  4074. float volumeEnd;
  4075. ma_uint64 lengthInFrames; /* The total length of the fade. */
  4076. ma_uint64 cursorInFrames; /* The current time in frames. Incremented by ma_fader_process_pcm_frames(). */
  4077. } ma_fader;
  4078. MA_API ma_result ma_fader_init(const ma_fader_config* pConfig, ma_fader* pFader);
  4079. MA_API ma_result ma_fader_process_pcm_frames(ma_fader* pFader, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4080. MA_API void ma_fader_get_data_format(const ma_fader* pFader, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate);
  4081. MA_API void ma_fader_set_fade(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames);
  4082. MA_API float ma_fader_get_current_volume(const ma_fader* pFader);
  4083. /* Spatializer. */
  4084. typedef struct
  4085. {
  4086. float x;
  4087. float y;
  4088. float z;
  4089. } ma_vec3f;
  4090. typedef struct
  4091. {
  4092. ma_vec3f v;
  4093. ma_spinlock lock;
  4094. } ma_atomic_vec3f;
  4095. typedef enum
  4096. {
  4097. ma_attenuation_model_none, /* No distance attenuation and no spatialization. */
  4098. ma_attenuation_model_inverse, /* Equivalent to OpenAL's AL_INVERSE_DISTANCE_CLAMPED. */
  4099. ma_attenuation_model_linear, /* Linear attenuation. Equivalent to OpenAL's AL_LINEAR_DISTANCE_CLAMPED. */
  4100. ma_attenuation_model_exponential /* Exponential attenuation. Equivalent to OpenAL's AL_EXPONENT_DISTANCE_CLAMPED. */
  4101. } ma_attenuation_model;
  4102. typedef enum
  4103. {
  4104. ma_positioning_absolute,
  4105. ma_positioning_relative
  4106. } ma_positioning;
  4107. typedef enum
  4108. {
  4109. ma_handedness_right,
  4110. ma_handedness_left
  4111. } ma_handedness;
  4112. typedef struct
  4113. {
  4114. ma_uint32 channelsOut;
  4115. ma_channel* pChannelMapOut;
  4116. ma_handedness handedness; /* Defaults to right. Forward is -1 on the Z axis. In a left handed system, forward is +1 on the Z axis. */
  4117. float coneInnerAngleInRadians;
  4118. float coneOuterAngleInRadians;
  4119. float coneOuterGain;
  4120. float speedOfSound;
  4121. ma_vec3f worldUp;
  4122. } ma_spatializer_listener_config;
  4123. MA_API ma_spatializer_listener_config ma_spatializer_listener_config_init(ma_uint32 channelsOut);
  4124. typedef struct
  4125. {
  4126. ma_spatializer_listener_config config;
  4127. ma_atomic_vec3f position; /* The absolute position of the listener. */
  4128. ma_atomic_vec3f direction; /* The direction the listener is facing. The world up vector is config.worldUp. */
  4129. ma_atomic_vec3f velocity;
  4130. ma_bool32 isEnabled;
  4131. /* Memory management. */
  4132. ma_bool32 _ownsHeap;
  4133. void* _pHeap;
  4134. } ma_spatializer_listener;
  4135. MA_API ma_result ma_spatializer_listener_get_heap_size(const ma_spatializer_listener_config* pConfig, size_t* pHeapSizeInBytes);
  4136. MA_API ma_result ma_spatializer_listener_init_preallocated(const ma_spatializer_listener_config* pConfig, void* pHeap, ma_spatializer_listener* pListener);
  4137. MA_API ma_result ma_spatializer_listener_init(const ma_spatializer_listener_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer_listener* pListener);
  4138. MA_API void ma_spatializer_listener_uninit(ma_spatializer_listener* pListener, const ma_allocation_callbacks* pAllocationCallbacks);
  4139. MA_API ma_channel* ma_spatializer_listener_get_channel_map(ma_spatializer_listener* pListener);
  4140. MA_API void ma_spatializer_listener_set_cone(ma_spatializer_listener* pListener, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  4141. MA_API void ma_spatializer_listener_get_cone(const ma_spatializer_listener* pListener, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  4142. MA_API void ma_spatializer_listener_set_position(ma_spatializer_listener* pListener, float x, float y, float z);
  4143. MA_API ma_vec3f ma_spatializer_listener_get_position(const ma_spatializer_listener* pListener);
  4144. MA_API void ma_spatializer_listener_set_direction(ma_spatializer_listener* pListener, float x, float y, float z);
  4145. MA_API ma_vec3f ma_spatializer_listener_get_direction(const ma_spatializer_listener* pListener);
  4146. MA_API void ma_spatializer_listener_set_velocity(ma_spatializer_listener* pListener, float x, float y, float z);
  4147. MA_API ma_vec3f ma_spatializer_listener_get_velocity(const ma_spatializer_listener* pListener);
  4148. MA_API void ma_spatializer_listener_set_speed_of_sound(ma_spatializer_listener* pListener, float speedOfSound);
  4149. MA_API float ma_spatializer_listener_get_speed_of_sound(const ma_spatializer_listener* pListener);
  4150. MA_API void ma_spatializer_listener_set_world_up(ma_spatializer_listener* pListener, float x, float y, float z);
  4151. MA_API ma_vec3f ma_spatializer_listener_get_world_up(const ma_spatializer_listener* pListener);
  4152. MA_API void ma_spatializer_listener_set_enabled(ma_spatializer_listener* pListener, ma_bool32 isEnabled);
  4153. MA_API ma_bool32 ma_spatializer_listener_is_enabled(const ma_spatializer_listener* pListener);
  4154. typedef struct
  4155. {
  4156. ma_uint32 channelsIn;
  4157. ma_uint32 channelsOut;
  4158. ma_channel* pChannelMapIn;
  4159. ma_attenuation_model attenuationModel;
  4160. ma_positioning positioning;
  4161. ma_handedness handedness; /* Defaults to right. Forward is -1 on the Z axis. In a left handed system, forward is +1 on the Z axis. */
  4162. float minGain;
  4163. float maxGain;
  4164. float minDistance;
  4165. float maxDistance;
  4166. float rolloff;
  4167. float coneInnerAngleInRadians;
  4168. float coneOuterAngleInRadians;
  4169. float coneOuterGain;
  4170. float dopplerFactor; /* Set to 0 to disable doppler effect. */
  4171. float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */
  4172. float minSpatializationChannelGain; /* The minimal scaling factor to apply to channel gains when accounting for the direction of the sound relative to the listener. Must be in the range of 0..1. Smaller values means more aggressive directional panning, larger values means more subtle directional panning. */
  4173. ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */
  4174. } ma_spatializer_config;
  4175. MA_API ma_spatializer_config ma_spatializer_config_init(ma_uint32 channelsIn, ma_uint32 channelsOut);
  4176. typedef struct
  4177. {
  4178. ma_uint32 channelsIn;
  4179. ma_uint32 channelsOut;
  4180. ma_channel* pChannelMapIn;
  4181. ma_attenuation_model attenuationModel;
  4182. ma_positioning positioning;
  4183. ma_handedness handedness; /* Defaults to right. Forward is -1 on the Z axis. In a left handed system, forward is +1 on the Z axis. */
  4184. float minGain;
  4185. float maxGain;
  4186. float minDistance;
  4187. float maxDistance;
  4188. float rolloff;
  4189. float coneInnerAngleInRadians;
  4190. float coneOuterAngleInRadians;
  4191. float coneOuterGain;
  4192. float dopplerFactor; /* Set to 0 to disable doppler effect. */
  4193. float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */
  4194. ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */
  4195. ma_atomic_vec3f position;
  4196. ma_atomic_vec3f direction;
  4197. ma_atomic_vec3f velocity; /* For doppler effect. */
  4198. float dopplerPitch; /* Will be updated by ma_spatializer_process_pcm_frames() and can be used by higher level functions to apply a pitch shift for doppler effect. */
  4199. float minSpatializationChannelGain;
  4200. ma_gainer gainer; /* For smooth gain transitions. */
  4201. float* pNewChannelGainsOut; /* An offset of _pHeap. Used by ma_spatializer_process_pcm_frames() to store new channel gains. The number of elements in this array is equal to config.channelsOut. */
  4202. /* Memory management. */
  4203. void* _pHeap;
  4204. ma_bool32 _ownsHeap;
  4205. } ma_spatializer;
  4206. MA_API ma_result ma_spatializer_get_heap_size(const ma_spatializer_config* pConfig, size_t* pHeapSizeInBytes);
  4207. MA_API ma_result ma_spatializer_init_preallocated(const ma_spatializer_config* pConfig, void* pHeap, ma_spatializer* pSpatializer);
  4208. MA_API ma_result ma_spatializer_init(const ma_spatializer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer* pSpatializer);
  4209. MA_API void ma_spatializer_uninit(ma_spatializer* pSpatializer, const ma_allocation_callbacks* pAllocationCallbacks);
  4210. MA_API ma_result ma_spatializer_process_pcm_frames(ma_spatializer* pSpatializer, ma_spatializer_listener* pListener, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4211. MA_API ma_result ma_spatializer_set_master_volume(ma_spatializer* pSpatializer, float volume);
  4212. MA_API ma_result ma_spatializer_get_master_volume(const ma_spatializer* pSpatializer, float* pVolume);
  4213. MA_API ma_uint32 ma_spatializer_get_input_channels(const ma_spatializer* pSpatializer);
  4214. MA_API ma_uint32 ma_spatializer_get_output_channels(const ma_spatializer* pSpatializer);
  4215. MA_API void ma_spatializer_set_attenuation_model(ma_spatializer* pSpatializer, ma_attenuation_model attenuationModel);
  4216. MA_API ma_attenuation_model ma_spatializer_get_attenuation_model(const ma_spatializer* pSpatializer);
  4217. MA_API void ma_spatializer_set_positioning(ma_spatializer* pSpatializer, ma_positioning positioning);
  4218. MA_API ma_positioning ma_spatializer_get_positioning(const ma_spatializer* pSpatializer);
  4219. MA_API void ma_spatializer_set_rolloff(ma_spatializer* pSpatializer, float rolloff);
  4220. MA_API float ma_spatializer_get_rolloff(const ma_spatializer* pSpatializer);
  4221. MA_API void ma_spatializer_set_min_gain(ma_spatializer* pSpatializer, float minGain);
  4222. MA_API float ma_spatializer_get_min_gain(const ma_spatializer* pSpatializer);
  4223. MA_API void ma_spatializer_set_max_gain(ma_spatializer* pSpatializer, float maxGain);
  4224. MA_API float ma_spatializer_get_max_gain(const ma_spatializer* pSpatializer);
  4225. MA_API void ma_spatializer_set_min_distance(ma_spatializer* pSpatializer, float minDistance);
  4226. MA_API float ma_spatializer_get_min_distance(const ma_spatializer* pSpatializer);
  4227. MA_API void ma_spatializer_set_max_distance(ma_spatializer* pSpatializer, float maxDistance);
  4228. MA_API float ma_spatializer_get_max_distance(const ma_spatializer* pSpatializer);
  4229. MA_API void ma_spatializer_set_cone(ma_spatializer* pSpatializer, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  4230. MA_API void ma_spatializer_get_cone(const ma_spatializer* pSpatializer, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  4231. MA_API void ma_spatializer_set_doppler_factor(ma_spatializer* pSpatializer, float dopplerFactor);
  4232. MA_API float ma_spatializer_get_doppler_factor(const ma_spatializer* pSpatializer);
  4233. MA_API void ma_spatializer_set_directional_attenuation_factor(ma_spatializer* pSpatializer, float directionalAttenuationFactor);
  4234. MA_API float ma_spatializer_get_directional_attenuation_factor(const ma_spatializer* pSpatializer);
  4235. MA_API void ma_spatializer_set_position(ma_spatializer* pSpatializer, float x, float y, float z);
  4236. MA_API ma_vec3f ma_spatializer_get_position(const ma_spatializer* pSpatializer);
  4237. MA_API void ma_spatializer_set_direction(ma_spatializer* pSpatializer, float x, float y, float z);
  4238. MA_API ma_vec3f ma_spatializer_get_direction(const ma_spatializer* pSpatializer);
  4239. MA_API void ma_spatializer_set_velocity(ma_spatializer* pSpatializer, float x, float y, float z);
  4240. MA_API ma_vec3f ma_spatializer_get_velocity(const ma_spatializer* pSpatializer);
  4241. MA_API void ma_spatializer_get_relative_position_and_direction(const ma_spatializer* pSpatializer, const ma_spatializer_listener* pListener, ma_vec3f* pRelativePos, ma_vec3f* pRelativeDir);
  4242. /************************************************************************************************************************************************************
  4243. *************************************************************************************************************************************************************
  4244. DATA CONVERSION
  4245. ===============
  4246. This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc.
  4247. *************************************************************************************************************************************************************
  4248. ************************************************************************************************************************************************************/
  4249. /**************************************************************************************************************************************************************
  4250. Resampling
  4251. **************************************************************************************************************************************************************/
  4252. typedef struct
  4253. {
  4254. ma_format format;
  4255. ma_uint32 channels;
  4256. ma_uint32 sampleRateIn;
  4257. ma_uint32 sampleRateOut;
  4258. ma_uint32 lpfOrder; /* The low-pass filter order. Setting this to 0 will disable low-pass filtering. */
  4259. double lpfNyquistFactor; /* 0..1. Defaults to 1. 1 = Half the sampling frequency (Nyquist Frequency), 0.5 = Quarter the sampling frequency (half Nyquest Frequency), etc. */
  4260. } ma_linear_resampler_config;
  4261. MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4262. typedef struct
  4263. {
  4264. ma_linear_resampler_config config;
  4265. ma_uint32 inAdvanceInt;
  4266. ma_uint32 inAdvanceFrac;
  4267. ma_uint32 inTimeInt;
  4268. ma_uint32 inTimeFrac;
  4269. union
  4270. {
  4271. float* f32;
  4272. ma_int16* s16;
  4273. } x0; /* The previous input frame. */
  4274. union
  4275. {
  4276. float* f32;
  4277. ma_int16* s16;
  4278. } x1; /* The next input frame. */
  4279. ma_lpf lpf;
  4280. /* Memory management. */
  4281. void* _pHeap;
  4282. ma_bool32 _ownsHeap;
  4283. } ma_linear_resampler;
  4284. MA_API ma_result ma_linear_resampler_get_heap_size(const ma_linear_resampler_config* pConfig, size_t* pHeapSizeInBytes);
  4285. MA_API ma_result ma_linear_resampler_init_preallocated(const ma_linear_resampler_config* pConfig, void* pHeap, ma_linear_resampler* pResampler);
  4286. MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_linear_resampler* pResampler);
  4287. MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks);
  4288. MA_API ma_result ma_linear_resampler_process_pcm_frames(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
  4289. MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4290. MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut);
  4291. MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler);
  4292. MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler);
  4293. MA_API ma_result ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
  4294. MA_API ma_result ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
  4295. MA_API ma_result ma_linear_resampler_reset(ma_linear_resampler* pResampler);
  4296. typedef struct ma_resampler_config ma_resampler_config;
  4297. typedef void ma_resampling_backend;
  4298. typedef struct
  4299. {
  4300. ma_result (* onGetHeapSize )(void* pUserData, const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes);
  4301. ma_result (* onInit )(void* pUserData, const ma_resampler_config* pConfig, void* pHeap, ma_resampling_backend** ppBackend);
  4302. void (* onUninit )(void* pUserData, ma_resampling_backend* pBackend, const ma_allocation_callbacks* pAllocationCallbacks);
  4303. ma_result (* onProcess )(void* pUserData, ma_resampling_backend* pBackend, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
  4304. ma_result (* onSetRate )(void* pUserData, ma_resampling_backend* pBackend, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); /* Optional. Rate changes will be disabled. */
  4305. ma_uint64 (* onGetInputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */
  4306. ma_uint64 (* onGetOutputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */
  4307. ma_result (* onGetRequiredInputFrameCount )(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount); /* Optional. Latency mitigation will be disabled. */
  4308. ma_result (* onGetExpectedOutputFrameCount)(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount); /* Optional. Latency mitigation will be disabled. */
  4309. ma_result (* onReset )(void* pUserData, ma_resampling_backend* pBackend);
  4310. } ma_resampling_backend_vtable;
  4311. typedef enum
  4312. {
  4313. ma_resample_algorithm_linear = 0, /* Fastest, lowest quality. Optional low-pass filtering. Default. */
  4314. ma_resample_algorithm_custom,
  4315. } ma_resample_algorithm;
  4316. struct ma_resampler_config
  4317. {
  4318. ma_format format; /* Must be either ma_format_f32 or ma_format_s16. */
  4319. ma_uint32 channels;
  4320. ma_uint32 sampleRateIn;
  4321. ma_uint32 sampleRateOut;
  4322. ma_resample_algorithm algorithm; /* When set to ma_resample_algorithm_custom, pBackendVTable will be used. */
  4323. ma_resampling_backend_vtable* pBackendVTable;
  4324. void* pBackendUserData;
  4325. struct
  4326. {
  4327. ma_uint32 lpfOrder;
  4328. } linear;
  4329. };
  4330. MA_API ma_resampler_config ma_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_resample_algorithm algorithm);
  4331. typedef struct
  4332. {
  4333. ma_resampling_backend* pBackend;
  4334. ma_resampling_backend_vtable* pBackendVTable;
  4335. void* pBackendUserData;
  4336. ma_format format;
  4337. ma_uint32 channels;
  4338. ma_uint32 sampleRateIn;
  4339. ma_uint32 sampleRateOut;
  4340. union
  4341. {
  4342. ma_linear_resampler linear;
  4343. } state; /* State for stock resamplers so we can avoid a malloc. For stock resamplers, pBackend will point here. */
  4344. /* Memory management. */
  4345. void* _pHeap;
  4346. ma_bool32 _ownsHeap;
  4347. } ma_resampler;
  4348. MA_API ma_result ma_resampler_get_heap_size(const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes);
  4349. MA_API ma_result ma_resampler_init_preallocated(const ma_resampler_config* pConfig, void* pHeap, ma_resampler* pResampler);
  4350. /*
  4351. Initializes a new resampler object from a config.
  4352. */
  4353. MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_resampler* pResampler);
  4354. /*
  4355. Uninitializes a resampler.
  4356. */
  4357. MA_API void ma_resampler_uninit(ma_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks);
  4358. /*
  4359. Converts the given input data.
  4360. Both the input and output frames must be in the format specified in the config when the resampler was initilized.
  4361. On input, [pFrameCountOut] contains the number of output frames to process. On output it contains the number of output frames that
  4362. were actually processed, which may be less than the requested amount which will happen if there's not enough input data. You can use
  4363. ma_resampler_get_expected_output_frame_count() to know how many output frames will be processed for a given number of input frames.
  4364. On input, [pFrameCountIn] contains the number of input frames contained in [pFramesIn]. On output it contains the number of whole
  4365. input frames that were actually processed. You can use ma_resampler_get_required_input_frame_count() to know how many input frames
  4366. you should provide for a given number of output frames. [pFramesIn] can be NULL, in which case zeroes will be used instead.
  4367. If [pFramesOut] is NULL, a seek is performed. In this case, if [pFrameCountOut] is not NULL it will seek by the specified number of
  4368. output frames. Otherwise, if [pFramesCountOut] is NULL and [pFrameCountIn] is not NULL, it will seek by the specified number of input
  4369. frames. When seeking, [pFramesIn] is allowed to NULL, in which case the internal timing state will be updated, but no input will be
  4370. processed. In this case, any internal filter state will be updated as if zeroes were passed in.
  4371. It is an error for [pFramesOut] to be non-NULL and [pFrameCountOut] to be NULL.
  4372. It is an error for both [pFrameCountOut] and [pFrameCountIn] to be NULL.
  4373. */
  4374. MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
  4375. /*
  4376. Sets the input and output sample rate.
  4377. */
  4378. MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4379. /*
  4380. Sets the input and output sample rate as a ratio.
  4381. The ration is in/out.
  4382. */
  4383. MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio);
  4384. /*
  4385. Retrieves the latency introduced by the resampler in input frames.
  4386. */
  4387. MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler);
  4388. /*
  4389. Retrieves the latency introduced by the resampler in output frames.
  4390. */
  4391. MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler);
  4392. /*
  4393. Calculates the number of whole input frames that would need to be read from the client in order to output the specified
  4394. number of output frames.
  4395. The returned value does not include cached input frames. It only returns the number of extra frames that would need to be
  4396. read from the input buffer in order to output the specified number of output frames.
  4397. */
  4398. MA_API ma_result ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
  4399. /*
  4400. Calculates the number of whole output frames that would be output after fully reading and consuming the specified number of
  4401. input frames.
  4402. */
  4403. MA_API ma_result ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
  4404. /*
  4405. Resets the resampler's timer and clears it's internal cache.
  4406. */
  4407. MA_API ma_result ma_resampler_reset(ma_resampler* pResampler);
  4408. /**************************************************************************************************************************************************************
  4409. Channel Conversion
  4410. **************************************************************************************************************************************************************/
  4411. typedef enum
  4412. {
  4413. ma_channel_conversion_path_unknown,
  4414. ma_channel_conversion_path_passthrough,
  4415. ma_channel_conversion_path_mono_out, /* Converting to mono. */
  4416. ma_channel_conversion_path_mono_in, /* Converting from mono. */
  4417. ma_channel_conversion_path_shuffle, /* Simple shuffle. Will use this when all channels are present in both input and output channel maps, but just in a different order. */
  4418. ma_channel_conversion_path_weights /* Blended based on weights. */
  4419. } ma_channel_conversion_path;
  4420. typedef enum
  4421. {
  4422. ma_mono_expansion_mode_duplicate = 0, /* The default. */
  4423. ma_mono_expansion_mode_average, /* Average the mono channel across all channels. */
  4424. ma_mono_expansion_mode_stereo_only, /* Duplicate to the left and right channels only and ignore the others. */
  4425. ma_mono_expansion_mode_default = ma_mono_expansion_mode_duplicate
  4426. } ma_mono_expansion_mode;
  4427. typedef struct
  4428. {
  4429. ma_format format;
  4430. ma_uint32 channelsIn;
  4431. ma_uint32 channelsOut;
  4432. const ma_channel* pChannelMapIn;
  4433. const ma_channel* pChannelMapOut;
  4434. ma_channel_mix_mode mixingMode;
  4435. ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */
  4436. float** ppWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */
  4437. } ma_channel_converter_config;
  4438. MA_API ma_channel_converter_config ma_channel_converter_config_init(ma_format format, ma_uint32 channelsIn, const ma_channel* pChannelMapIn, ma_uint32 channelsOut, const ma_channel* pChannelMapOut, ma_channel_mix_mode mixingMode);
  4439. typedef struct
  4440. {
  4441. ma_format format;
  4442. ma_uint32 channelsIn;
  4443. ma_uint32 channelsOut;
  4444. ma_channel_mix_mode mixingMode;
  4445. ma_channel_conversion_path conversionPath;
  4446. ma_channel* pChannelMapIn;
  4447. ma_channel* pChannelMapOut;
  4448. ma_uint8* pShuffleTable; /* Indexed by output channel index. */
  4449. union
  4450. {
  4451. float** f32;
  4452. ma_int32** s16;
  4453. } weights; /* [in][out] */
  4454. /* Memory management. */
  4455. void* _pHeap;
  4456. ma_bool32 _ownsHeap;
  4457. } ma_channel_converter;
  4458. MA_API ma_result ma_channel_converter_get_heap_size(const ma_channel_converter_config* pConfig, size_t* pHeapSizeInBytes);
  4459. MA_API ma_result ma_channel_converter_init_preallocated(const ma_channel_converter_config* pConfig, void* pHeap, ma_channel_converter* pConverter);
  4460. MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_channel_converter* pConverter);
  4461. MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks);
  4462. MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4463. MA_API ma_result ma_channel_converter_get_input_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4464. MA_API ma_result ma_channel_converter_get_output_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4465. /**************************************************************************************************************************************************************
  4466. Data Conversion
  4467. **************************************************************************************************************************************************************/
  4468. typedef struct
  4469. {
  4470. ma_format formatIn;
  4471. ma_format formatOut;
  4472. ma_uint32 channelsIn;
  4473. ma_uint32 channelsOut;
  4474. ma_uint32 sampleRateIn;
  4475. ma_uint32 sampleRateOut;
  4476. ma_channel* pChannelMapIn;
  4477. ma_channel* pChannelMapOut;
  4478. ma_dither_mode ditherMode;
  4479. ma_channel_mix_mode channelMixMode;
  4480. ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */
  4481. float** ppChannelWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */
  4482. ma_bool32 allowDynamicSampleRate;
  4483. ma_resampler_config resampling;
  4484. } ma_data_converter_config;
  4485. MA_API ma_data_converter_config ma_data_converter_config_init_default(void);
  4486. MA_API ma_data_converter_config ma_data_converter_config_init(ma_format formatIn, ma_format formatOut, ma_uint32 channelsIn, ma_uint32 channelsOut, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4487. typedef enum
  4488. {
  4489. ma_data_converter_execution_path_passthrough, /* No conversion. */
  4490. ma_data_converter_execution_path_format_only, /* Only format conversion. */
  4491. ma_data_converter_execution_path_channels_only, /* Only channel conversion. */
  4492. ma_data_converter_execution_path_resample_only, /* Only resampling. */
  4493. ma_data_converter_execution_path_resample_first, /* All conversions, but resample as the first step. */
  4494. ma_data_converter_execution_path_channels_first /* All conversions, but channels as the first step. */
  4495. } ma_data_converter_execution_path;
  4496. typedef struct
  4497. {
  4498. ma_format formatIn;
  4499. ma_format formatOut;
  4500. ma_uint32 channelsIn;
  4501. ma_uint32 channelsOut;
  4502. ma_uint32 sampleRateIn;
  4503. ma_uint32 sampleRateOut;
  4504. ma_dither_mode ditherMode;
  4505. ma_data_converter_execution_path executionPath; /* The execution path the data converter will follow when processing. */
  4506. ma_channel_converter channelConverter;
  4507. ma_resampler resampler;
  4508. ma_bool8 hasPreFormatConversion;
  4509. ma_bool8 hasPostFormatConversion;
  4510. ma_bool8 hasChannelConverter;
  4511. ma_bool8 hasResampler;
  4512. ma_bool8 isPassthrough;
  4513. /* Memory management. */
  4514. ma_bool8 _ownsHeap;
  4515. void* _pHeap;
  4516. } ma_data_converter;
  4517. MA_API ma_result ma_data_converter_get_heap_size(const ma_data_converter_config* pConfig, size_t* pHeapSizeInBytes);
  4518. MA_API ma_result ma_data_converter_init_preallocated(const ma_data_converter_config* pConfig, void* pHeap, ma_data_converter* pConverter);
  4519. MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_converter* pConverter);
  4520. MA_API void ma_data_converter_uninit(ma_data_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks);
  4521. MA_API ma_result ma_data_converter_process_pcm_frames(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
  4522. MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4523. MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut);
  4524. MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter);
  4525. MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter);
  4526. MA_API ma_result ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
  4527. MA_API ma_result ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
  4528. MA_API ma_result ma_data_converter_get_input_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4529. MA_API ma_result ma_data_converter_get_output_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4530. MA_API ma_result ma_data_converter_reset(ma_data_converter* pConverter);
  4531. /************************************************************************************************************************************************************
  4532. Format Conversion
  4533. ************************************************************************************************************************************************************/
  4534. MA_API void ma_pcm_u8_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4535. MA_API void ma_pcm_u8_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4536. MA_API void ma_pcm_u8_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4537. MA_API void ma_pcm_u8_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4538. MA_API void ma_pcm_s16_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4539. MA_API void ma_pcm_s16_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4540. MA_API void ma_pcm_s16_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4541. MA_API void ma_pcm_s16_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4542. MA_API void ma_pcm_s24_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4543. MA_API void ma_pcm_s24_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4544. MA_API void ma_pcm_s24_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4545. MA_API void ma_pcm_s24_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4546. MA_API void ma_pcm_s32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4547. MA_API void ma_pcm_s32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4548. MA_API void ma_pcm_s32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4549. MA_API void ma_pcm_s32_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4550. MA_API void ma_pcm_f32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4551. MA_API void ma_pcm_f32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4552. MA_API void ma_pcm_f32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4553. MA_API void ma_pcm_f32_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4554. MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode);
  4555. MA_API void ma_convert_pcm_frames_format(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 frameCount, ma_uint32 channels, ma_dither_mode ditherMode);
  4556. /*
  4557. Deinterleaves an interleaved buffer.
  4558. */
  4559. MA_API void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames);
  4560. /*
  4561. Interleaves a group of deinterleaved buffers.
  4562. */
  4563. MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames);
  4564. /************************************************************************************************************************************************************
  4565. Channel Maps
  4566. ************************************************************************************************************************************************************/
  4567. /*
  4568. This is used in the shuffle table to indicate that the channel index is undefined and should be ignored.
  4569. */
  4570. #define MA_CHANNEL_INDEX_NULL 255
  4571. /*
  4572. Retrieves the channel position of the specified channel in the given channel map.
  4573. The pChannelMap parameter can be null, in which case miniaudio's default channel map will be assumed.
  4574. */
  4575. MA_API ma_channel ma_channel_map_get_channel(const ma_channel* pChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex);
  4576. /*
  4577. Initializes a blank channel map.
  4578. When a blank channel map is specified anywhere it indicates that the native channel map should be used.
  4579. */
  4580. MA_API void ma_channel_map_init_blank(ma_channel* pChannelMap, ma_uint32 channels);
  4581. /*
  4582. Helper for retrieving a standard channel map.
  4583. The output channel map buffer must have a capacity of at least `channelMapCap`.
  4584. */
  4585. MA_API void ma_channel_map_init_standard(ma_standard_channel_map standardChannelMap, ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channels);
  4586. /*
  4587. Copies a channel map.
  4588. Both input and output channel map buffers must have a capacity of at at least `channels`.
  4589. */
  4590. MA_API void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels);
  4591. /*
  4592. Copies a channel map if one is specified, otherwise copies the default channel map.
  4593. The output buffer must have a capacity of at least `channels`. If not NULL, the input channel map must also have a capacity of at least `channels`.
  4594. */
  4595. MA_API void ma_channel_map_copy_or_default(ma_channel* pOut, size_t channelMapCapOut, const ma_channel* pIn, ma_uint32 channels);
  4596. /*
  4597. Determines whether or not a channel map is valid.
  4598. A blank channel map is valid (all channels set to MA_CHANNEL_NONE). The way a blank channel map is handled is context specific, but
  4599. is usually treated as a passthrough.
  4600. Invalid channel maps:
  4601. - A channel map with no channels
  4602. - A channel map with more than one channel and a mono channel
  4603. The channel map buffer must have a capacity of at least `channels`.
  4604. */
  4605. MA_API ma_bool32 ma_channel_map_is_valid(const ma_channel* pChannelMap, ma_uint32 channels);
  4606. /*
  4607. Helper for comparing two channel maps for equality.
  4608. This assumes the channel count is the same between the two.
  4609. Both channels map buffers must have a capacity of at least `channels`.
  4610. */
  4611. MA_API ma_bool32 ma_channel_map_is_equal(const ma_channel* pChannelMapA, const ma_channel* pChannelMapB, ma_uint32 channels);
  4612. /*
  4613. Helper for determining if a channel map is blank (all channels set to MA_CHANNEL_NONE).
  4614. The channel map buffer must have a capacity of at least `channels`.
  4615. */
  4616. MA_API ma_bool32 ma_channel_map_is_blank(const ma_channel* pChannelMap, ma_uint32 channels);
  4617. /*
  4618. Helper for determining whether or not a channel is present in the given channel map.
  4619. The channel map buffer must have a capacity of at least `channels`.
  4620. */
  4621. MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition);
  4622. /*
  4623. Find a channel position in the given channel map. Returns MA_TRUE if the channel is found; MA_FALSE otherwise. The
  4624. index of the channel is output to `pChannelIndex`.
  4625. The channel map buffer must have a capacity of at least `channels`.
  4626. */
  4627. MA_API ma_bool32 ma_channel_map_find_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition, ma_uint32* pChannelIndex);
  4628. /*
  4629. Generates a string representing the given channel map.
  4630. This is for printing and debugging purposes, not serialization/deserialization.
  4631. Returns the length of the string, not including the null terminator.
  4632. */
  4633. MA_API size_t ma_channel_map_to_string(const ma_channel* pChannelMap, ma_uint32 channels, char* pBufferOut, size_t bufferCap);
  4634. /*
  4635. Retrieves a human readable version of a channel position.
  4636. */
  4637. MA_API const char* ma_channel_position_to_string(ma_channel channel);
  4638. /************************************************************************************************************************************************************
  4639. Conversion Helpers
  4640. ************************************************************************************************************************************************************/
  4641. /*
  4642. High-level helper for doing a full format conversion in one go. Returns the number of output frames. Call this with pOut set to NULL to
  4643. determine the required size of the output buffer. frameCountOut should be set to the capacity of pOut. If pOut is NULL, frameCountOut is
  4644. ignored.
  4645. A return value of 0 indicates an error.
  4646. This function is useful for one-off bulk conversions, but if you're streaming data you should use the ma_data_converter APIs instead.
  4647. */
  4648. MA_API ma_uint64 ma_convert_frames(void* pOut, ma_uint64 frameCountOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, const void* pIn, ma_uint64 frameCountIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn);
  4649. MA_API ma_uint64 ma_convert_frames_ex(void* pOut, ma_uint64 frameCountOut, const void* pIn, ma_uint64 frameCountIn, const ma_data_converter_config* pConfig);
  4650. /************************************************************************************************************************************************************
  4651. Data Source
  4652. ************************************************************************************************************************************************************/
  4653. typedef void ma_data_source;
  4654. #define MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT 0x00000001
  4655. typedef struct
  4656. {
  4657. ma_result (* onRead)(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  4658. ma_result (* onSeek)(ma_data_source* pDataSource, ma_uint64 frameIndex);
  4659. ma_result (* onGetDataFormat)(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  4660. ma_result (* onGetCursor)(ma_data_source* pDataSource, ma_uint64* pCursor);
  4661. ma_result (* onGetLength)(ma_data_source* pDataSource, ma_uint64* pLength);
  4662. ma_result (* onSetLooping)(ma_data_source* pDataSource, ma_bool32 isLooping);
  4663. ma_uint32 flags;
  4664. } ma_data_source_vtable;
  4665. typedef ma_data_source* (* ma_data_source_get_next_proc)(ma_data_source* pDataSource);
  4666. typedef struct
  4667. {
  4668. const ma_data_source_vtable* vtable;
  4669. } ma_data_source_config;
  4670. MA_API ma_data_source_config ma_data_source_config_init(void);
  4671. typedef struct
  4672. {
  4673. const ma_data_source_vtable* vtable;
  4674. ma_uint64 rangeBegInFrames;
  4675. ma_uint64 rangeEndInFrames; /* Set to -1 for unranged (default). */
  4676. ma_uint64 loopBegInFrames; /* Relative to rangeBegInFrames. */
  4677. ma_uint64 loopEndInFrames; /* Relative to rangeBegInFrames. Set to -1 for the end of the range. */
  4678. ma_data_source* pCurrent; /* When non-NULL, the data source being initialized will act as a proxy and will route all operations to pCurrent. Used in conjunction with pNext/onGetNext for seamless chaining. */
  4679. ma_data_source* pNext; /* When set to NULL, onGetNext will be used. */
  4680. ma_data_source_get_next_proc onGetNext; /* Will be used when pNext is NULL. If both are NULL, no next will be used. */
  4681. MA_ATOMIC(4, ma_bool32) isLooping;
  4682. } ma_data_source_base;
  4683. MA_API ma_result ma_data_source_init(const ma_data_source_config* pConfig, ma_data_source* pDataSource);
  4684. MA_API void ma_data_source_uninit(ma_data_source* pDataSource);
  4685. MA_API ma_result ma_data_source_read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); /* Must support pFramesOut = NULL in which case a forward seek should be performed. */
  4686. MA_API ma_result ma_data_source_seek_pcm_frames(ma_data_source* pDataSource, ma_uint64 frameCount, ma_uint64* pFramesSeeked); /* Can only seek forward. Equivalent to ma_data_source_read_pcm_frames(pDataSource, NULL, frameCount, &framesRead); */
  4687. MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex);
  4688. MA_API ma_result ma_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  4689. MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor);
  4690. MA_API ma_result ma_data_source_get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength); /* Returns MA_NOT_IMPLEMENTED if the length is unknown or cannot be determined. Decoders can return this. */
  4691. MA_API ma_result ma_data_source_get_cursor_in_seconds(ma_data_source* pDataSource, float* pCursor);
  4692. MA_API ma_result ma_data_source_get_length_in_seconds(ma_data_source* pDataSource, float* pLength);
  4693. MA_API ma_result ma_data_source_set_looping(ma_data_source* pDataSource, ma_bool32 isLooping);
  4694. MA_API ma_bool32 ma_data_source_is_looping(const ma_data_source* pDataSource);
  4695. MA_API ma_result ma_data_source_set_range_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 rangeBegInFrames, ma_uint64 rangeEndInFrames);
  4696. MA_API void ma_data_source_get_range_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pRangeBegInFrames, ma_uint64* pRangeEndInFrames);
  4697. MA_API ma_result ma_data_source_set_loop_point_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 loopBegInFrames, ma_uint64 loopEndInFrames);
  4698. MA_API void ma_data_source_get_loop_point_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pLoopBegInFrames, ma_uint64* pLoopEndInFrames);
  4699. MA_API ma_result ma_data_source_set_current(ma_data_source* pDataSource, ma_data_source* pCurrentDataSource);
  4700. MA_API ma_data_source* ma_data_source_get_current(const ma_data_source* pDataSource);
  4701. MA_API ma_result ma_data_source_set_next(ma_data_source* pDataSource, ma_data_source* pNextDataSource);
  4702. MA_API ma_data_source* ma_data_source_get_next(const ma_data_source* pDataSource);
  4703. MA_API ma_result ma_data_source_set_next_callback(ma_data_source* pDataSource, ma_data_source_get_next_proc onGetNext);
  4704. MA_API ma_data_source_get_next_proc ma_data_source_get_next_callback(const ma_data_source* pDataSource);
  4705. typedef struct
  4706. {
  4707. ma_data_source_base ds;
  4708. ma_format format;
  4709. ma_uint32 channels;
  4710. ma_uint32 sampleRate;
  4711. ma_uint64 cursor;
  4712. ma_uint64 sizeInFrames;
  4713. const void* pData;
  4714. } ma_audio_buffer_ref;
  4715. MA_API ma_result ma_audio_buffer_ref_init(ma_format format, ma_uint32 channels, const void* pData, ma_uint64 sizeInFrames, ma_audio_buffer_ref* pAudioBufferRef);
  4716. MA_API void ma_audio_buffer_ref_uninit(ma_audio_buffer_ref* pAudioBufferRef);
  4717. MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames);
  4718. MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
  4719. MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex);
  4720. MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount);
  4721. MA_API ma_result ma_audio_buffer_ref_unmap(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameCount); /* Returns MA_AT_END if the end has been reached. This should be considered successful. */
  4722. MA_API ma_bool32 ma_audio_buffer_ref_at_end(const ma_audio_buffer_ref* pAudioBufferRef);
  4723. MA_API ma_result ma_audio_buffer_ref_get_cursor_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pCursor);
  4724. MA_API ma_result ma_audio_buffer_ref_get_length_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pLength);
  4725. MA_API ma_result ma_audio_buffer_ref_get_available_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames);
  4726. typedef struct
  4727. {
  4728. ma_format format;
  4729. ma_uint32 channels;
  4730. ma_uint32 sampleRate;
  4731. ma_uint64 sizeInFrames;
  4732. const void* pData; /* If set to NULL, will allocate a block of memory for you. */
  4733. ma_allocation_callbacks allocationCallbacks;
  4734. } ma_audio_buffer_config;
  4735. MA_API ma_audio_buffer_config ma_audio_buffer_config_init(ma_format format, ma_uint32 channels, ma_uint64 sizeInFrames, const void* pData, const ma_allocation_callbacks* pAllocationCallbacks);
  4736. typedef struct
  4737. {
  4738. ma_audio_buffer_ref ref;
  4739. ma_allocation_callbacks allocationCallbacks;
  4740. ma_bool32 ownsData; /* Used to control whether or not miniaudio owns the data buffer. If set to true, pData will be freed in ma_audio_buffer_uninit(). */
  4741. ma_uint8 _pExtraData[1]; /* For allocating a buffer with the memory located directly after the other memory of the structure. */
  4742. } ma_audio_buffer;
  4743. MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
  4744. MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
  4745. MA_API ma_result ma_audio_buffer_alloc_and_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer** ppAudioBuffer); /* Always copies the data. Doesn't make sense to use this otherwise. Use ma_audio_buffer_uninit_and_free() to uninit. */
  4746. MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer);
  4747. MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer);
  4748. MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
  4749. MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex);
  4750. MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount);
  4751. MA_API ma_result ma_audio_buffer_unmap(ma_audio_buffer* pAudioBuffer, ma_uint64 frameCount); /* Returns MA_AT_END if the end has been reached. This should be considered successful. */
  4752. MA_API ma_bool32 ma_audio_buffer_at_end(const ma_audio_buffer* pAudioBuffer);
  4753. MA_API ma_result ma_audio_buffer_get_cursor_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pCursor);
  4754. MA_API ma_result ma_audio_buffer_get_length_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pLength);
  4755. MA_API ma_result ma_audio_buffer_get_available_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames);
  4756. /*
  4757. Paged Audio Buffer
  4758. ==================
  4759. A paged audio buffer is made up of a linked list of pages. It's expandable, but not shrinkable. It
  4760. can be used for cases where audio data is streamed in asynchronously while allowing data to be read
  4761. at the same time.
  4762. This is lock-free, but not 100% thread safe. You can append a page and read from the buffer across
  4763. simultaneously across different threads, however only one thread at a time can append, and only one
  4764. thread at a time can read and seek.
  4765. */
  4766. typedef struct ma_paged_audio_buffer_page ma_paged_audio_buffer_page;
  4767. struct ma_paged_audio_buffer_page
  4768. {
  4769. MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pNext;
  4770. ma_uint64 sizeInFrames;
  4771. ma_uint8 pAudioData[1];
  4772. };
  4773. typedef struct
  4774. {
  4775. ma_format format;
  4776. ma_uint32 channels;
  4777. ma_paged_audio_buffer_page head; /* Dummy head for the lock-free algorithm. Always has a size of 0. */
  4778. MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pTail; /* Never null. Initially set to &head. */
  4779. } ma_paged_audio_buffer_data;
  4780. MA_API ma_result ma_paged_audio_buffer_data_init(ma_format format, ma_uint32 channels, ma_paged_audio_buffer_data* pData);
  4781. MA_API void ma_paged_audio_buffer_data_uninit(ma_paged_audio_buffer_data* pData, const ma_allocation_callbacks* pAllocationCallbacks);
  4782. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_head(ma_paged_audio_buffer_data* pData);
  4783. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_tail(ma_paged_audio_buffer_data* pData);
  4784. MA_API ma_result ma_paged_audio_buffer_data_get_length_in_pcm_frames(ma_paged_audio_buffer_data* pData, ma_uint64* pLength);
  4785. MA_API ma_result ma_paged_audio_buffer_data_allocate_page(ma_paged_audio_buffer_data* pData, ma_uint64 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks, ma_paged_audio_buffer_page** ppPage);
  4786. MA_API ma_result ma_paged_audio_buffer_data_free_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage, const ma_allocation_callbacks* pAllocationCallbacks);
  4787. MA_API ma_result ma_paged_audio_buffer_data_append_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage);
  4788. MA_API ma_result ma_paged_audio_buffer_data_allocate_and_append_page(ma_paged_audio_buffer_data* pData, ma_uint32 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks);
  4789. typedef struct
  4790. {
  4791. ma_paged_audio_buffer_data* pData; /* Must not be null. */
  4792. } ma_paged_audio_buffer_config;
  4793. MA_API ma_paged_audio_buffer_config ma_paged_audio_buffer_config_init(ma_paged_audio_buffer_data* pData);
  4794. typedef struct
  4795. {
  4796. ma_data_source_base ds;
  4797. ma_paged_audio_buffer_data* pData; /* Audio data is read from here. Cannot be null. */
  4798. ma_paged_audio_buffer_page* pCurrent;
  4799. ma_uint64 relativeCursor; /* Relative to the current page. */
  4800. ma_uint64 absoluteCursor;
  4801. } ma_paged_audio_buffer;
  4802. MA_API ma_result ma_paged_audio_buffer_init(const ma_paged_audio_buffer_config* pConfig, ma_paged_audio_buffer* pPagedAudioBuffer);
  4803. MA_API void ma_paged_audio_buffer_uninit(ma_paged_audio_buffer* pPagedAudioBuffer);
  4804. MA_API ma_result ma_paged_audio_buffer_read_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); /* Returns MA_AT_END if no more pages available. */
  4805. MA_API ma_result ma_paged_audio_buffer_seek_to_pcm_frame(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64 frameIndex);
  4806. MA_API ma_result ma_paged_audio_buffer_get_cursor_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pCursor);
  4807. MA_API ma_result ma_paged_audio_buffer_get_length_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pLength);
  4808. /************************************************************************************************************************************************************
  4809. Ring Buffer
  4810. ************************************************************************************************************************************************************/
  4811. typedef struct
  4812. {
  4813. void* pBuffer;
  4814. ma_uint32 subbufferSizeInBytes;
  4815. ma_uint32 subbufferCount;
  4816. ma_uint32 subbufferStrideInBytes;
  4817. MA_ATOMIC(4, ma_uint32) encodedReadOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. Must be used atomically. */
  4818. MA_ATOMIC(4, ma_uint32) encodedWriteOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. Must be used atomically. */
  4819. ma_bool8 ownsBuffer; /* Used to know whether or not miniaudio is responsible for free()-ing the buffer. */
  4820. ma_bool8 clearOnWriteAcquire; /* When set, clears the acquired write buffer before returning from ma_rb_acquire_write(). */
  4821. ma_allocation_callbacks allocationCallbacks;
  4822. } ma_rb;
  4823. MA_API ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size_t subbufferStrideInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB);
  4824. MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB);
  4825. MA_API void ma_rb_uninit(ma_rb* pRB);
  4826. MA_API void ma_rb_reset(ma_rb* pRB);
  4827. MA_API ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
  4828. MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes);
  4829. MA_API ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
  4830. MA_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes);
  4831. MA_API ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes);
  4832. MA_API ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes);
  4833. MA_API ma_int32 ma_rb_pointer_distance(ma_rb* pRB); /* Returns the distance between the write pointer and the read pointer. Should never be negative for a correct program. Will return the number of bytes that can be read before the read pointer hits the write pointer. */
  4834. MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB);
  4835. MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB);
  4836. MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB);
  4837. MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB);
  4838. MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex);
  4839. MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer);
  4840. typedef struct
  4841. {
  4842. ma_data_source_base ds;
  4843. ma_rb rb;
  4844. ma_format format;
  4845. ma_uint32 channels;
  4846. ma_uint32 sampleRate; /* Not required for the ring buffer itself, but useful for associating the data with some sample rate, particularly for data sources. */
  4847. } ma_pcm_rb;
  4848. MA_API ma_result ma_pcm_rb_init_ex(ma_format format, ma_uint32 channels, ma_uint32 subbufferSizeInFrames, ma_uint32 subbufferCount, ma_uint32 subbufferStrideInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB);
  4849. MA_API ma_result ma_pcm_rb_init(ma_format format, ma_uint32 channels, ma_uint32 bufferSizeInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB);
  4850. MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB);
  4851. MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB);
  4852. MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
  4853. MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames);
  4854. MA_API ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
  4855. MA_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames);
  4856. MA_API ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
  4857. MA_API ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
  4858. MA_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB); /* Return value is in frames. */
  4859. MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB);
  4860. MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB);
  4861. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB);
  4862. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB);
  4863. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex);
  4864. MA_API void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer);
  4865. MA_API ma_format ma_pcm_rb_get_format(const ma_pcm_rb* pRB);
  4866. MA_API ma_uint32 ma_pcm_rb_get_channels(const ma_pcm_rb* pRB);
  4867. MA_API ma_uint32 ma_pcm_rb_get_sample_rate(const ma_pcm_rb* pRB);
  4868. MA_API void ma_pcm_rb_set_sample_rate(ma_pcm_rb* pRB, ma_uint32 sampleRate);
  4869. /*
  4870. The idea of the duplex ring buffer is to act as the intermediary buffer when running two asynchronous devices in a duplex set up. The
  4871. capture device writes to it, and then a playback device reads from it.
  4872. At the moment this is just a simple naive implementation, but in the future I want to implement some dynamic resampling to seamlessly
  4873. handle desyncs. Note that the API is work in progress and may change at any time in any version.
  4874. The size of the buffer is based on the capture side since that's what'll be written to the buffer. It is based on the capture period size
  4875. in frames. The internal sample rate of the capture device is also needed in order to calculate the size.
  4876. */
  4877. typedef struct
  4878. {
  4879. ma_pcm_rb rb;
  4880. } ma_duplex_rb;
  4881. MA_API ma_result ma_duplex_rb_init(ma_format captureFormat, ma_uint32 captureChannels, ma_uint32 sampleRate, ma_uint32 captureInternalSampleRate, ma_uint32 captureInternalPeriodSizeInFrames, const ma_allocation_callbacks* pAllocationCallbacks, ma_duplex_rb* pRB);
  4882. MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB);
  4883. /************************************************************************************************************************************************************
  4884. Miscellaneous Helpers
  4885. ************************************************************************************************************************************************************/
  4886. /*
  4887. Retrieves a human readable description of the given result code.
  4888. */
  4889. MA_API const char* ma_result_description(ma_result result);
  4890. /*
  4891. malloc()
  4892. */
  4893. MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  4894. /*
  4895. calloc()
  4896. */
  4897. MA_API void* ma_calloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  4898. /*
  4899. realloc()
  4900. */
  4901. MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  4902. /*
  4903. free()
  4904. */
  4905. MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
  4906. /*
  4907. Performs an aligned malloc, with the assumption that the alignment is a power of 2.
  4908. */
  4909. MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks);
  4910. /*
  4911. Free's an aligned malloc'd buffer.
  4912. */
  4913. MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
  4914. /*
  4915. Retrieves a friendly name for a format.
  4916. */
  4917. MA_API const char* ma_get_format_name(ma_format format);
  4918. /*
  4919. Blends two frames in floating point format.
  4920. */
  4921. MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels);
  4922. /*
  4923. Retrieves the size of a sample in bytes for the given format.
  4924. This API is efficient and is implemented using a lookup table.
  4925. Thread Safety: SAFE
  4926. This API is pure.
  4927. */
  4928. MA_API ma_uint32 ma_get_bytes_per_sample(ma_format format);
  4929. static MA_INLINE ma_uint32 ma_get_bytes_per_frame(ma_format format, ma_uint32 channels) { return ma_get_bytes_per_sample(format) * channels; }
  4930. /*
  4931. Converts a log level to a string.
  4932. */
  4933. MA_API const char* ma_log_level_to_string(ma_uint32 logLevel);
  4934. /************************************************************************************************************************************************************
  4935. Synchronization
  4936. ************************************************************************************************************************************************************/
  4937. /*
  4938. Locks a spinlock.
  4939. */
  4940. MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock);
  4941. /*
  4942. Locks a spinlock, but does not yield() when looping.
  4943. */
  4944. MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock);
  4945. /*
  4946. Unlocks a spinlock.
  4947. */
  4948. MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock);
  4949. #ifndef MA_NO_THREADING
  4950. /*
  4951. Creates a mutex.
  4952. A mutex must be created from a valid context. A mutex is initially unlocked.
  4953. */
  4954. MA_API ma_result ma_mutex_init(ma_mutex* pMutex);
  4955. /*
  4956. Deletes a mutex.
  4957. */
  4958. MA_API void ma_mutex_uninit(ma_mutex* pMutex);
  4959. /*
  4960. Locks a mutex with an infinite timeout.
  4961. */
  4962. MA_API void ma_mutex_lock(ma_mutex* pMutex);
  4963. /*
  4964. Unlocks a mutex.
  4965. */
  4966. MA_API void ma_mutex_unlock(ma_mutex* pMutex);
  4967. /*
  4968. Initializes an auto-reset event.
  4969. */
  4970. MA_API ma_result ma_event_init(ma_event* pEvent);
  4971. /*
  4972. Uninitializes an auto-reset event.
  4973. */
  4974. MA_API void ma_event_uninit(ma_event* pEvent);
  4975. /*
  4976. Waits for the specified auto-reset event to become signalled.
  4977. */
  4978. MA_API ma_result ma_event_wait(ma_event* pEvent);
  4979. /*
  4980. Signals the specified auto-reset event.
  4981. */
  4982. MA_API ma_result ma_event_signal(ma_event* pEvent);
  4983. #endif /* MA_NO_THREADING */
  4984. /*
  4985. Fence
  4986. =====
  4987. This locks while the counter is larger than 0. Counter can be incremented and decremented by any
  4988. thread, but care needs to be taken when waiting. It is possible for one thread to acquire the
  4989. fence just as another thread returns from ma_fence_wait().
  4990. The idea behind a fence is to allow you to wait for a group of operations to complete. When an
  4991. operation starts, the counter is incremented which locks the fence. When the operation completes,
  4992. the fence will be released which decrements the counter. ma_fence_wait() will block until the
  4993. counter hits zero.
  4994. If threading is disabled, ma_fence_wait() will spin on the counter.
  4995. */
  4996. typedef struct
  4997. {
  4998. #ifndef MA_NO_THREADING
  4999. ma_event e;
  5000. #endif
  5001. ma_uint32 counter;
  5002. } ma_fence;
  5003. MA_API ma_result ma_fence_init(ma_fence* pFence);
  5004. MA_API void ma_fence_uninit(ma_fence* pFence);
  5005. MA_API ma_result ma_fence_acquire(ma_fence* pFence); /* Increment counter. */
  5006. MA_API ma_result ma_fence_release(ma_fence* pFence); /* Decrement counter. */
  5007. MA_API ma_result ma_fence_wait(ma_fence* pFence); /* Wait for counter to reach 0. */
  5008. /*
  5009. Notification callback for asynchronous operations.
  5010. */
  5011. typedef void ma_async_notification;
  5012. typedef struct
  5013. {
  5014. void (* onSignal)(ma_async_notification* pNotification);
  5015. } ma_async_notification_callbacks;
  5016. MA_API ma_result ma_async_notification_signal(ma_async_notification* pNotification);
  5017. /*
  5018. Simple polling notification.
  5019. This just sets a variable when the notification has been signalled which is then polled with ma_async_notification_poll_is_signalled()
  5020. */
  5021. typedef struct
  5022. {
  5023. ma_async_notification_callbacks cb;
  5024. ma_bool32 signalled;
  5025. } ma_async_notification_poll;
  5026. MA_API ma_result ma_async_notification_poll_init(ma_async_notification_poll* pNotificationPoll);
  5027. MA_API ma_bool32 ma_async_notification_poll_is_signalled(const ma_async_notification_poll* pNotificationPoll);
  5028. /*
  5029. Event Notification
  5030. This uses an ma_event. If threading is disabled (MA_NO_THREADING), initialization will fail.
  5031. */
  5032. typedef struct
  5033. {
  5034. ma_async_notification_callbacks cb;
  5035. #ifndef MA_NO_THREADING
  5036. ma_event e;
  5037. #endif
  5038. } ma_async_notification_event;
  5039. MA_API ma_result ma_async_notification_event_init(ma_async_notification_event* pNotificationEvent);
  5040. MA_API ma_result ma_async_notification_event_uninit(ma_async_notification_event* pNotificationEvent);
  5041. MA_API ma_result ma_async_notification_event_wait(ma_async_notification_event* pNotificationEvent);
  5042. MA_API ma_result ma_async_notification_event_signal(ma_async_notification_event* pNotificationEvent);
  5043. /************************************************************************************************************************************************************
  5044. Job Queue
  5045. ************************************************************************************************************************************************************/
  5046. /*
  5047. Slot Allocator
  5048. --------------
  5049. The idea of the slot allocator is for it to be used in conjunction with a fixed sized buffer. You use the slot allocator to allocator an index that can be used
  5050. as the insertion point for an object.
  5051. Slots are reference counted to help mitigate the ABA problem in the lock-free queue we use for tracking jobs.
  5052. The slot index is stored in the low 32 bits. The reference counter is stored in the high 32 bits:
  5053. +-----------------+-----------------+
  5054. | 32 Bits | 32 Bits |
  5055. +-----------------+-----------------+
  5056. | Reference Count | Slot Index |
  5057. +-----------------+-----------------+
  5058. */
  5059. typedef struct
  5060. {
  5061. ma_uint32 capacity; /* The number of slots to make available. */
  5062. } ma_slot_allocator_config;
  5063. MA_API ma_slot_allocator_config ma_slot_allocator_config_init(ma_uint32 capacity);
  5064. typedef struct
  5065. {
  5066. MA_ATOMIC(4, ma_uint32) bitfield; /* Must be used atomically because the allocation and freeing routines need to make copies of this which must never be optimized away by the compiler. */
  5067. } ma_slot_allocator_group;
  5068. typedef struct
  5069. {
  5070. ma_slot_allocator_group* pGroups; /* Slots are grouped in chunks of 32. */
  5071. ma_uint32* pSlots; /* 32 bits for reference counting for ABA mitigation. */
  5072. ma_uint32 count; /* Allocation count. */
  5073. ma_uint32 capacity;
  5074. /* Memory management. */
  5075. ma_bool32 _ownsHeap;
  5076. void* _pHeap;
  5077. } ma_slot_allocator;
  5078. MA_API ma_result ma_slot_allocator_get_heap_size(const ma_slot_allocator_config* pConfig, size_t* pHeapSizeInBytes);
  5079. MA_API ma_result ma_slot_allocator_init_preallocated(const ma_slot_allocator_config* pConfig, void* pHeap, ma_slot_allocator* pAllocator);
  5080. MA_API ma_result ma_slot_allocator_init(const ma_slot_allocator_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_slot_allocator* pAllocator);
  5081. MA_API void ma_slot_allocator_uninit(ma_slot_allocator* pAllocator, const ma_allocation_callbacks* pAllocationCallbacks);
  5082. MA_API ma_result ma_slot_allocator_alloc(ma_slot_allocator* pAllocator, ma_uint64* pSlot);
  5083. MA_API ma_result ma_slot_allocator_free(ma_slot_allocator* pAllocator, ma_uint64 slot);
  5084. typedef struct ma_job ma_job;
  5085. /*
  5086. Callback for processing a job. Each job type will have their own processing callback which will be
  5087. called by ma_job_process().
  5088. */
  5089. typedef ma_result (* ma_job_proc)(ma_job* pJob);
  5090. /* When a job type is added here an callback needs to be added go "g_jobVTable" in the implementation section. */
  5091. typedef enum
  5092. {
  5093. /* Miscellaneous. */
  5094. MA_JOB_TYPE_QUIT = 0,
  5095. MA_JOB_TYPE_CUSTOM,
  5096. /* Resource Manager. */
  5097. MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE,
  5098. MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE,
  5099. MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE,
  5100. MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER,
  5101. MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER,
  5102. MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM,
  5103. MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM,
  5104. MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM,
  5105. MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM,
  5106. /* Device. */
  5107. MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE,
  5108. /* Count. Must always be last. */
  5109. MA_JOB_TYPE_COUNT
  5110. } ma_job_type;
  5111. struct ma_job
  5112. {
  5113. union
  5114. {
  5115. struct
  5116. {
  5117. ma_uint16 code; /* Job type. */
  5118. ma_uint16 slot; /* Index into a ma_slot_allocator. */
  5119. ma_uint32 refcount;
  5120. } breakup;
  5121. ma_uint64 allocation;
  5122. } toc; /* 8 bytes. We encode the job code into the slot allocation data to save space. */
  5123. MA_ATOMIC(8, ma_uint64) next; /* refcount + slot for the next item. Does not include the job code. */
  5124. ma_uint32 order; /* Execution order. Used to create a data dependency and ensure a job is executed in order. Usage is contextual depending on the job type. */
  5125. union
  5126. {
  5127. /* Miscellaneous. */
  5128. struct
  5129. {
  5130. ma_job_proc proc;
  5131. ma_uintptr data0;
  5132. ma_uintptr data1;
  5133. } custom;
  5134. /* Resource Manager */
  5135. union
  5136. {
  5137. struct
  5138. {
  5139. /*ma_resource_manager**/ void* pResourceManager;
  5140. /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
  5141. char* pFilePath;
  5142. wchar_t* pFilePathW;
  5143. ma_uint32 flags; /* Resource manager data source flags that were used when initializing the data buffer. */
  5144. ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */
  5145. ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. Will be passed through to MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE when decoding. */
  5146. ma_fence* pInitFence; /* Released when initialization of the decoder is complete. */
  5147. ma_fence* pDoneFence; /* Released if initialization of the decoder fails. Passed through to PAGE_DATA_BUFFER_NODE untouched if init is successful. */
  5148. } loadDataBufferNode;
  5149. struct
  5150. {
  5151. /*ma_resource_manager**/ void* pResourceManager;
  5152. /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
  5153. ma_async_notification* pDoneNotification;
  5154. ma_fence* pDoneFence;
  5155. } freeDataBufferNode;
  5156. struct
  5157. {
  5158. /*ma_resource_manager**/ void* pResourceManager;
  5159. /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
  5160. /*ma_decoder**/ void* pDecoder;
  5161. ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */
  5162. ma_fence* pDoneFence; /* Passed through from LOAD_DATA_BUFFER_NODE and released when the data buffer completes decoding or an error occurs. */
  5163. } pageDataBufferNode;
  5164. struct
  5165. {
  5166. /*ma_resource_manager_data_buffer**/ void* pDataBuffer;
  5167. ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */
  5168. ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */
  5169. ma_fence* pInitFence; /* Released when the data buffer has been initialized and the format/channels/rate can be retrieved. */
  5170. ma_fence* pDoneFence; /* Released when the data buffer has been fully decoded. */
  5171. ma_uint64 rangeBegInPCMFrames;
  5172. ma_uint64 rangeEndInPCMFrames;
  5173. ma_uint64 loopPointBegInPCMFrames;
  5174. ma_uint64 loopPointEndInPCMFrames;
  5175. ma_uint32 isLooping;
  5176. } loadDataBuffer;
  5177. struct
  5178. {
  5179. /*ma_resource_manager_data_buffer**/ void* pDataBuffer;
  5180. ma_async_notification* pDoneNotification;
  5181. ma_fence* pDoneFence;
  5182. } freeDataBuffer;
  5183. struct
  5184. {
  5185. /*ma_resource_manager_data_stream**/ void* pDataStream;
  5186. char* pFilePath; /* Allocated when the job is posted, freed by the job thread after loading. */
  5187. wchar_t* pFilePathW; /* ^ As above ^. Only used if pFilePath is NULL. */
  5188. ma_uint64 initialSeekPoint;
  5189. ma_async_notification* pInitNotification; /* Signalled after the first two pages have been decoded and frames can be read from the stream. */
  5190. ma_fence* pInitFence;
  5191. } loadDataStream;
  5192. struct
  5193. {
  5194. /*ma_resource_manager_data_stream**/ void* pDataStream;
  5195. ma_async_notification* pDoneNotification;
  5196. ma_fence* pDoneFence;
  5197. } freeDataStream;
  5198. struct
  5199. {
  5200. /*ma_resource_manager_data_stream**/ void* pDataStream;
  5201. ma_uint32 pageIndex; /* The index of the page to decode into. */
  5202. } pageDataStream;
  5203. struct
  5204. {
  5205. /*ma_resource_manager_data_stream**/ void* pDataStream;
  5206. ma_uint64 frameIndex;
  5207. } seekDataStream;
  5208. } resourceManager;
  5209. /* Device. */
  5210. union
  5211. {
  5212. union
  5213. {
  5214. struct
  5215. {
  5216. /*ma_device**/ void* pDevice;
  5217. /*ma_device_type*/ ma_uint32 deviceType;
  5218. } reroute;
  5219. } aaudio;
  5220. } device;
  5221. } data;
  5222. };
  5223. MA_API ma_job ma_job_init(ma_uint16 code);
  5224. MA_API ma_result ma_job_process(ma_job* pJob);
  5225. /*
  5226. When set, ma_job_queue_next() will not wait and no semaphore will be signaled in
  5227. ma_job_queue_post(). ma_job_queue_next() will return MA_NO_DATA_AVAILABLE if nothing is available.
  5228. This flag should always be used for platforms that do not support multithreading.
  5229. */
  5230. typedef enum
  5231. {
  5232. MA_JOB_QUEUE_FLAG_NON_BLOCKING = 0x00000001
  5233. } ma_job_queue_flags;
  5234. typedef struct
  5235. {
  5236. ma_uint32 flags;
  5237. ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. */
  5238. } ma_job_queue_config;
  5239. MA_API ma_job_queue_config ma_job_queue_config_init(ma_uint32 flags, ma_uint32 capacity);
  5240. typedef struct
  5241. {
  5242. ma_uint32 flags; /* Flags passed in at initialization time. */
  5243. ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. Set by the config. */
  5244. MA_ATOMIC(8, ma_uint64) head; /* The first item in the list. Required for removing from the top of the list. */
  5245. MA_ATOMIC(8, ma_uint64) tail; /* The last item in the list. Required for appending to the end of the list. */
  5246. #ifndef MA_NO_THREADING
  5247. ma_semaphore sem; /* Only used when MA_JOB_QUEUE_FLAG_NON_BLOCKING is unset. */
  5248. #endif
  5249. ma_slot_allocator allocator;
  5250. ma_job* pJobs;
  5251. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  5252. ma_spinlock lock;
  5253. #endif
  5254. /* Memory management. */
  5255. void* _pHeap;
  5256. ma_bool32 _ownsHeap;
  5257. } ma_job_queue;
  5258. MA_API ma_result ma_job_queue_get_heap_size(const ma_job_queue_config* pConfig, size_t* pHeapSizeInBytes);
  5259. MA_API ma_result ma_job_queue_init_preallocated(const ma_job_queue_config* pConfig, void* pHeap, ma_job_queue* pQueue);
  5260. MA_API ma_result ma_job_queue_init(const ma_job_queue_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_job_queue* pQueue);
  5261. MA_API void ma_job_queue_uninit(ma_job_queue* pQueue, const ma_allocation_callbacks* pAllocationCallbacks);
  5262. MA_API ma_result ma_job_queue_post(ma_job_queue* pQueue, const ma_job* pJob);
  5263. MA_API ma_result ma_job_queue_next(ma_job_queue* pQueue, ma_job* pJob); /* Returns MA_CANCELLED if the next job is a quit job. */
  5264. /************************************************************************************************************************************************************
  5265. *************************************************************************************************************************************************************
  5266. DEVICE I/O
  5267. ==========
  5268. This section contains the APIs for device playback and capture. Here is where you'll find ma_device_init(), etc.
  5269. *************************************************************************************************************************************************************
  5270. ************************************************************************************************************************************************************/
  5271. #ifndef MA_NO_DEVICE_IO
  5272. /* Some backends are only supported on certain platforms. */
  5273. #if defined(MA_WIN32)
  5274. #define MA_SUPPORT_WASAPI
  5275. #if defined(MA_WIN32_DESKTOP) /* DirectSound and WinMM backends are only supported on desktops. */
  5276. #define MA_SUPPORT_DSOUND
  5277. #define MA_SUPPORT_WINMM
  5278. /* Don't enable JACK here if compiling with Cosmopolitan. It'll be enabled in the Linux section below. */
  5279. #if !defined(__COSMOPOLITAN__)
  5280. #define MA_SUPPORT_JACK /* JACK is technically supported on Windows, but I don't know how many people use it in practice... */
  5281. #endif
  5282. #endif
  5283. #endif
  5284. #if defined(MA_UNIX) && !defined(MA_ORBIS) && !defined(MA_PROSPERO)
  5285. #if defined(MA_LINUX)
  5286. #if !defined(MA_ANDROID) && !defined(__COSMOPOLITAN__) /* ALSA is not supported on Android. */
  5287. #define MA_SUPPORT_ALSA
  5288. #endif
  5289. #endif
  5290. #if !defined(MA_BSD) && !defined(MA_ANDROID) && !defined(MA_EMSCRIPTEN)
  5291. #define MA_SUPPORT_PULSEAUDIO
  5292. #define MA_SUPPORT_JACK
  5293. #endif
  5294. #if defined(__OpenBSD__) /* <-- Change this to "#if defined(MA_BSD)" to enable sndio on all BSD flavors. */
  5295. #define MA_SUPPORT_SNDIO /* sndio is only supported on OpenBSD for now. May be expanded later if there's demand. */
  5296. #endif
  5297. #if defined(__NetBSD__) || defined(__OpenBSD__)
  5298. #define MA_SUPPORT_AUDIO4 /* Only support audio(4) on platforms with known support. */
  5299. #endif
  5300. #if defined(__FreeBSD__) || defined(__DragonFly__)
  5301. #define MA_SUPPORT_OSS /* Only support OSS on specific platforms with known support. */
  5302. #endif
  5303. #endif
  5304. #if defined(MA_ANDROID)
  5305. #define MA_SUPPORT_AAUDIO
  5306. #define MA_SUPPORT_OPENSL
  5307. #endif
  5308. #if defined(MA_APPLE)
  5309. #define MA_SUPPORT_COREAUDIO
  5310. #endif
  5311. #if defined(MA_EMSCRIPTEN)
  5312. #define MA_SUPPORT_WEBAUDIO
  5313. #endif
  5314. /* All platforms should support custom backends. */
  5315. #define MA_SUPPORT_CUSTOM
  5316. /* Explicitly disable the Null backend for Emscripten because it uses a background thread which is not properly supported right now. */
  5317. #if !defined(MA_EMSCRIPTEN)
  5318. #define MA_SUPPORT_NULL
  5319. #endif
  5320. #if defined(MA_SUPPORT_WASAPI) && !defined(MA_NO_WASAPI) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WASAPI))
  5321. #define MA_HAS_WASAPI
  5322. #endif
  5323. #if defined(MA_SUPPORT_DSOUND) && !defined(MA_NO_DSOUND) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_DSOUND))
  5324. #define MA_HAS_DSOUND
  5325. #endif
  5326. #if defined(MA_SUPPORT_WINMM) && !defined(MA_NO_WINMM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WINMM))
  5327. #define MA_HAS_WINMM
  5328. #endif
  5329. #if defined(MA_SUPPORT_ALSA) && !defined(MA_NO_ALSA) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_ALSA))
  5330. #define MA_HAS_ALSA
  5331. #endif
  5332. #if defined(MA_SUPPORT_PULSEAUDIO) && !defined(MA_NO_PULSEAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_PULSEAUDIO))
  5333. #define MA_HAS_PULSEAUDIO
  5334. #endif
  5335. #if defined(MA_SUPPORT_JACK) && !defined(MA_NO_JACK) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_JACK))
  5336. #define MA_HAS_JACK
  5337. #endif
  5338. #if defined(MA_SUPPORT_COREAUDIO) && !defined(MA_NO_COREAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_COREAUDIO))
  5339. #define MA_HAS_COREAUDIO
  5340. #endif
  5341. #if defined(MA_SUPPORT_SNDIO) && !defined(MA_NO_SNDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_SNDIO))
  5342. #define MA_HAS_SNDIO
  5343. #endif
  5344. #if defined(MA_SUPPORT_AUDIO4) && !defined(MA_NO_AUDIO4) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AUDIO4))
  5345. #define MA_HAS_AUDIO4
  5346. #endif
  5347. #if defined(MA_SUPPORT_OSS) && !defined(MA_NO_OSS) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OSS))
  5348. #define MA_HAS_OSS
  5349. #endif
  5350. #if defined(MA_SUPPORT_AAUDIO) && !defined(MA_NO_AAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AAUDIO))
  5351. #define MA_HAS_AAUDIO
  5352. #endif
  5353. #if defined(MA_SUPPORT_OPENSL) && !defined(MA_NO_OPENSL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OPENSL))
  5354. #define MA_HAS_OPENSL
  5355. #endif
  5356. #if defined(MA_SUPPORT_WEBAUDIO) && !defined(MA_NO_WEBAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WEBAUDIO))
  5357. #define MA_HAS_WEBAUDIO
  5358. #endif
  5359. #if defined(MA_SUPPORT_CUSTOM) && !defined(MA_NO_CUSTOM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_CUSTOM))
  5360. #define MA_HAS_CUSTOM
  5361. #endif
  5362. #if defined(MA_SUPPORT_NULL) && !defined(MA_NO_NULL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_NULL))
  5363. #define MA_HAS_NULL
  5364. #endif
  5365. typedef enum
  5366. {
  5367. ma_device_state_uninitialized = 0,
  5368. ma_device_state_stopped = 1, /* The device's default state after initialization. */
  5369. ma_device_state_started = 2, /* The device is started and is requesting and/or delivering audio data. */
  5370. ma_device_state_starting = 3, /* Transitioning from a stopped state to started. */
  5371. ma_device_state_stopping = 4 /* Transitioning from a started state to stopped. */
  5372. } ma_device_state;
  5373. MA_ATOMIC_SAFE_TYPE_DECL(i32, 4, device_state)
  5374. #ifdef MA_SUPPORT_WASAPI
  5375. /* We need a IMMNotificationClient object for WASAPI. */
  5376. typedef struct
  5377. {
  5378. void* lpVtbl;
  5379. ma_uint32 counter;
  5380. ma_device* pDevice;
  5381. } ma_IMMNotificationClient;
  5382. #endif
  5383. /* Backend enums must be in priority order. */
  5384. typedef enum
  5385. {
  5386. ma_backend_wasapi,
  5387. ma_backend_dsound,
  5388. ma_backend_winmm,
  5389. ma_backend_coreaudio,
  5390. ma_backend_sndio,
  5391. ma_backend_audio4,
  5392. ma_backend_oss,
  5393. ma_backend_pulseaudio,
  5394. ma_backend_alsa,
  5395. ma_backend_jack,
  5396. ma_backend_aaudio,
  5397. ma_backend_opensl,
  5398. ma_backend_webaudio,
  5399. ma_backend_custom, /* <-- Custom backend, with callbacks defined by the context config. */
  5400. ma_backend_null /* <-- Must always be the last item. Lowest priority, and used as the terminator for backend enumeration. */
  5401. } ma_backend;
  5402. #define MA_BACKEND_COUNT (ma_backend_null+1)
  5403. /*
  5404. Device job thread. This is used by backends that require asynchronous processing of certain
  5405. operations. It is not used by all backends.
  5406. The device job thread is made up of a thread and a job queue. You can post a job to the thread with
  5407. ma_device_job_thread_post(). The thread will do the processing of the job.
  5408. */
  5409. typedef struct
  5410. {
  5411. ma_bool32 noThread; /* Set this to true if you want to process jobs yourself. */
  5412. ma_uint32 jobQueueCapacity;
  5413. ma_uint32 jobQueueFlags;
  5414. } ma_device_job_thread_config;
  5415. MA_API ma_device_job_thread_config ma_device_job_thread_config_init(void);
  5416. typedef struct
  5417. {
  5418. ma_thread thread;
  5419. ma_job_queue jobQueue;
  5420. ma_bool32 _hasThread;
  5421. } ma_device_job_thread;
  5422. MA_API ma_result ma_device_job_thread_init(const ma_device_job_thread_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_device_job_thread* pJobThread);
  5423. MA_API void ma_device_job_thread_uninit(ma_device_job_thread* pJobThread, const ma_allocation_callbacks* pAllocationCallbacks);
  5424. MA_API ma_result ma_device_job_thread_post(ma_device_job_thread* pJobThread, const ma_job* pJob);
  5425. MA_API ma_result ma_device_job_thread_next(ma_device_job_thread* pJobThread, ma_job* pJob);
  5426. /* Device notification types. */
  5427. typedef enum
  5428. {
  5429. ma_device_notification_type_started,
  5430. ma_device_notification_type_stopped,
  5431. ma_device_notification_type_rerouted,
  5432. ma_device_notification_type_interruption_began,
  5433. ma_device_notification_type_interruption_ended
  5434. } ma_device_notification_type;
  5435. typedef struct
  5436. {
  5437. ma_device* pDevice;
  5438. ma_device_notification_type type;
  5439. union
  5440. {
  5441. struct
  5442. {
  5443. int _unused;
  5444. } started;
  5445. struct
  5446. {
  5447. int _unused;
  5448. } stopped;
  5449. struct
  5450. {
  5451. int _unused;
  5452. } rerouted;
  5453. struct
  5454. {
  5455. int _unused;
  5456. } interruption;
  5457. } data;
  5458. } ma_device_notification;
  5459. /*
  5460. The notification callback for when the application should be notified of a change to the device.
  5461. This callback is used for notifying the application of changes such as when the device has started,
  5462. stopped, rerouted or an interruption has occurred. Note that not all backends will post all
  5463. notification types. For example, some backends will perform automatic stream routing without any
  5464. kind of notification to the host program which means miniaudio will never know about it and will
  5465. never be able to fire the rerouted notification. You should keep this in mind when designing your
  5466. program.
  5467. The stopped notification will *not* get fired when a device is rerouted.
  5468. Parameters
  5469. ----------
  5470. pNotification (in)
  5471. A pointer to a structure containing information about the event. Use the `pDevice` member of
  5472. this object to retrieve the relevant device. The `type` member can be used to discriminate
  5473. against each of the notification types.
  5474. Remarks
  5475. -------
  5476. Do not restart or uninitialize the device from the callback.
  5477. Not all notifications will be triggered by all backends, however the started and stopped events
  5478. should be reliable for all backends. Some backends do not have a good way to detect device
  5479. stoppages due to unplugging the device which may result in the stopped callback not getting
  5480. fired. This has been observed with at least one BSD variant.
  5481. The rerouted notification is fired *after* the reroute has occurred. The stopped notification will
  5482. *not* get fired when a device is rerouted. The following backends are known to do automatic stream
  5483. rerouting, but do not have a way to be notified of the change:
  5484. * DirectSound
  5485. The interruption notifications are used on mobile platforms for detecting when audio is interrupted
  5486. due to things like an incoming phone call. Currently this is only implemented on iOS. None of the
  5487. Android backends will report this notification.
  5488. */
  5489. typedef void (* ma_device_notification_proc)(const ma_device_notification* pNotification);
  5490. /*
  5491. The callback for processing audio data from the device.
  5492. The data callback is fired by miniaudio whenever the device needs to have more data delivered to a playback device, or when a capture device has some data
  5493. available. This is called as soon as the backend asks for more data which means it may be called with inconsistent frame counts. You cannot assume the
  5494. callback will be fired with a consistent frame count.
  5495. Parameters
  5496. ----------
  5497. pDevice (in)
  5498. A pointer to the relevant device.
  5499. pOutput (out)
  5500. A pointer to the output buffer that will receive audio data that will later be played back through the speakers. This will be non-null for a playback or
  5501. full-duplex device and null for a capture and loopback device.
  5502. pInput (in)
  5503. A pointer to the buffer containing input data from a recording device. This will be non-null for a capture, full-duplex or loopback device and null for a
  5504. playback device.
  5505. frameCount (in)
  5506. The number of PCM frames to process. Note that this will not necessarily be equal to what you requested when you initialized the device. The
  5507. `periodSizeInFrames` and `periodSizeInMilliseconds` members of the device config are just hints, and are not necessarily exactly what you'll get. You must
  5508. not assume this will always be the same value each time the callback is fired.
  5509. Remarks
  5510. -------
  5511. You cannot stop and start the device from inside the callback or else you'll get a deadlock. You must also not uninitialize the device from inside the
  5512. callback. The following APIs cannot be called from inside the callback:
  5513. ma_device_init()
  5514. ma_device_init_ex()
  5515. ma_device_uninit()
  5516. ma_device_start()
  5517. ma_device_stop()
  5518. The proper way to stop the device is to call `ma_device_stop()` from a different thread, normally the main application thread.
  5519. */
  5520. typedef void (* ma_device_data_proc)(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
  5521. /*
  5522. DEPRECATED. Use ma_device_notification_proc instead.
  5523. The callback for when the device has been stopped.
  5524. This will be called when the device is stopped explicitly with `ma_device_stop()` and also called implicitly when the device is stopped through external forces
  5525. such as being unplugged or an internal error occurring.
  5526. Parameters
  5527. ----------
  5528. pDevice (in)
  5529. A pointer to the device that has just stopped.
  5530. Remarks
  5531. -------
  5532. Do not restart or uninitialize the device from the callback.
  5533. */
  5534. typedef void (* ma_stop_proc)(ma_device* pDevice); /* DEPRECATED. Use ma_device_notification_proc instead. */
  5535. typedef enum
  5536. {
  5537. ma_device_type_playback = 1,
  5538. ma_device_type_capture = 2,
  5539. ma_device_type_duplex = ma_device_type_playback | ma_device_type_capture, /* 3 */
  5540. ma_device_type_loopback = 4
  5541. } ma_device_type;
  5542. typedef enum
  5543. {
  5544. ma_share_mode_shared = 0,
  5545. ma_share_mode_exclusive
  5546. } ma_share_mode;
  5547. /* iOS/tvOS/watchOS session categories. */
  5548. typedef enum
  5549. {
  5550. ma_ios_session_category_default = 0, /* AVAudioSessionCategoryPlayAndRecord. */
  5551. ma_ios_session_category_none, /* Leave the session category unchanged. */
  5552. ma_ios_session_category_ambient, /* AVAudioSessionCategoryAmbient */
  5553. ma_ios_session_category_solo_ambient, /* AVAudioSessionCategorySoloAmbient */
  5554. ma_ios_session_category_playback, /* AVAudioSessionCategoryPlayback */
  5555. ma_ios_session_category_record, /* AVAudioSessionCategoryRecord */
  5556. ma_ios_session_category_play_and_record, /* AVAudioSessionCategoryPlayAndRecord */
  5557. ma_ios_session_category_multi_route /* AVAudioSessionCategoryMultiRoute */
  5558. } ma_ios_session_category;
  5559. /* iOS/tvOS/watchOS session category options */
  5560. typedef enum
  5561. {
  5562. ma_ios_session_category_option_mix_with_others = 0x01, /* AVAudioSessionCategoryOptionMixWithOthers */
  5563. ma_ios_session_category_option_duck_others = 0x02, /* AVAudioSessionCategoryOptionDuckOthers */
  5564. ma_ios_session_category_option_allow_bluetooth = 0x04, /* AVAudioSessionCategoryOptionAllowBluetooth */
  5565. ma_ios_session_category_option_default_to_speaker = 0x08, /* AVAudioSessionCategoryOptionDefaultToSpeaker */
  5566. ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others = 0x11, /* AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers */
  5567. ma_ios_session_category_option_allow_bluetooth_a2dp = 0x20, /* AVAudioSessionCategoryOptionAllowBluetoothA2DP */
  5568. ma_ios_session_category_option_allow_air_play = 0x40, /* AVAudioSessionCategoryOptionAllowAirPlay */
  5569. } ma_ios_session_category_option;
  5570. /* OpenSL stream types. */
  5571. typedef enum
  5572. {
  5573. ma_opensl_stream_type_default = 0, /* Leaves the stream type unset. */
  5574. ma_opensl_stream_type_voice, /* SL_ANDROID_STREAM_VOICE */
  5575. ma_opensl_stream_type_system, /* SL_ANDROID_STREAM_SYSTEM */
  5576. ma_opensl_stream_type_ring, /* SL_ANDROID_STREAM_RING */
  5577. ma_opensl_stream_type_media, /* SL_ANDROID_STREAM_MEDIA */
  5578. ma_opensl_stream_type_alarm, /* SL_ANDROID_STREAM_ALARM */
  5579. ma_opensl_stream_type_notification /* SL_ANDROID_STREAM_NOTIFICATION */
  5580. } ma_opensl_stream_type;
  5581. /* OpenSL recording presets. */
  5582. typedef enum
  5583. {
  5584. ma_opensl_recording_preset_default = 0, /* Leaves the input preset unset. */
  5585. ma_opensl_recording_preset_generic, /* SL_ANDROID_RECORDING_PRESET_GENERIC */
  5586. ma_opensl_recording_preset_camcorder, /* SL_ANDROID_RECORDING_PRESET_CAMCORDER */
  5587. ma_opensl_recording_preset_voice_recognition, /* SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION */
  5588. ma_opensl_recording_preset_voice_communication, /* SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION */
  5589. ma_opensl_recording_preset_voice_unprocessed /* SL_ANDROID_RECORDING_PRESET_UNPROCESSED */
  5590. } ma_opensl_recording_preset;
  5591. /* WASAPI audio thread priority characteristics. */
  5592. typedef enum
  5593. {
  5594. ma_wasapi_usage_default = 0,
  5595. ma_wasapi_usage_games,
  5596. ma_wasapi_usage_pro_audio,
  5597. } ma_wasapi_usage;
  5598. /* AAudio usage types. */
  5599. typedef enum
  5600. {
  5601. ma_aaudio_usage_default = 0, /* Leaves the usage type unset. */
  5602. ma_aaudio_usage_media, /* AAUDIO_USAGE_MEDIA */
  5603. ma_aaudio_usage_voice_communication, /* AAUDIO_USAGE_VOICE_COMMUNICATION */
  5604. ma_aaudio_usage_voice_communication_signalling, /* AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING */
  5605. ma_aaudio_usage_alarm, /* AAUDIO_USAGE_ALARM */
  5606. ma_aaudio_usage_notification, /* AAUDIO_USAGE_NOTIFICATION */
  5607. ma_aaudio_usage_notification_ringtone, /* AAUDIO_USAGE_NOTIFICATION_RINGTONE */
  5608. ma_aaudio_usage_notification_event, /* AAUDIO_USAGE_NOTIFICATION_EVENT */
  5609. ma_aaudio_usage_assistance_accessibility, /* AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY */
  5610. ma_aaudio_usage_assistance_navigation_guidance, /* AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE */
  5611. ma_aaudio_usage_assistance_sonification, /* AAUDIO_USAGE_ASSISTANCE_SONIFICATION */
  5612. ma_aaudio_usage_game, /* AAUDIO_USAGE_GAME */
  5613. ma_aaudio_usage_assitant, /* AAUDIO_USAGE_ASSISTANT */
  5614. ma_aaudio_usage_emergency, /* AAUDIO_SYSTEM_USAGE_EMERGENCY */
  5615. ma_aaudio_usage_safety, /* AAUDIO_SYSTEM_USAGE_SAFETY */
  5616. ma_aaudio_usage_vehicle_status, /* AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS */
  5617. ma_aaudio_usage_announcement /* AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT */
  5618. } ma_aaudio_usage;
  5619. /* AAudio content types. */
  5620. typedef enum
  5621. {
  5622. ma_aaudio_content_type_default = 0, /* Leaves the content type unset. */
  5623. ma_aaudio_content_type_speech, /* AAUDIO_CONTENT_TYPE_SPEECH */
  5624. ma_aaudio_content_type_music, /* AAUDIO_CONTENT_TYPE_MUSIC */
  5625. ma_aaudio_content_type_movie, /* AAUDIO_CONTENT_TYPE_MOVIE */
  5626. ma_aaudio_content_type_sonification /* AAUDIO_CONTENT_TYPE_SONIFICATION */
  5627. } ma_aaudio_content_type;
  5628. /* AAudio input presets. */
  5629. typedef enum
  5630. {
  5631. ma_aaudio_input_preset_default = 0, /* Leaves the input preset unset. */
  5632. ma_aaudio_input_preset_generic, /* AAUDIO_INPUT_PRESET_GENERIC */
  5633. ma_aaudio_input_preset_camcorder, /* AAUDIO_INPUT_PRESET_CAMCORDER */
  5634. ma_aaudio_input_preset_voice_recognition, /* AAUDIO_INPUT_PRESET_VOICE_RECOGNITION */
  5635. ma_aaudio_input_preset_voice_communication, /* AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION */
  5636. ma_aaudio_input_preset_unprocessed, /* AAUDIO_INPUT_PRESET_UNPROCESSED */
  5637. ma_aaudio_input_preset_voice_performance /* AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE */
  5638. } ma_aaudio_input_preset;
  5639. typedef enum
  5640. {
  5641. ma_aaudio_allow_capture_default = 0, /* Leaves the allowed capture policy unset. */
  5642. ma_aaudio_allow_capture_by_all, /* AAUDIO_ALLOW_CAPTURE_BY_ALL */
  5643. ma_aaudio_allow_capture_by_system, /* AAUDIO_ALLOW_CAPTURE_BY_SYSTEM */
  5644. ma_aaudio_allow_capture_by_none /* AAUDIO_ALLOW_CAPTURE_BY_NONE */
  5645. } ma_aaudio_allowed_capture_policy;
  5646. typedef union
  5647. {
  5648. ma_int64 counter;
  5649. double counterD;
  5650. } ma_timer;
  5651. typedef union
  5652. {
  5653. ma_wchar_win32 wasapi[64]; /* WASAPI uses a wchar_t string for identification. */
  5654. ma_uint8 dsound[16]; /* DirectSound uses a GUID for identification. */
  5655. /*UINT_PTR*/ ma_uint32 winmm; /* When creating a device, WinMM expects a Win32 UINT_PTR for device identification. In practice it's actually just a UINT. */
  5656. char alsa[256]; /* ALSA uses a name string for identification. */
  5657. char pulse[256]; /* PulseAudio uses a name string for identification. */
  5658. int jack; /* JACK always uses default devices. */
  5659. char coreaudio[256]; /* Core Audio uses a string for identification. */
  5660. char sndio[256]; /* "snd/0", etc. */
  5661. char audio4[256]; /* "/dev/audio", etc. */
  5662. char oss[64]; /* "dev/dsp0", etc. "dev/dsp" for the default device. */
  5663. ma_int32 aaudio; /* AAudio uses a 32-bit integer for identification. */
  5664. ma_uint32 opensl; /* OpenSL|ES uses a 32-bit unsigned integer for identification. */
  5665. char webaudio[32]; /* Web Audio always uses default devices for now, but if this changes it'll be a GUID. */
  5666. union
  5667. {
  5668. int i;
  5669. char s[256];
  5670. void* p;
  5671. } custom; /* The custom backend could be anything. Give them a few options. */
  5672. int nullbackend; /* The null backend uses an integer for device IDs. */
  5673. } ma_device_id;
  5674. typedef struct ma_context_config ma_context_config;
  5675. typedef struct ma_device_config ma_device_config;
  5676. typedef struct ma_backend_callbacks ma_backend_callbacks;
  5677. #define MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE (1U << 1) /* If set, this is supported in exclusive mode. Otherwise not natively supported by exclusive mode. */
  5678. #ifndef MA_MAX_DEVICE_NAME_LENGTH
  5679. #define MA_MAX_DEVICE_NAME_LENGTH 255
  5680. #endif
  5681. typedef struct
  5682. {
  5683. /* Basic info. This is the only information guaranteed to be filled in during device enumeration. */
  5684. ma_device_id id;
  5685. char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* +1 for null terminator. */
  5686. ma_bool32 isDefault;
  5687. ma_uint32 nativeDataFormatCount;
  5688. struct
  5689. {
  5690. ma_format format; /* Sample format. If set to ma_format_unknown, all sample formats are supported. */
  5691. ma_uint32 channels; /* If set to 0, all channels are supported. */
  5692. ma_uint32 sampleRate; /* If set to 0, all sample rates are supported. */
  5693. ma_uint32 flags; /* A combination of MA_DATA_FORMAT_FLAG_* flags. */
  5694. } nativeDataFormats[/*ma_format_count * ma_standard_sample_rate_count * MA_MAX_CHANNELS*/ 64]; /* Not sure how big to make this. There can be *many* permutations for virtual devices which can support anything. */
  5695. } ma_device_info;
  5696. struct ma_device_config
  5697. {
  5698. ma_device_type deviceType;
  5699. ma_uint32 sampleRate;
  5700. ma_uint32 periodSizeInFrames;
  5701. ma_uint32 periodSizeInMilliseconds;
  5702. ma_uint32 periods;
  5703. ma_performance_profile performanceProfile;
  5704. ma_bool8 noPreSilencedOutputBuffer; /* When set to true, the contents of the output buffer passed into the data callback will be left undefined rather than initialized to silence. */
  5705. ma_bool8 noClip; /* When set to true, the contents of the output buffer passed into the data callback will be clipped after returning. Only applies when the playback sample format is f32. */
  5706. ma_bool8 noDisableDenormals; /* Do not disable denormals when firing the data callback. */
  5707. ma_bool8 noFixedSizedCallback; /* Disables strict fixed-sized data callbacks. Setting this to true will result in the period size being treated only as a hint to the backend. This is an optimization for those who don't need fixed sized callbacks. */
  5708. ma_device_data_proc dataCallback;
  5709. ma_device_notification_proc notificationCallback;
  5710. ma_stop_proc stopCallback;
  5711. void* pUserData;
  5712. ma_resampler_config resampling;
  5713. struct
  5714. {
  5715. const ma_device_id* pDeviceID;
  5716. ma_format format;
  5717. ma_uint32 channels;
  5718. ma_channel* pChannelMap;
  5719. ma_channel_mix_mode channelMixMode;
  5720. ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */
  5721. ma_share_mode shareMode;
  5722. } playback;
  5723. struct
  5724. {
  5725. const ma_device_id* pDeviceID;
  5726. ma_format format;
  5727. ma_uint32 channels;
  5728. ma_channel* pChannelMap;
  5729. ma_channel_mix_mode channelMixMode;
  5730. ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */
  5731. ma_share_mode shareMode;
  5732. } capture;
  5733. struct
  5734. {
  5735. ma_wasapi_usage usage; /* When configured, uses Avrt APIs to set the thread characteristics. */
  5736. ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
  5737. ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
  5738. ma_bool8 noAutoStreamRouting; /* Disables automatic stream routing. */
  5739. ma_bool8 noHardwareOffloading; /* Disables WASAPI's hardware offloading feature. */
  5740. ma_uint32 loopbackProcessID; /* The process ID to include or exclude for loopback mode. Set to 0 to capture audio from all processes. Ignored when an explicit device ID is specified. */
  5741. ma_bool8 loopbackProcessExclude; /* When set to true, excludes the process specified by loopbackProcessID. By default, the process will be included. */
  5742. } wasapi;
  5743. struct
  5744. {
  5745. ma_bool32 noMMap; /* Disables MMap mode. */
  5746. ma_bool32 noAutoFormat; /* Opens the ALSA device with SND_PCM_NO_AUTO_FORMAT. */
  5747. ma_bool32 noAutoChannels; /* Opens the ALSA device with SND_PCM_NO_AUTO_CHANNELS. */
  5748. ma_bool32 noAutoResample; /* Opens the ALSA device with SND_PCM_NO_AUTO_RESAMPLE. */
  5749. } alsa;
  5750. struct
  5751. {
  5752. const char* pStreamNamePlayback;
  5753. const char* pStreamNameCapture;
  5754. } pulse;
  5755. struct
  5756. {
  5757. ma_bool32 allowNominalSampleRateChange; /* Desktop only. When enabled, allows changing of the sample rate at the operating system level. */
  5758. } coreaudio;
  5759. struct
  5760. {
  5761. ma_opensl_stream_type streamType;
  5762. ma_opensl_recording_preset recordingPreset;
  5763. ma_bool32 enableCompatibilityWorkarounds;
  5764. } opensl;
  5765. struct
  5766. {
  5767. ma_aaudio_usage usage;
  5768. ma_aaudio_content_type contentType;
  5769. ma_aaudio_input_preset inputPreset;
  5770. ma_aaudio_allowed_capture_policy allowedCapturePolicy;
  5771. ma_bool32 noAutoStartAfterReroute;
  5772. ma_bool32 enableCompatibilityWorkarounds;
  5773. } aaudio;
  5774. };
  5775. /*
  5776. The callback for handling device enumeration. This is fired from `ma_context_enumerated_devices()`.
  5777. Parameters
  5778. ----------
  5779. pContext (in)
  5780. A pointer to the context performing the enumeration.
  5781. deviceType (in)
  5782. The type of the device being enumerated. This will always be either `ma_device_type_playback` or `ma_device_type_capture`.
  5783. pInfo (in)
  5784. A pointer to a `ma_device_info` containing the ID and name of the enumerated device. Note that this will not include detailed information about the device,
  5785. only basic information (ID and name). The reason for this is that it would otherwise require opening the backend device to probe for the information which
  5786. is too inefficient.
  5787. pUserData (in)
  5788. The user data pointer passed into `ma_context_enumerate_devices()`.
  5789. */
  5790. typedef ma_bool32 (* ma_enum_devices_callback_proc)(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData);
  5791. /*
  5792. Describes some basic details about a playback or capture device.
  5793. */
  5794. typedef struct
  5795. {
  5796. const ma_device_id* pDeviceID;
  5797. ma_share_mode shareMode;
  5798. ma_format format;
  5799. ma_uint32 channels;
  5800. ma_uint32 sampleRate;
  5801. ma_channel channelMap[MA_MAX_CHANNELS];
  5802. ma_uint32 periodSizeInFrames;
  5803. ma_uint32 periodSizeInMilliseconds;
  5804. ma_uint32 periodCount;
  5805. } ma_device_descriptor;
  5806. /*
  5807. These are the callbacks required to be implemented for a backend. These callbacks are grouped into two parts: context and device. There is one context
  5808. to many devices. A device is created from a context.
  5809. The general flow goes like this:
  5810. 1) A context is created with `onContextInit()`
  5811. 1a) Available devices can be enumerated with `onContextEnumerateDevices()` if required.
  5812. 1b) Detailed information about a device can be queried with `onContextGetDeviceInfo()` if required.
  5813. 2) A device is created from the context that was created in the first step using `onDeviceInit()`, and optionally a device ID that was
  5814. selected from device enumeration via `onContextEnumerateDevices()`.
  5815. 3) A device is started or stopped with `onDeviceStart()` / `onDeviceStop()`
  5816. 4) Data is delivered to and from the device by the backend. This is always done based on the native format returned by the prior call
  5817. to `onDeviceInit()`. Conversion between the device's native format and the format requested by the application will be handled by
  5818. miniaudio internally.
  5819. Initialization of the context is quite simple. You need to do any necessary initialization of internal objects and then output the
  5820. callbacks defined in this structure.
  5821. Once the context has been initialized you can initialize a device. Before doing so, however, the application may want to know which
  5822. physical devices are available. This is where `onContextEnumerateDevices()` comes in. This is fairly simple. For each device, fire the
  5823. given callback with, at a minimum, the basic information filled out in `ma_device_info`. When the callback returns `MA_FALSE`, enumeration
  5824. needs to stop and the `onContextEnumerateDevices()` function returns with a success code.
  5825. Detailed device information can be retrieved from a device ID using `onContextGetDeviceInfo()`. This takes as input the device type and ID,
  5826. and on output returns detailed information about the device in `ma_device_info`. The `onContextGetDeviceInfo()` callback must handle the
  5827. case when the device ID is NULL, in which case information about the default device needs to be retrieved.
  5828. Once the context has been created and the device ID retrieved (if using anything other than the default device), the device can be created.
  5829. This is a little bit more complicated than initialization of the context due to it's more complicated configuration. When initializing a
  5830. device, a duplex device may be requested. This means a separate data format needs to be specified for both playback and capture. On input,
  5831. the data format is set to what the application wants. On output it's set to the native format which should match as closely as possible to
  5832. the requested format. The conversion between the format requested by the application and the device's native format will be handled
  5833. internally by miniaudio.
  5834. On input, if the sample format is set to `ma_format_unknown`, the backend is free to use whatever sample format it desires, so long as it's
  5835. supported by miniaudio. When the channel count is set to 0, the backend should use the device's native channel count. The same applies for
  5836. sample rate. For the channel map, the default should be used when `ma_channel_map_is_blank()` returns true (all channels set to
  5837. `MA_CHANNEL_NONE`). On input, the `periodSizeInFrames` or `periodSizeInMilliseconds` option should always be set. The backend should
  5838. inspect both of these variables. If `periodSizeInFrames` is set, it should take priority, otherwise it needs to be derived from the period
  5839. size in milliseconds (`periodSizeInMilliseconds`) and the sample rate, keeping in mind that the sample rate may be 0, in which case the
  5840. sample rate will need to be determined before calculating the period size in frames. On output, all members of the `ma_device_descriptor`
  5841. object should be set to a valid value, except for `periodSizeInMilliseconds` which is optional (`periodSizeInFrames` *must* be set).
  5842. Starting and stopping of the device is done with `onDeviceStart()` and `onDeviceStop()` and should be self-explanatory. If the backend uses
  5843. asynchronous reading and writing, `onDeviceStart()` and `onDeviceStop()` should always be implemented.
  5844. The handling of data delivery between the application and the device is the most complicated part of the process. To make this a bit
  5845. easier, some helper callbacks are available. If the backend uses a blocking read/write style of API, the `onDeviceRead()` and
  5846. `onDeviceWrite()` callbacks can optionally be implemented. These are blocking and work just like reading and writing from a file. If the
  5847. backend uses a callback for data delivery, that callback must call `ma_device_handle_backend_data_callback()` from within it's callback.
  5848. This allows miniaudio to then process any necessary data conversion and then pass it to the miniaudio data callback.
  5849. If the backend requires absolute flexibility with it's data delivery, it can optionally implement the `onDeviceDataLoop()` callback
  5850. which will allow it to implement the logic that will run on the audio thread. This is much more advanced and is completely optional.
  5851. The audio thread should run data delivery logic in a loop while `ma_device_get_state() == ma_device_state_started` and no errors have been
  5852. encountered. Do not start or stop the device here. That will be handled from outside the `onDeviceDataLoop()` callback.
  5853. The invocation of the `onDeviceDataLoop()` callback will be handled by miniaudio. When you start the device, miniaudio will fire this
  5854. callback. When the device is stopped, the `ma_device_get_state() == ma_device_state_started` condition will fail and the loop will be terminated
  5855. which will then fall through to the part that stops the device. For an example on how to implement the `onDeviceDataLoop()` callback,
  5856. look at `ma_device_audio_thread__default_read_write()`. Implement the `onDeviceDataLoopWakeup()` callback if you need a mechanism to
  5857. wake up the audio thread.
  5858. If the backend supports an optimized retrieval of device information from an initialized `ma_device` object, it should implement the
  5859. `onDeviceGetInfo()` callback. This is optional, in which case it will fall back to `onContextGetDeviceInfo()` which is less efficient.
  5860. */
  5861. struct ma_backend_callbacks
  5862. {
  5863. ma_result (* onContextInit)(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks);
  5864. ma_result (* onContextUninit)(ma_context* pContext);
  5865. ma_result (* onContextEnumerateDevices)(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData);
  5866. ma_result (* onContextGetDeviceInfo)(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo);
  5867. ma_result (* onDeviceInit)(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture);
  5868. ma_result (* onDeviceUninit)(ma_device* pDevice);
  5869. ma_result (* onDeviceStart)(ma_device* pDevice);
  5870. ma_result (* onDeviceStop)(ma_device* pDevice);
  5871. ma_result (* onDeviceRead)(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead);
  5872. ma_result (* onDeviceWrite)(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten);
  5873. ma_result (* onDeviceDataLoop)(ma_device* pDevice);
  5874. ma_result (* onDeviceDataLoopWakeup)(ma_device* pDevice);
  5875. ma_result (* onDeviceGetInfo)(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo);
  5876. };
  5877. struct ma_context_config
  5878. {
  5879. ma_log* pLog;
  5880. ma_thread_priority threadPriority;
  5881. size_t threadStackSize;
  5882. void* pUserData;
  5883. ma_allocation_callbacks allocationCallbacks;
  5884. struct
  5885. {
  5886. ma_bool32 useVerboseDeviceEnumeration;
  5887. } alsa;
  5888. struct
  5889. {
  5890. const char* pApplicationName;
  5891. const char* pServerName;
  5892. ma_bool32 tryAutoSpawn; /* Enables autospawning of the PulseAudio daemon if necessary. */
  5893. } pulse;
  5894. struct
  5895. {
  5896. ma_ios_session_category sessionCategory;
  5897. ma_uint32 sessionCategoryOptions;
  5898. ma_bool32 noAudioSessionActivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization. */
  5899. ma_bool32 noAudioSessionDeactivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization. */
  5900. } coreaudio;
  5901. struct
  5902. {
  5903. const char* pClientName;
  5904. ma_bool32 tryStartServer;
  5905. } jack;
  5906. ma_backend_callbacks custom;
  5907. };
  5908. /* WASAPI specific structure for some commands which must run on a common thread due to bugs in WASAPI. */
  5909. typedef struct
  5910. {
  5911. int code;
  5912. ma_event* pEvent; /* This will be signalled when the event is complete. */
  5913. union
  5914. {
  5915. struct
  5916. {
  5917. int _unused;
  5918. } quit;
  5919. struct
  5920. {
  5921. ma_device_type deviceType;
  5922. void* pAudioClient;
  5923. void** ppAudioClientService;
  5924. ma_result* pResult; /* The result from creating the audio client service. */
  5925. } createAudioClient;
  5926. struct
  5927. {
  5928. ma_device* pDevice;
  5929. ma_device_type deviceType;
  5930. } releaseAudioClient;
  5931. } data;
  5932. } ma_context_command__wasapi;
  5933. struct ma_context
  5934. {
  5935. ma_backend_callbacks callbacks;
  5936. ma_backend backend; /* DirectSound, ALSA, etc. */
  5937. ma_log* pLog;
  5938. ma_log log; /* Only used if the log is owned by the context. The pLog member will be set to &log in this case. */
  5939. ma_thread_priority threadPriority;
  5940. size_t threadStackSize;
  5941. void* pUserData;
  5942. ma_allocation_callbacks allocationCallbacks;
  5943. ma_mutex deviceEnumLock; /* Used to make ma_context_get_devices() thread safe. */
  5944. ma_mutex deviceInfoLock; /* Used to make ma_context_get_device_info() thread safe. */
  5945. ma_uint32 deviceInfoCapacity; /* Total capacity of pDeviceInfos. */
  5946. ma_uint32 playbackDeviceInfoCount;
  5947. ma_uint32 captureDeviceInfoCount;
  5948. ma_device_info* pDeviceInfos; /* Playback devices first, then capture. */
  5949. union
  5950. {
  5951. #ifdef MA_SUPPORT_WASAPI
  5952. struct
  5953. {
  5954. ma_thread commandThread;
  5955. ma_mutex commandLock;
  5956. ma_semaphore commandSem;
  5957. ma_uint32 commandIndex;
  5958. ma_uint32 commandCount;
  5959. ma_context_command__wasapi commands[4];
  5960. ma_handle hAvrt;
  5961. ma_proc AvSetMmThreadCharacteristicsA;
  5962. ma_proc AvRevertMmThreadcharacteristics;
  5963. ma_handle hMMDevapi;
  5964. ma_proc ActivateAudioInterfaceAsync;
  5965. } wasapi;
  5966. #endif
  5967. #ifdef MA_SUPPORT_DSOUND
  5968. struct
  5969. {
  5970. ma_handle hDSoundDLL;
  5971. ma_proc DirectSoundCreate;
  5972. ma_proc DirectSoundEnumerateA;
  5973. ma_proc DirectSoundCaptureCreate;
  5974. ma_proc DirectSoundCaptureEnumerateA;
  5975. } dsound;
  5976. #endif
  5977. #ifdef MA_SUPPORT_WINMM
  5978. struct
  5979. {
  5980. ma_handle hWinMM;
  5981. ma_proc waveOutGetNumDevs;
  5982. ma_proc waveOutGetDevCapsA;
  5983. ma_proc waveOutOpen;
  5984. ma_proc waveOutClose;
  5985. ma_proc waveOutPrepareHeader;
  5986. ma_proc waveOutUnprepareHeader;
  5987. ma_proc waveOutWrite;
  5988. ma_proc waveOutReset;
  5989. ma_proc waveInGetNumDevs;
  5990. ma_proc waveInGetDevCapsA;
  5991. ma_proc waveInOpen;
  5992. ma_proc waveInClose;
  5993. ma_proc waveInPrepareHeader;
  5994. ma_proc waveInUnprepareHeader;
  5995. ma_proc waveInAddBuffer;
  5996. ma_proc waveInStart;
  5997. ma_proc waveInReset;
  5998. } winmm;
  5999. #endif
  6000. #ifdef MA_SUPPORT_ALSA
  6001. struct
  6002. {
  6003. ma_handle asoundSO;
  6004. ma_proc snd_pcm_open;
  6005. ma_proc snd_pcm_close;
  6006. ma_proc snd_pcm_hw_params_sizeof;
  6007. ma_proc snd_pcm_hw_params_any;
  6008. ma_proc snd_pcm_hw_params_set_format;
  6009. ma_proc snd_pcm_hw_params_set_format_first;
  6010. ma_proc snd_pcm_hw_params_get_format_mask;
  6011. ma_proc snd_pcm_hw_params_set_channels;
  6012. ma_proc snd_pcm_hw_params_set_channels_near;
  6013. ma_proc snd_pcm_hw_params_set_channels_minmax;
  6014. ma_proc snd_pcm_hw_params_set_rate_resample;
  6015. ma_proc snd_pcm_hw_params_set_rate;
  6016. ma_proc snd_pcm_hw_params_set_rate_near;
  6017. ma_proc snd_pcm_hw_params_set_buffer_size_near;
  6018. ma_proc snd_pcm_hw_params_set_periods_near;
  6019. ma_proc snd_pcm_hw_params_set_access;
  6020. ma_proc snd_pcm_hw_params_get_format;
  6021. ma_proc snd_pcm_hw_params_get_channels;
  6022. ma_proc snd_pcm_hw_params_get_channels_min;
  6023. ma_proc snd_pcm_hw_params_get_channels_max;
  6024. ma_proc snd_pcm_hw_params_get_rate;
  6025. ma_proc snd_pcm_hw_params_get_rate_min;
  6026. ma_proc snd_pcm_hw_params_get_rate_max;
  6027. ma_proc snd_pcm_hw_params_get_buffer_size;
  6028. ma_proc snd_pcm_hw_params_get_periods;
  6029. ma_proc snd_pcm_hw_params_get_access;
  6030. ma_proc snd_pcm_hw_params_test_format;
  6031. ma_proc snd_pcm_hw_params_test_channels;
  6032. ma_proc snd_pcm_hw_params_test_rate;
  6033. ma_proc snd_pcm_hw_params;
  6034. ma_proc snd_pcm_sw_params_sizeof;
  6035. ma_proc snd_pcm_sw_params_current;
  6036. ma_proc snd_pcm_sw_params_get_boundary;
  6037. ma_proc snd_pcm_sw_params_set_avail_min;
  6038. ma_proc snd_pcm_sw_params_set_start_threshold;
  6039. ma_proc snd_pcm_sw_params_set_stop_threshold;
  6040. ma_proc snd_pcm_sw_params;
  6041. ma_proc snd_pcm_format_mask_sizeof;
  6042. ma_proc snd_pcm_format_mask_test;
  6043. ma_proc snd_pcm_get_chmap;
  6044. ma_proc snd_pcm_state;
  6045. ma_proc snd_pcm_prepare;
  6046. ma_proc snd_pcm_start;
  6047. ma_proc snd_pcm_drop;
  6048. ma_proc snd_pcm_drain;
  6049. ma_proc snd_pcm_reset;
  6050. ma_proc snd_device_name_hint;
  6051. ma_proc snd_device_name_get_hint;
  6052. ma_proc snd_card_get_index;
  6053. ma_proc snd_device_name_free_hint;
  6054. ma_proc snd_pcm_mmap_begin;
  6055. ma_proc snd_pcm_mmap_commit;
  6056. ma_proc snd_pcm_recover;
  6057. ma_proc snd_pcm_readi;
  6058. ma_proc snd_pcm_writei;
  6059. ma_proc snd_pcm_avail;
  6060. ma_proc snd_pcm_avail_update;
  6061. ma_proc snd_pcm_wait;
  6062. ma_proc snd_pcm_nonblock;
  6063. ma_proc snd_pcm_info;
  6064. ma_proc snd_pcm_info_sizeof;
  6065. ma_proc snd_pcm_info_get_name;
  6066. ma_proc snd_pcm_poll_descriptors;
  6067. ma_proc snd_pcm_poll_descriptors_count;
  6068. ma_proc snd_pcm_poll_descriptors_revents;
  6069. ma_proc snd_config_update_free_global;
  6070. ma_mutex internalDeviceEnumLock;
  6071. ma_bool32 useVerboseDeviceEnumeration;
  6072. } alsa;
  6073. #endif
  6074. #ifdef MA_SUPPORT_PULSEAUDIO
  6075. struct
  6076. {
  6077. ma_handle pulseSO;
  6078. ma_proc pa_mainloop_new;
  6079. ma_proc pa_mainloop_free;
  6080. ma_proc pa_mainloop_quit;
  6081. ma_proc pa_mainloop_get_api;
  6082. ma_proc pa_mainloop_iterate;
  6083. ma_proc pa_mainloop_wakeup;
  6084. ma_proc pa_threaded_mainloop_new;
  6085. ma_proc pa_threaded_mainloop_free;
  6086. ma_proc pa_threaded_mainloop_start;
  6087. ma_proc pa_threaded_mainloop_stop;
  6088. ma_proc pa_threaded_mainloop_lock;
  6089. ma_proc pa_threaded_mainloop_unlock;
  6090. ma_proc pa_threaded_mainloop_wait;
  6091. ma_proc pa_threaded_mainloop_signal;
  6092. ma_proc pa_threaded_mainloop_accept;
  6093. ma_proc pa_threaded_mainloop_get_retval;
  6094. ma_proc pa_threaded_mainloop_get_api;
  6095. ma_proc pa_threaded_mainloop_in_thread;
  6096. ma_proc pa_threaded_mainloop_set_name;
  6097. ma_proc pa_context_new;
  6098. ma_proc pa_context_unref;
  6099. ma_proc pa_context_connect;
  6100. ma_proc pa_context_disconnect;
  6101. ma_proc pa_context_set_state_callback;
  6102. ma_proc pa_context_get_state;
  6103. ma_proc pa_context_get_sink_info_list;
  6104. ma_proc pa_context_get_source_info_list;
  6105. ma_proc pa_context_get_sink_info_by_name;
  6106. ma_proc pa_context_get_source_info_by_name;
  6107. ma_proc pa_operation_unref;
  6108. ma_proc pa_operation_get_state;
  6109. ma_proc pa_channel_map_init_extend;
  6110. ma_proc pa_channel_map_valid;
  6111. ma_proc pa_channel_map_compatible;
  6112. ma_proc pa_stream_new;
  6113. ma_proc pa_stream_unref;
  6114. ma_proc pa_stream_connect_playback;
  6115. ma_proc pa_stream_connect_record;
  6116. ma_proc pa_stream_disconnect;
  6117. ma_proc pa_stream_get_state;
  6118. ma_proc pa_stream_get_sample_spec;
  6119. ma_proc pa_stream_get_channel_map;
  6120. ma_proc pa_stream_get_buffer_attr;
  6121. ma_proc pa_stream_set_buffer_attr;
  6122. ma_proc pa_stream_get_device_name;
  6123. ma_proc pa_stream_set_write_callback;
  6124. ma_proc pa_stream_set_read_callback;
  6125. ma_proc pa_stream_set_suspended_callback;
  6126. ma_proc pa_stream_set_moved_callback;
  6127. ma_proc pa_stream_is_suspended;
  6128. ma_proc pa_stream_flush;
  6129. ma_proc pa_stream_drain;
  6130. ma_proc pa_stream_is_corked;
  6131. ma_proc pa_stream_cork;
  6132. ma_proc pa_stream_trigger;
  6133. ma_proc pa_stream_begin_write;
  6134. ma_proc pa_stream_write;
  6135. ma_proc pa_stream_peek;
  6136. ma_proc pa_stream_drop;
  6137. ma_proc pa_stream_writable_size;
  6138. ma_proc pa_stream_readable_size;
  6139. /*pa_mainloop**/ ma_ptr pMainLoop;
  6140. /*pa_context**/ ma_ptr pPulseContext;
  6141. char* pApplicationName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */
  6142. char* pServerName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */
  6143. } pulse;
  6144. #endif
  6145. #ifdef MA_SUPPORT_JACK
  6146. struct
  6147. {
  6148. ma_handle jackSO;
  6149. ma_proc jack_client_open;
  6150. ma_proc jack_client_close;
  6151. ma_proc jack_client_name_size;
  6152. ma_proc jack_set_process_callback;
  6153. ma_proc jack_set_buffer_size_callback;
  6154. ma_proc jack_on_shutdown;
  6155. ma_proc jack_get_sample_rate;
  6156. ma_proc jack_get_buffer_size;
  6157. ma_proc jack_get_ports;
  6158. ma_proc jack_activate;
  6159. ma_proc jack_deactivate;
  6160. ma_proc jack_connect;
  6161. ma_proc jack_port_register;
  6162. ma_proc jack_port_name;
  6163. ma_proc jack_port_get_buffer;
  6164. ma_proc jack_free;
  6165. char* pClientName;
  6166. ma_bool32 tryStartServer;
  6167. } jack;
  6168. #endif
  6169. #ifdef MA_SUPPORT_COREAUDIO
  6170. struct
  6171. {
  6172. ma_handle hCoreFoundation;
  6173. ma_proc CFStringGetCString;
  6174. ma_proc CFRelease;
  6175. ma_handle hCoreAudio;
  6176. ma_proc AudioObjectGetPropertyData;
  6177. ma_proc AudioObjectGetPropertyDataSize;
  6178. ma_proc AudioObjectSetPropertyData;
  6179. ma_proc AudioObjectAddPropertyListener;
  6180. ma_proc AudioObjectRemovePropertyListener;
  6181. ma_handle hAudioUnit; /* Could possibly be set to AudioToolbox on later versions of macOS. */
  6182. ma_proc AudioComponentFindNext;
  6183. ma_proc AudioComponentInstanceDispose;
  6184. ma_proc AudioComponentInstanceNew;
  6185. ma_proc AudioOutputUnitStart;
  6186. ma_proc AudioOutputUnitStop;
  6187. ma_proc AudioUnitAddPropertyListener;
  6188. ma_proc AudioUnitGetPropertyInfo;
  6189. ma_proc AudioUnitGetProperty;
  6190. ma_proc AudioUnitSetProperty;
  6191. ma_proc AudioUnitInitialize;
  6192. ma_proc AudioUnitRender;
  6193. /*AudioComponent*/ ma_ptr component;
  6194. ma_bool32 noAudioSessionDeactivate; /* For tracking whether or not the iOS audio session should be explicitly deactivated. Set from the config in ma_context_init__coreaudio(). */
  6195. } coreaudio;
  6196. #endif
  6197. #ifdef MA_SUPPORT_SNDIO
  6198. struct
  6199. {
  6200. ma_handle sndioSO;
  6201. ma_proc sio_open;
  6202. ma_proc sio_close;
  6203. ma_proc sio_setpar;
  6204. ma_proc sio_getpar;
  6205. ma_proc sio_getcap;
  6206. ma_proc sio_start;
  6207. ma_proc sio_stop;
  6208. ma_proc sio_read;
  6209. ma_proc sio_write;
  6210. ma_proc sio_onmove;
  6211. ma_proc sio_nfds;
  6212. ma_proc sio_pollfd;
  6213. ma_proc sio_revents;
  6214. ma_proc sio_eof;
  6215. ma_proc sio_setvol;
  6216. ma_proc sio_onvol;
  6217. ma_proc sio_initpar;
  6218. } sndio;
  6219. #endif
  6220. #ifdef MA_SUPPORT_AUDIO4
  6221. struct
  6222. {
  6223. int _unused;
  6224. } audio4;
  6225. #endif
  6226. #ifdef MA_SUPPORT_OSS
  6227. struct
  6228. {
  6229. int versionMajor;
  6230. int versionMinor;
  6231. } oss;
  6232. #endif
  6233. #ifdef MA_SUPPORT_AAUDIO
  6234. struct
  6235. {
  6236. ma_handle hAAudio; /* libaaudio.so */
  6237. ma_proc AAudio_createStreamBuilder;
  6238. ma_proc AAudioStreamBuilder_delete;
  6239. ma_proc AAudioStreamBuilder_setDeviceId;
  6240. ma_proc AAudioStreamBuilder_setDirection;
  6241. ma_proc AAudioStreamBuilder_setSharingMode;
  6242. ma_proc AAudioStreamBuilder_setFormat;
  6243. ma_proc AAudioStreamBuilder_setChannelCount;
  6244. ma_proc AAudioStreamBuilder_setSampleRate;
  6245. ma_proc AAudioStreamBuilder_setBufferCapacityInFrames;
  6246. ma_proc AAudioStreamBuilder_setFramesPerDataCallback;
  6247. ma_proc AAudioStreamBuilder_setDataCallback;
  6248. ma_proc AAudioStreamBuilder_setErrorCallback;
  6249. ma_proc AAudioStreamBuilder_setPerformanceMode;
  6250. ma_proc AAudioStreamBuilder_setUsage;
  6251. ma_proc AAudioStreamBuilder_setContentType;
  6252. ma_proc AAudioStreamBuilder_setInputPreset;
  6253. ma_proc AAudioStreamBuilder_setAllowedCapturePolicy;
  6254. ma_proc AAudioStreamBuilder_openStream;
  6255. ma_proc AAudioStream_close;
  6256. ma_proc AAudioStream_getState;
  6257. ma_proc AAudioStream_waitForStateChange;
  6258. ma_proc AAudioStream_getFormat;
  6259. ma_proc AAudioStream_getChannelCount;
  6260. ma_proc AAudioStream_getSampleRate;
  6261. ma_proc AAudioStream_getBufferCapacityInFrames;
  6262. ma_proc AAudioStream_getFramesPerDataCallback;
  6263. ma_proc AAudioStream_getFramesPerBurst;
  6264. ma_proc AAudioStream_requestStart;
  6265. ma_proc AAudioStream_requestStop;
  6266. ma_device_job_thread jobThread; /* For processing operations outside of the error callback, specifically device disconnections and rerouting. */
  6267. } aaudio;
  6268. #endif
  6269. #ifdef MA_SUPPORT_OPENSL
  6270. struct
  6271. {
  6272. ma_handle libOpenSLES;
  6273. ma_handle SL_IID_ENGINE;
  6274. ma_handle SL_IID_AUDIOIODEVICECAPABILITIES;
  6275. ma_handle SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
  6276. ma_handle SL_IID_RECORD;
  6277. ma_handle SL_IID_PLAY;
  6278. ma_handle SL_IID_OUTPUTMIX;
  6279. ma_handle SL_IID_ANDROIDCONFIGURATION;
  6280. ma_proc slCreateEngine;
  6281. } opensl;
  6282. #endif
  6283. #ifdef MA_SUPPORT_WEBAUDIO
  6284. struct
  6285. {
  6286. int _unused;
  6287. } webaudio;
  6288. #endif
  6289. #ifdef MA_SUPPORT_NULL
  6290. struct
  6291. {
  6292. int _unused;
  6293. } null_backend;
  6294. #endif
  6295. };
  6296. union
  6297. {
  6298. #if defined(MA_WIN32)
  6299. struct
  6300. {
  6301. /*HMODULE*/ ma_handle hOle32DLL;
  6302. ma_proc CoInitialize;
  6303. ma_proc CoInitializeEx;
  6304. ma_proc CoUninitialize;
  6305. ma_proc CoCreateInstance;
  6306. ma_proc CoTaskMemFree;
  6307. ma_proc PropVariantClear;
  6308. ma_proc StringFromGUID2;
  6309. /*HMODULE*/ ma_handle hUser32DLL;
  6310. ma_proc GetForegroundWindow;
  6311. ma_proc GetDesktopWindow;
  6312. /*HMODULE*/ ma_handle hAdvapi32DLL;
  6313. ma_proc RegOpenKeyExA;
  6314. ma_proc RegCloseKey;
  6315. ma_proc RegQueryValueExA;
  6316. } win32;
  6317. #endif
  6318. #ifdef MA_POSIX
  6319. struct
  6320. {
  6321. int _unused;
  6322. } posix;
  6323. #endif
  6324. int _unused;
  6325. };
  6326. };
  6327. struct ma_device
  6328. {
  6329. ma_context* pContext;
  6330. ma_device_type type;
  6331. ma_uint32 sampleRate;
  6332. ma_atomic_device_state state; /* The state of the device is variable and can change at any time on any thread. Must be used atomically. */
  6333. ma_device_data_proc onData; /* Set once at initialization time and should not be changed after. */
  6334. ma_device_notification_proc onNotification; /* Set once at initialization time and should not be changed after. */
  6335. ma_stop_proc onStop; /* DEPRECATED. Use the notification callback instead. Set once at initialization time and should not be changed after. */
  6336. void* pUserData; /* Application defined data. */
  6337. ma_mutex startStopLock;
  6338. ma_event wakeupEvent;
  6339. ma_event startEvent;
  6340. ma_event stopEvent;
  6341. ma_thread thread;
  6342. ma_result workResult; /* This is set by the worker thread after it's finished doing a job. */
  6343. ma_bool8 isOwnerOfContext; /* When set to true, uninitializing the device will also uninitialize the context. Set to true when NULL is passed into ma_device_init(). */
  6344. ma_bool8 noPreSilencedOutputBuffer;
  6345. ma_bool8 noClip;
  6346. ma_bool8 noDisableDenormals;
  6347. ma_bool8 noFixedSizedCallback;
  6348. ma_atomic_float masterVolumeFactor; /* Linear 0..1. Can be read and written simultaneously by different threads. Must be used atomically. */
  6349. ma_duplex_rb duplexRB; /* Intermediary buffer for duplex device on asynchronous backends. */
  6350. struct
  6351. {
  6352. ma_resample_algorithm algorithm;
  6353. ma_resampling_backend_vtable* pBackendVTable;
  6354. void* pBackendUserData;
  6355. struct
  6356. {
  6357. ma_uint32 lpfOrder;
  6358. } linear;
  6359. } resampling;
  6360. struct
  6361. {
  6362. ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */
  6363. ma_device_id id; /* If using an explicit device, will be set to a copy of the ID used for initialization. Otherwise cleared to 0. */
  6364. char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* Maybe temporary. Likely to be replaced with a query API. */
  6365. ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
  6366. ma_format format;
  6367. ma_uint32 channels;
  6368. ma_channel channelMap[MA_MAX_CHANNELS];
  6369. ma_format internalFormat;
  6370. ma_uint32 internalChannels;
  6371. ma_uint32 internalSampleRate;
  6372. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  6373. ma_uint32 internalPeriodSizeInFrames;
  6374. ma_uint32 internalPeriods;
  6375. ma_channel_mix_mode channelMixMode;
  6376. ma_bool32 calculateLFEFromSpatialChannels;
  6377. ma_data_converter converter;
  6378. void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */
  6379. ma_uint32 intermediaryBufferCap;
  6380. ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */
  6381. void* pInputCache; /* In external format. Can be null. */
  6382. ma_uint64 inputCacheCap;
  6383. ma_uint64 inputCacheConsumed;
  6384. ma_uint64 inputCacheRemaining;
  6385. } playback;
  6386. struct
  6387. {
  6388. ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */
  6389. ma_device_id id; /* If using an explicit device, will be set to a copy of the ID used for initialization. Otherwise cleared to 0. */
  6390. char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* Maybe temporary. Likely to be replaced with a query API. */
  6391. ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
  6392. ma_format format;
  6393. ma_uint32 channels;
  6394. ma_channel channelMap[MA_MAX_CHANNELS];
  6395. ma_format internalFormat;
  6396. ma_uint32 internalChannels;
  6397. ma_uint32 internalSampleRate;
  6398. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  6399. ma_uint32 internalPeriodSizeInFrames;
  6400. ma_uint32 internalPeriods;
  6401. ma_channel_mix_mode channelMixMode;
  6402. ma_bool32 calculateLFEFromSpatialChannels;
  6403. ma_data_converter converter;
  6404. void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */
  6405. ma_uint32 intermediaryBufferCap;
  6406. ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */
  6407. } capture;
  6408. union
  6409. {
  6410. #ifdef MA_SUPPORT_WASAPI
  6411. struct
  6412. {
  6413. /*IAudioClient**/ ma_ptr pAudioClientPlayback;
  6414. /*IAudioClient**/ ma_ptr pAudioClientCapture;
  6415. /*IAudioRenderClient**/ ma_ptr pRenderClient;
  6416. /*IAudioCaptureClient**/ ma_ptr pCaptureClient;
  6417. /*IMMDeviceEnumerator**/ ma_ptr pDeviceEnumerator; /* Used for IMMNotificationClient notifications. Required for detecting default device changes. */
  6418. ma_IMMNotificationClient notificationClient;
  6419. /*HANDLE*/ ma_handle hEventPlayback; /* Auto reset. Initialized to signaled. */
  6420. /*HANDLE*/ ma_handle hEventCapture; /* Auto reset. Initialized to unsignaled. */
  6421. ma_uint32 actualBufferSizeInFramesPlayback; /* Value from GetBufferSize(). internalPeriodSizeInFrames is not set to the _actual_ buffer size when low-latency shared mode is being used due to the way the IAudioClient3 API works. */
  6422. ma_uint32 actualBufferSizeInFramesCapture;
  6423. ma_uint32 originalPeriodSizeInFrames;
  6424. ma_uint32 originalPeriodSizeInMilliseconds;
  6425. ma_uint32 originalPeriods;
  6426. ma_performance_profile originalPerformanceProfile;
  6427. ma_uint32 periodSizeInFramesPlayback;
  6428. ma_uint32 periodSizeInFramesCapture;
  6429. void* pMappedBufferCapture;
  6430. ma_uint32 mappedBufferCaptureCap;
  6431. ma_uint32 mappedBufferCaptureLen;
  6432. void* pMappedBufferPlayback;
  6433. ma_uint32 mappedBufferPlaybackCap;
  6434. ma_uint32 mappedBufferPlaybackLen;
  6435. ma_atomic_bool32 isStartedCapture; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */
  6436. ma_atomic_bool32 isStartedPlayback; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */
  6437. ma_uint32 loopbackProcessID;
  6438. ma_bool8 loopbackProcessExclude;
  6439. ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
  6440. ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
  6441. ma_bool8 noHardwareOffloading;
  6442. ma_bool8 allowCaptureAutoStreamRouting;
  6443. ma_bool8 allowPlaybackAutoStreamRouting;
  6444. ma_bool8 isDetachedPlayback;
  6445. ma_bool8 isDetachedCapture;
  6446. ma_wasapi_usage usage;
  6447. void* hAvrtHandle;
  6448. ma_mutex rerouteLock;
  6449. } wasapi;
  6450. #endif
  6451. #ifdef MA_SUPPORT_DSOUND
  6452. struct
  6453. {
  6454. /*LPDIRECTSOUND*/ ma_ptr pPlayback;
  6455. /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackPrimaryBuffer;
  6456. /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackBuffer;
  6457. /*LPDIRECTSOUNDCAPTURE*/ ma_ptr pCapture;
  6458. /*LPDIRECTSOUNDCAPTUREBUFFER*/ ma_ptr pCaptureBuffer;
  6459. } dsound;
  6460. #endif
  6461. #ifdef MA_SUPPORT_WINMM
  6462. struct
  6463. {
  6464. /*HWAVEOUT*/ ma_handle hDevicePlayback;
  6465. /*HWAVEIN*/ ma_handle hDeviceCapture;
  6466. /*HANDLE*/ ma_handle hEventPlayback;
  6467. /*HANDLE*/ ma_handle hEventCapture;
  6468. ma_uint32 fragmentSizeInFrames;
  6469. ma_uint32 iNextHeaderPlayback; /* [0,periods). Used as an index into pWAVEHDRPlayback. */
  6470. ma_uint32 iNextHeaderCapture; /* [0,periods). Used as an index into pWAVEHDRCapture. */
  6471. ma_uint32 headerFramesConsumedPlayback; /* The number of PCM frames consumed in the buffer in pWAVEHEADER[iNextHeader]. */
  6472. ma_uint32 headerFramesConsumedCapture; /* ^^^ */
  6473. /*WAVEHDR**/ ma_uint8* pWAVEHDRPlayback; /* One instantiation for each period. */
  6474. /*WAVEHDR**/ ma_uint8* pWAVEHDRCapture; /* One instantiation for each period. */
  6475. ma_uint8* pIntermediaryBufferPlayback;
  6476. ma_uint8* pIntermediaryBufferCapture;
  6477. ma_uint8* _pHeapData; /* Used internally and is used for the heap allocated data for the intermediary buffer and the WAVEHDR structures. */
  6478. } winmm;
  6479. #endif
  6480. #ifdef MA_SUPPORT_ALSA
  6481. struct
  6482. {
  6483. /*snd_pcm_t**/ ma_ptr pPCMPlayback;
  6484. /*snd_pcm_t**/ ma_ptr pPCMCapture;
  6485. /*struct pollfd**/ void* pPollDescriptorsPlayback;
  6486. /*struct pollfd**/ void* pPollDescriptorsCapture;
  6487. int pollDescriptorCountPlayback;
  6488. int pollDescriptorCountCapture;
  6489. int wakeupfdPlayback; /* eventfd for waking up from poll() when the playback device is stopped. */
  6490. int wakeupfdCapture; /* eventfd for waking up from poll() when the capture device is stopped. */
  6491. ma_bool8 isUsingMMapPlayback;
  6492. ma_bool8 isUsingMMapCapture;
  6493. } alsa;
  6494. #endif
  6495. #ifdef MA_SUPPORT_PULSEAUDIO
  6496. struct
  6497. {
  6498. /*pa_mainloop**/ ma_ptr pMainLoop;
  6499. /*pa_context**/ ma_ptr pPulseContext;
  6500. /*pa_stream**/ ma_ptr pStreamPlayback;
  6501. /*pa_stream**/ ma_ptr pStreamCapture;
  6502. } pulse;
  6503. #endif
  6504. #ifdef MA_SUPPORT_JACK
  6505. struct
  6506. {
  6507. /*jack_client_t**/ ma_ptr pClient;
  6508. /*jack_port_t**/ ma_ptr* ppPortsPlayback;
  6509. /*jack_port_t**/ ma_ptr* ppPortsCapture;
  6510. float* pIntermediaryBufferPlayback; /* Typed as a float because JACK is always floating point. */
  6511. float* pIntermediaryBufferCapture;
  6512. } jack;
  6513. #endif
  6514. #ifdef MA_SUPPORT_COREAUDIO
  6515. struct
  6516. {
  6517. ma_uint32 deviceObjectIDPlayback;
  6518. ma_uint32 deviceObjectIDCapture;
  6519. /*AudioUnit*/ ma_ptr audioUnitPlayback;
  6520. /*AudioUnit*/ ma_ptr audioUnitCapture;
  6521. /*AudioBufferList**/ ma_ptr pAudioBufferList; /* Only used for input devices. */
  6522. ma_uint32 audioBufferCapInFrames; /* Only used for input devices. The capacity in frames of each buffer in pAudioBufferList. */
  6523. ma_event stopEvent;
  6524. ma_uint32 originalPeriodSizeInFrames;
  6525. ma_uint32 originalPeriodSizeInMilliseconds;
  6526. ma_uint32 originalPeriods;
  6527. ma_performance_profile originalPerformanceProfile;
  6528. ma_bool32 isDefaultPlaybackDevice;
  6529. ma_bool32 isDefaultCaptureDevice;
  6530. ma_bool32 isSwitchingPlaybackDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
  6531. ma_bool32 isSwitchingCaptureDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
  6532. void* pNotificationHandler; /* Only used on mobile platforms. Obj-C object for handling route changes. */
  6533. } coreaudio;
  6534. #endif
  6535. #ifdef MA_SUPPORT_SNDIO
  6536. struct
  6537. {
  6538. ma_ptr handlePlayback;
  6539. ma_ptr handleCapture;
  6540. ma_bool32 isStartedPlayback;
  6541. ma_bool32 isStartedCapture;
  6542. } sndio;
  6543. #endif
  6544. #ifdef MA_SUPPORT_AUDIO4
  6545. struct
  6546. {
  6547. int fdPlayback;
  6548. int fdCapture;
  6549. } audio4;
  6550. #endif
  6551. #ifdef MA_SUPPORT_OSS
  6552. struct
  6553. {
  6554. int fdPlayback;
  6555. int fdCapture;
  6556. } oss;
  6557. #endif
  6558. #ifdef MA_SUPPORT_AAUDIO
  6559. struct
  6560. {
  6561. /*AAudioStream**/ ma_ptr pStreamPlayback;
  6562. /*AAudioStream**/ ma_ptr pStreamCapture;
  6563. ma_aaudio_usage usage;
  6564. ma_aaudio_content_type contentType;
  6565. ma_aaudio_input_preset inputPreset;
  6566. ma_aaudio_allowed_capture_policy allowedCapturePolicy;
  6567. ma_bool32 noAutoStartAfterReroute;
  6568. } aaudio;
  6569. #endif
  6570. #ifdef MA_SUPPORT_OPENSL
  6571. struct
  6572. {
  6573. /*SLObjectItf*/ ma_ptr pOutputMixObj;
  6574. /*SLOutputMixItf*/ ma_ptr pOutputMix;
  6575. /*SLObjectItf*/ ma_ptr pAudioPlayerObj;
  6576. /*SLPlayItf*/ ma_ptr pAudioPlayer;
  6577. /*SLObjectItf*/ ma_ptr pAudioRecorderObj;
  6578. /*SLRecordItf*/ ma_ptr pAudioRecorder;
  6579. /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueuePlayback;
  6580. /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueueCapture;
  6581. ma_bool32 isDrainingCapture;
  6582. ma_bool32 isDrainingPlayback;
  6583. ma_uint32 currentBufferIndexPlayback;
  6584. ma_uint32 currentBufferIndexCapture;
  6585. ma_uint8* pBufferPlayback; /* This is malloc()'d and is used for storing audio data. Typed as ma_uint8 for easy offsetting. */
  6586. ma_uint8* pBufferCapture;
  6587. } opensl;
  6588. #endif
  6589. #ifdef MA_SUPPORT_WEBAUDIO
  6590. struct
  6591. {
  6592. /* AudioWorklets path. */
  6593. /* EMSCRIPTEN_WEBAUDIO_T */ int audioContextPlayback;
  6594. /* EMSCRIPTEN_WEBAUDIO_T */ int audioContextCapture;
  6595. /* EMSCRIPTEN_AUDIO_WORKLET_NODE_T */ int workletNodePlayback;
  6596. /* EMSCRIPTEN_AUDIO_WORKLET_NODE_T */ int workletNodeCapture;
  6597. size_t intermediaryBufferSizeInFramesPlayback;
  6598. size_t intermediaryBufferSizeInFramesCapture;
  6599. float* pIntermediaryBufferPlayback;
  6600. float* pIntermediaryBufferCapture;
  6601. void* pStackBufferPlayback;
  6602. void* pStackBufferCapture;
  6603. ma_bool32 isInitialized;
  6604. /* ScriptProcessorNode path. */
  6605. int indexPlayback; /* We use a factory on the JavaScript side to manage devices and use an index for JS/C interop. */
  6606. int indexCapture;
  6607. } webaudio;
  6608. #endif
  6609. #ifdef MA_SUPPORT_NULL
  6610. struct
  6611. {
  6612. ma_thread deviceThread;
  6613. ma_event operationEvent;
  6614. ma_event operationCompletionEvent;
  6615. ma_semaphore operationSemaphore;
  6616. ma_uint32 operation;
  6617. ma_result operationResult;
  6618. ma_timer timer;
  6619. double priorRunTime;
  6620. ma_uint32 currentPeriodFramesRemainingPlayback;
  6621. ma_uint32 currentPeriodFramesRemainingCapture;
  6622. ma_uint64 lastProcessedFramePlayback;
  6623. ma_uint64 lastProcessedFrameCapture;
  6624. ma_atomic_bool32 isStarted; /* Read and written by multiple threads. Must be used atomically, and must be 32-bit for compiler compatibility. */
  6625. } null_device;
  6626. #endif
  6627. };
  6628. };
  6629. #if defined(_MSC_VER) && !defined(__clang__)
  6630. #pragma warning(pop)
  6631. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  6632. #pragma GCC diagnostic pop /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  6633. #endif
  6634. /*
  6635. Initializes a `ma_context_config` object.
  6636. Return Value
  6637. ------------
  6638. A `ma_context_config` initialized to defaults.
  6639. Remarks
  6640. -------
  6641. You must always use this to initialize the default state of the `ma_context_config` object. Not using this will result in your program breaking when miniaudio
  6642. is updated and new members are added to `ma_context_config`. It also sets logical defaults.
  6643. You can override members of the returned object by changing it's members directly.
  6644. See Also
  6645. --------
  6646. ma_context_init()
  6647. */
  6648. MA_API ma_context_config ma_context_config_init(void);
  6649. /*
  6650. Initializes a context.
  6651. The context is used for selecting and initializing an appropriate backend and to represent the backend at a more global level than that of an individual
  6652. device. There is one context to many devices, and a device is created from a context. A context is required to enumerate devices.
  6653. Parameters
  6654. ----------
  6655. backends (in, optional)
  6656. A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order.
  6657. backendCount (in, optional)
  6658. The number of items in `backend`. Ignored if `backend` is NULL.
  6659. pConfig (in, optional)
  6660. The context configuration.
  6661. pContext (in)
  6662. A pointer to the context object being initialized.
  6663. Return Value
  6664. ------------
  6665. MA_SUCCESS if successful; any other error code otherwise.
  6666. Thread Safety
  6667. -------------
  6668. Unsafe. Do not call this function across multiple threads as some backends read and write to global state.
  6669. Remarks
  6670. -------
  6671. When `backends` is NULL, the default priority order will be used. Below is a list of backends in priority order:
  6672. |-------------|-----------------------|--------------------------------------------------------|
  6673. | Name | Enum Name | Supported Operating Systems |
  6674. |-------------|-----------------------|--------------------------------------------------------|
  6675. | WASAPI | ma_backend_wasapi | Windows Vista+ |
  6676. | DirectSound | ma_backend_dsound | Windows XP+ |
  6677. | WinMM | ma_backend_winmm | Windows XP+ (may work on older versions, but untested) |
  6678. | Core Audio | ma_backend_coreaudio | macOS, iOS |
  6679. | ALSA | ma_backend_alsa | Linux |
  6680. | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
  6681. | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
  6682. | sndio | ma_backend_sndio | OpenBSD |
  6683. | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
  6684. | OSS | ma_backend_oss | FreeBSD |
  6685. | AAudio | ma_backend_aaudio | Android 8+ |
  6686. | OpenSL|ES | ma_backend_opensl | Android (API level 16+) |
  6687. | Web Audio | ma_backend_webaudio | Web (via Emscripten) |
  6688. | Null | ma_backend_null | Cross Platform (not used on Web) |
  6689. |-------------|-----------------------|--------------------------------------------------------|
  6690. The context can be configured via the `pConfig` argument. The config object is initialized with `ma_context_config_init()`. Individual configuration settings
  6691. can then be set directly on the structure. Below are the members of the `ma_context_config` object.
  6692. pLog
  6693. A pointer to the `ma_log` to post log messages to. Can be NULL if the application does not
  6694. require logging. See the `ma_log` API for details on how to use the logging system.
  6695. threadPriority
  6696. The desired priority to use for the audio thread. Allowable values include the following:
  6697. |--------------------------------------|
  6698. | Thread Priority |
  6699. |--------------------------------------|
  6700. | ma_thread_priority_idle |
  6701. | ma_thread_priority_lowest |
  6702. | ma_thread_priority_low |
  6703. | ma_thread_priority_normal |
  6704. | ma_thread_priority_high |
  6705. | ma_thread_priority_highest (default) |
  6706. | ma_thread_priority_realtime |
  6707. | ma_thread_priority_default |
  6708. |--------------------------------------|
  6709. threadStackSize
  6710. The desired size of the stack for the audio thread. Defaults to the operating system's default.
  6711. pUserData
  6712. A pointer to application-defined data. This can be accessed from the context object directly such as `context.pUserData`.
  6713. allocationCallbacks
  6714. Structure containing custom allocation callbacks. Leaving this at defaults will cause it to use MA_MALLOC, MA_REALLOC and MA_FREE. These allocation
  6715. callbacks will be used for anything tied to the context, including devices.
  6716. alsa.useVerboseDeviceEnumeration
  6717. ALSA will typically enumerate many different devices which can be intrusive and not user-friendly. To combat this, miniaudio will enumerate only unique
  6718. card/device pairs by default. The problem with this is that you lose a bit of flexibility and control. Setting alsa.useVerboseDeviceEnumeration makes
  6719. it so the ALSA backend includes all devices. Defaults to false.
  6720. pulse.pApplicationName
  6721. PulseAudio only. The application name to use when initializing the PulseAudio context with `pa_context_new()`.
  6722. pulse.pServerName
  6723. PulseAudio only. The name of the server to connect to with `pa_context_connect()`.
  6724. pulse.tryAutoSpawn
  6725. PulseAudio only. Whether or not to try automatically starting the PulseAudio daemon. Defaults to false. If you set this to true, keep in mind that
  6726. miniaudio uses a trial and error method to find the most appropriate backend, and this will result in the PulseAudio daemon starting which may be
  6727. intrusive for the end user.
  6728. coreaudio.sessionCategory
  6729. iOS only. The session category to use for the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
  6730. |-----------------------------------------|-------------------------------------|
  6731. | miniaudio Token | Core Audio Token |
  6732. |-----------------------------------------|-------------------------------------|
  6733. | ma_ios_session_category_ambient | AVAudioSessionCategoryAmbient |
  6734. | ma_ios_session_category_solo_ambient | AVAudioSessionCategorySoloAmbient |
  6735. | ma_ios_session_category_playback | AVAudioSessionCategoryPlayback |
  6736. | ma_ios_session_category_record | AVAudioSessionCategoryRecord |
  6737. | ma_ios_session_category_play_and_record | AVAudioSessionCategoryPlayAndRecord |
  6738. | ma_ios_session_category_multi_route | AVAudioSessionCategoryMultiRoute |
  6739. | ma_ios_session_category_none | AVAudioSessionCategoryAmbient |
  6740. | ma_ios_session_category_default | AVAudioSessionCategoryAmbient |
  6741. |-----------------------------------------|-------------------------------------|
  6742. coreaudio.sessionCategoryOptions
  6743. iOS only. Session category options to use with the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
  6744. |---------------------------------------------------------------------------|------------------------------------------------------------------|
  6745. | miniaudio Token | Core Audio Token |
  6746. |---------------------------------------------------------------------------|------------------------------------------------------------------|
  6747. | ma_ios_session_category_option_mix_with_others | AVAudioSessionCategoryOptionMixWithOthers |
  6748. | ma_ios_session_category_option_duck_others | AVAudioSessionCategoryOptionDuckOthers |
  6749. | ma_ios_session_category_option_allow_bluetooth | AVAudioSessionCategoryOptionAllowBluetooth |
  6750. | ma_ios_session_category_option_default_to_speaker | AVAudioSessionCategoryOptionDefaultToSpeaker |
  6751. | ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others | AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers |
  6752. | ma_ios_session_category_option_allow_bluetooth_a2dp | AVAudioSessionCategoryOptionAllowBluetoothA2DP |
  6753. | ma_ios_session_category_option_allow_air_play | AVAudioSessionCategoryOptionAllowAirPlay |
  6754. |---------------------------------------------------------------------------|------------------------------------------------------------------|
  6755. coreaudio.noAudioSessionActivate
  6756. iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization.
  6757. coreaudio.noAudioSessionDeactivate
  6758. iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization.
  6759. jack.pClientName
  6760. The name of the client to pass to `jack_client_open()`.
  6761. jack.tryStartServer
  6762. Whether or not to try auto-starting the JACK server. Defaults to false.
  6763. It is recommended that only a single context is active at any given time because it's a bulky data structure which performs run-time linking for the
  6764. relevant backends every time it's initialized.
  6765. The location of the context cannot change throughout it's lifetime. Consider allocating the `ma_context` object with `malloc()` if this is an issue. The
  6766. reason for this is that a pointer to the context is stored in the `ma_device` structure.
  6767. Example 1 - Default Initialization
  6768. ----------------------------------
  6769. The example below shows how to initialize the context using the default configuration.
  6770. ```c
  6771. ma_context context;
  6772. ma_result result = ma_context_init(NULL, 0, NULL, &context);
  6773. if (result != MA_SUCCESS) {
  6774. // Error.
  6775. }
  6776. ```
  6777. Example 2 - Custom Configuration
  6778. --------------------------------
  6779. The example below shows how to initialize the context using custom backend priorities and a custom configuration. In this hypothetical example, the program
  6780. wants to prioritize ALSA over PulseAudio on Linux. They also want to avoid using the WinMM backend on Windows because it's latency is too high. They also
  6781. want an error to be returned if no valid backend is available which they achieve by excluding the Null backend.
  6782. For the configuration, the program wants to capture any log messages so they can, for example, route it to a log file and user interface.
  6783. ```c
  6784. ma_backend backends[] = {
  6785. ma_backend_alsa,
  6786. ma_backend_pulseaudio,
  6787. ma_backend_wasapi,
  6788. ma_backend_dsound
  6789. };
  6790. ma_log log;
  6791. ma_log_init(&log);
  6792. ma_log_register_callback(&log, ma_log_callback_init(my_log_callbac, pMyLogUserData));
  6793. ma_context_config config = ma_context_config_init();
  6794. config.pLog = &log; // Specify a custom log object in the config so any logs that are posted from ma_context_init() are captured.
  6795. ma_context context;
  6796. ma_result result = ma_context_init(backends, sizeof(backends)/sizeof(backends[0]), &config, &context);
  6797. if (result != MA_SUCCESS) {
  6798. // Error.
  6799. if (result == MA_NO_BACKEND) {
  6800. // Couldn't find an appropriate backend.
  6801. }
  6802. }
  6803. // You could also attach a log callback post-initialization:
  6804. ma_log_register_callback(ma_context_get_log(&context), ma_log_callback_init(my_log_callback, pMyLogUserData));
  6805. ```
  6806. See Also
  6807. --------
  6808. ma_context_config_init()
  6809. ma_context_uninit()
  6810. */
  6811. MA_API ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext);
  6812. /*
  6813. Uninitializes a context.
  6814. Return Value
  6815. ------------
  6816. MA_SUCCESS if successful; any other error code otherwise.
  6817. Thread Safety
  6818. -------------
  6819. Unsafe. Do not call this function across multiple threads as some backends read and write to global state.
  6820. Remarks
  6821. -------
  6822. Results are undefined if you call this while any device created by this context is still active.
  6823. See Also
  6824. --------
  6825. ma_context_init()
  6826. */
  6827. MA_API ma_result ma_context_uninit(ma_context* pContext);
  6828. /*
  6829. Retrieves the size of the ma_context object.
  6830. This is mainly for the purpose of bindings to know how much memory to allocate.
  6831. */
  6832. MA_API size_t ma_context_sizeof(void);
  6833. /*
  6834. Retrieves a pointer to the log object associated with this context.
  6835. Remarks
  6836. -------
  6837. Pass the returned pointer to `ma_log_post()`, `ma_log_postv()` or `ma_log_postf()` to post a log
  6838. message.
  6839. You can attach your own logging callback to the log with `ma_log_register_callback()`
  6840. Return Value
  6841. ------------
  6842. A pointer to the `ma_log` object that the context uses to post log messages. If some error occurs,
  6843. NULL will be returned.
  6844. */
  6845. MA_API ma_log* ma_context_get_log(ma_context* pContext);
  6846. /*
  6847. Enumerates over every device (both playback and capture).
  6848. This is a lower-level enumeration function to the easier to use `ma_context_get_devices()`. Use `ma_context_enumerate_devices()` if you would rather not incur
  6849. an internal heap allocation, or it simply suits your code better.
  6850. Note that this only retrieves the ID and name/description of the device. The reason for only retrieving basic information is that it would otherwise require
  6851. opening the backend device in order to probe it for more detailed information which can be inefficient. Consider using `ma_context_get_device_info()` for this,
  6852. but don't call it from within the enumeration callback.
  6853. Returning false from the callback will stop enumeration. Returning true will continue enumeration.
  6854. Parameters
  6855. ----------
  6856. pContext (in)
  6857. A pointer to the context performing the enumeration.
  6858. callback (in)
  6859. The callback to fire for each enumerated device.
  6860. pUserData (in)
  6861. A pointer to application-defined data passed to the callback.
  6862. Return Value
  6863. ------------
  6864. MA_SUCCESS if successful; any other error code otherwise.
  6865. Thread Safety
  6866. -------------
  6867. Safe. This is guarded using a simple mutex lock.
  6868. Remarks
  6869. -------
  6870. Do _not_ assume the first enumerated device of a given type is the default device.
  6871. Some backends and platforms may only support default playback and capture devices.
  6872. In general, you should not do anything complicated from within the callback. In particular, do not try initializing a device from within the callback. Also,
  6873. do not try to call `ma_context_get_device_info()` from within the callback.
  6874. Consider using `ma_context_get_devices()` for a simpler and safer API, albeit at the expense of an internal heap allocation.
  6875. Example 1 - Simple Enumeration
  6876. ------------------------------
  6877. ma_bool32 ma_device_enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData)
  6878. {
  6879. printf("Device Name: %s\n", pInfo->name);
  6880. return MA_TRUE;
  6881. }
  6882. ma_result result = ma_context_enumerate_devices(&context, my_device_enum_callback, pMyUserData);
  6883. if (result != MA_SUCCESS) {
  6884. // Error.
  6885. }
  6886. See Also
  6887. --------
  6888. ma_context_get_devices()
  6889. */
  6890. MA_API ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData);
  6891. /*
  6892. Retrieves basic information about every active playback and/or capture device.
  6893. This function will allocate memory internally for the device lists and return a pointer to them through the `ppPlaybackDeviceInfos` and `ppCaptureDeviceInfos`
  6894. parameters. If you do not want to incur the overhead of these allocations consider using `ma_context_enumerate_devices()` which will instead use a callback.
  6895. Parameters
  6896. ----------
  6897. pContext (in)
  6898. A pointer to the context performing the enumeration.
  6899. ppPlaybackDeviceInfos (out)
  6900. A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for playback devices.
  6901. pPlaybackDeviceCount (out)
  6902. A pointer to an unsigned integer that will receive the number of playback devices.
  6903. ppCaptureDeviceInfos (out)
  6904. A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for capture devices.
  6905. pCaptureDeviceCount (out)
  6906. A pointer to an unsigned integer that will receive the number of capture devices.
  6907. Return Value
  6908. ------------
  6909. MA_SUCCESS if successful; any other error code otherwise.
  6910. Thread Safety
  6911. -------------
  6912. Unsafe. Since each call to this function invalidates the pointers from the previous call, you should not be calling this simultaneously across multiple
  6913. threads. Instead, you need to make a copy of the returned data with your own higher level synchronization.
  6914. Remarks
  6915. -------
  6916. It is _not_ safe to assume the first device in the list is the default device.
  6917. You can pass in NULL for the playback or capture lists in which case they'll be ignored.
  6918. The returned pointers will become invalid upon the next call this this function, or when the context is uninitialized. Do not free the returned pointers.
  6919. See Also
  6920. --------
  6921. ma_context_get_devices()
  6922. */
  6923. MA_API ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlaybackDeviceInfos, ma_uint32* pPlaybackDeviceCount, ma_device_info** ppCaptureDeviceInfos, ma_uint32* pCaptureDeviceCount);
  6924. /*
  6925. Retrieves information about a device of the given type, with the specified ID and share mode.
  6926. Parameters
  6927. ----------
  6928. pContext (in)
  6929. A pointer to the context performing the query.
  6930. deviceType (in)
  6931. The type of the device being queried. Must be either `ma_device_type_playback` or `ma_device_type_capture`.
  6932. pDeviceID (in)
  6933. The ID of the device being queried.
  6934. pDeviceInfo (out)
  6935. A pointer to the `ma_device_info` structure that will receive the device information.
  6936. Return Value
  6937. ------------
  6938. MA_SUCCESS if successful; any other error code otherwise.
  6939. Thread Safety
  6940. -------------
  6941. Safe. This is guarded using a simple mutex lock.
  6942. Remarks
  6943. -------
  6944. Do _not_ call this from within the `ma_context_enumerate_devices()` callback.
  6945. It's possible for a device to have different information and capabilities depending on whether or not it's opened in shared or exclusive mode. For example, in
  6946. shared mode, WASAPI always uses floating point samples for mixing, but in exclusive mode it can be anything. Therefore, this function allows you to specify
  6947. which share mode you want information for. Note that not all backends and devices support shared or exclusive mode, in which case this function will fail if
  6948. the requested share mode is unsupported.
  6949. This leaves pDeviceInfo unmodified in the result of an error.
  6950. */
  6951. MA_API ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo);
  6952. /*
  6953. Determines if the given context supports loopback mode.
  6954. Parameters
  6955. ----------
  6956. pContext (in)
  6957. A pointer to the context getting queried.
  6958. Return Value
  6959. ------------
  6960. MA_TRUE if the context supports loopback mode; MA_FALSE otherwise.
  6961. */
  6962. MA_API ma_bool32 ma_context_is_loopback_supported(ma_context* pContext);
  6963. /*
  6964. Initializes a device config with default settings.
  6965. Parameters
  6966. ----------
  6967. deviceType (in)
  6968. The type of the device this config is being initialized for. This must set to one of the following:
  6969. |-------------------------|
  6970. | Device Type |
  6971. |-------------------------|
  6972. | ma_device_type_playback |
  6973. | ma_device_type_capture |
  6974. | ma_device_type_duplex |
  6975. | ma_device_type_loopback |
  6976. |-------------------------|
  6977. Return Value
  6978. ------------
  6979. A new device config object with default settings. You will typically want to adjust the config after this function returns. See remarks.
  6980. Thread Safety
  6981. -------------
  6982. Safe.
  6983. Callback Safety
  6984. ---------------
  6985. Safe, but don't try initializing a device in a callback.
  6986. Remarks
  6987. -------
  6988. The returned config will be initialized to defaults. You will normally want to customize a few variables before initializing the device. See Example 1 for a
  6989. typical configuration which sets the sample format, channel count, sample rate, data callback and user data. These are usually things you will want to change
  6990. before initializing the device.
  6991. See `ma_device_init()` for details on specific configuration options.
  6992. Example 1 - Simple Configuration
  6993. --------------------------------
  6994. The example below is what a program will typically want to configure for each device at a minimum. Notice how `ma_device_config_init()` is called first, and
  6995. then the returned object is modified directly. This is important because it ensures that your program continues to work as new configuration options are added
  6996. to the `ma_device_config` structure.
  6997. ```c
  6998. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  6999. config.playback.format = ma_format_f32;
  7000. config.playback.channels = 2;
  7001. config.sampleRate = 48000;
  7002. config.dataCallback = ma_data_callback;
  7003. config.pUserData = pMyUserData;
  7004. ```
  7005. See Also
  7006. --------
  7007. ma_device_init()
  7008. ma_device_init_ex()
  7009. */
  7010. MA_API ma_device_config ma_device_config_init(ma_device_type deviceType);
  7011. /*
  7012. Initializes a device.
  7013. A device represents a physical audio device. The idea is you send or receive audio data from the device to either play it back through a speaker, or capture it
  7014. from a microphone. Whether or not you should send or receive data from the device (or both) depends on the type of device you are initializing which can be
  7015. playback, capture, full-duplex or loopback. (Note that loopback mode is only supported on select backends.) Sending and receiving audio data to and from the
  7016. device is done via a callback which is fired by miniaudio at periodic time intervals.
  7017. The frequency at which data is delivered to and from a device depends on the size of it's period. The size of the period can be defined in terms of PCM frames
  7018. or milliseconds, whichever is more convenient. Generally speaking, the smaller the period, the lower the latency at the expense of higher CPU usage and
  7019. increased risk of glitching due to the more frequent and granular data deliver intervals. The size of a period will depend on your requirements, but
  7020. miniaudio's defaults should work fine for most scenarios. If you're building a game you should leave this fairly small, whereas if you're building a simple
  7021. media player you can make it larger. Note that the period size you request is actually just a hint - miniaudio will tell the backend what you want, but the
  7022. backend is ultimately responsible for what it gives you. You cannot assume you will get exactly what you ask for.
  7023. When delivering data to and from a device you need to make sure it's in the correct format which you can set through the device configuration. You just set the
  7024. format that you want to use and miniaudio will perform all of the necessary conversion for you internally. When delivering data to and from the callback you
  7025. can assume the format is the same as what you requested when you initialized the device. See Remarks for more details on miniaudio's data conversion pipeline.
  7026. Parameters
  7027. ----------
  7028. pContext (in, optional)
  7029. A pointer to the context that owns the device. This can be null, in which case it creates a default context internally.
  7030. pConfig (in)
  7031. A pointer to the device configuration. Cannot be null. See remarks for details.
  7032. pDevice (out)
  7033. A pointer to the device object being initialized.
  7034. Return Value
  7035. ------------
  7036. MA_SUCCESS if successful; any other error code otherwise.
  7037. Thread Safety
  7038. -------------
  7039. Unsafe. It is not safe to call this function simultaneously for different devices because some backends depend on and mutate global state. The same applies to
  7040. calling this at the same time as `ma_device_uninit()`.
  7041. Callback Safety
  7042. ---------------
  7043. Unsafe. It is not safe to call this inside any callback.
  7044. Remarks
  7045. -------
  7046. Setting `pContext` to NULL will result in miniaudio creating a default context internally and is equivalent to passing in a context initialized like so:
  7047. ```c
  7048. ma_context_init(NULL, 0, NULL, &context);
  7049. ```
  7050. Do not set `pContext` to NULL if you are needing to open multiple devices. You can, however, use NULL when initializing the first device, and then use
  7051. device.pContext for the initialization of other devices.
  7052. The device can be configured via the `pConfig` argument. The config object is initialized with `ma_device_config_init()`. Individual configuration settings can
  7053. then be set directly on the structure. Below are the members of the `ma_device_config` object.
  7054. deviceType
  7055. Must be `ma_device_type_playback`, `ma_device_type_capture`, `ma_device_type_duplex` of `ma_device_type_loopback`.
  7056. sampleRate
  7057. The sample rate, in hertz. The most common sample rates are 48000 and 44100. Setting this to 0 will use the device's native sample rate.
  7058. periodSizeInFrames
  7059. The desired size of a period in PCM frames. If this is 0, `periodSizeInMilliseconds` will be used instead. If both are 0 the default buffer size will
  7060. be used depending on the selected performance profile. This value affects latency. See below for details.
  7061. periodSizeInMilliseconds
  7062. The desired size of a period in milliseconds. If this is 0, `periodSizeInFrames` will be used instead. If both are 0 the default buffer size will be
  7063. used depending on the selected performance profile. The value affects latency. See below for details.
  7064. periods
  7065. The number of periods making up the device's entire buffer. The total buffer size is `periodSizeInFrames` or `periodSizeInMilliseconds` multiplied by
  7066. this value. This is just a hint as backends will be the ones who ultimately decide how your periods will be configured.
  7067. performanceProfile
  7068. A hint to miniaudio as to the performance requirements of your program. Can be either `ma_performance_profile_low_latency` (default) or
  7069. `ma_performance_profile_conservative`. This mainly affects the size of default buffers and can usually be left at it's default value.
  7070. noPreSilencedOutputBuffer
  7071. When set to true, the contents of the output buffer passed into the data callback will be left undefined. When set to false (default), the contents of
  7072. the output buffer will be cleared the zero. You can use this to avoid the overhead of zeroing out the buffer if you can guarantee that your data
  7073. callback will write to every sample in the output buffer, or if you are doing your own clearing.
  7074. noClip
  7075. When set to true, the contents of the output buffer passed into the data callback will be clipped after returning. When set to false (default), the
  7076. contents of the output buffer are left alone after returning and it will be left up to the backend itself to decide whether or not the clip. This only
  7077. applies when the playback sample format is f32.
  7078. noDisableDenormals
  7079. By default, miniaudio will disable denormals when the data callback is called. Setting this to true will prevent the disabling of denormals.
  7080. noFixedSizedCallback
  7081. Allows miniaudio to fire the data callback with any frame count. When this is set to false (the default), the data callback will be fired with a
  7082. consistent frame count as specified by `periodSizeInFrames` or `periodSizeInMilliseconds`. When set to true, miniaudio will fire the callback with
  7083. whatever the backend requests, which could be anything.
  7084. dataCallback
  7085. The callback to fire whenever data is ready to be delivered to or from the device.
  7086. notificationCallback
  7087. The callback to fire when something has changed with the device, such as whether or not it has been started or stopped.
  7088. pUserData
  7089. The user data pointer to use with the device. You can access this directly from the device object like `device.pUserData`.
  7090. resampling.algorithm
  7091. The resampling algorithm to use when miniaudio needs to perform resampling between the rate specified by `sampleRate` and the device's native rate. The
  7092. default value is `ma_resample_algorithm_linear`, and the quality can be configured with `resampling.linear.lpfOrder`.
  7093. resampling.pBackendVTable
  7094. A pointer to an optional vtable that can be used for plugging in a custom resampler.
  7095. resampling.pBackendUserData
  7096. A pointer that will passed to callbacks in pBackendVTable.
  7097. resampling.linear.lpfOrder
  7098. The linear resampler applies a low-pass filter as part of it's processing for anti-aliasing. This setting controls the order of the filter. The higher
  7099. the value, the better the quality, in general. Setting this to 0 will disable low-pass filtering altogether. The maximum value is
  7100. `MA_MAX_FILTER_ORDER`. The default value is `min(4, MA_MAX_FILTER_ORDER)`.
  7101. playback.pDeviceID
  7102. A pointer to a `ma_device_id` structure containing the ID of the playback device to initialize. Setting this NULL (default) will use the system's
  7103. default playback device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration.
  7104. playback.format
  7105. The sample format to use for playback. When set to `ma_format_unknown` the device's native format will be used. This can be retrieved after
  7106. initialization from the device object directly with `device.playback.format`.
  7107. playback.channels
  7108. The number of channels to use for playback. When set to 0 the device's native channel count will be used. This can be retrieved after initialization
  7109. from the device object directly with `device.playback.channels`.
  7110. playback.pChannelMap
  7111. The channel map to use for playback. When left empty, the device's native channel map will be used. This can be retrieved after initialization from the
  7112. device object direct with `device.playback.pChannelMap`. When set, the buffer should contain `channels` items.
  7113. playback.shareMode
  7114. The preferred share mode to use for playback. Can be either `ma_share_mode_shared` (default) or `ma_share_mode_exclusive`. Note that if you specify
  7115. exclusive mode, but it's not supported by the backend, initialization will fail. You can then fall back to shared mode if desired by changing this to
  7116. ma_share_mode_shared and reinitializing.
  7117. capture.pDeviceID
  7118. A pointer to a `ma_device_id` structure containing the ID of the capture device to initialize. Setting this NULL (default) will use the system's
  7119. default capture device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration.
  7120. capture.format
  7121. The sample format to use for capture. When set to `ma_format_unknown` the device's native format will be used. This can be retrieved after
  7122. initialization from the device object directly with `device.capture.format`.
  7123. capture.channels
  7124. The number of channels to use for capture. When set to 0 the device's native channel count will be used. This can be retrieved after initialization
  7125. from the device object directly with `device.capture.channels`.
  7126. capture.pChannelMap
  7127. The channel map to use for capture. When left empty, the device's native channel map will be used. This can be retrieved after initialization from the
  7128. device object direct with `device.capture.pChannelMap`. When set, the buffer should contain `channels` items.
  7129. capture.shareMode
  7130. The preferred share mode to use for capture. Can be either `ma_share_mode_shared` (default) or `ma_share_mode_exclusive`. Note that if you specify
  7131. exclusive mode, but it's not supported by the backend, initialization will fail. You can then fall back to shared mode if desired by changing this to
  7132. ma_share_mode_shared and reinitializing.
  7133. wasapi.noAutoConvertSRC
  7134. WASAPI only. When set to true, disables WASAPI's automatic resampling and forces the use of miniaudio's resampler. Defaults to false.
  7135. wasapi.noDefaultQualitySRC
  7136. WASAPI only. Only used when `wasapi.noAutoConvertSRC` is set to false. When set to true, disables the use of `AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY`.
  7137. You should usually leave this set to false, which is the default.
  7138. wasapi.noAutoStreamRouting
  7139. WASAPI only. When set to true, disables automatic stream routing on the WASAPI backend. Defaults to false.
  7140. wasapi.noHardwareOffloading
  7141. WASAPI only. When set to true, disables the use of WASAPI's hardware offloading feature. Defaults to false.
  7142. alsa.noMMap
  7143. ALSA only. When set to true, disables MMap mode. Defaults to false.
  7144. alsa.noAutoFormat
  7145. ALSA only. When set to true, disables ALSA's automatic format conversion by including the SND_PCM_NO_AUTO_FORMAT flag. Defaults to false.
  7146. alsa.noAutoChannels
  7147. ALSA only. When set to true, disables ALSA's automatic channel conversion by including the SND_PCM_NO_AUTO_CHANNELS flag. Defaults to false.
  7148. alsa.noAutoResample
  7149. ALSA only. When set to true, disables ALSA's automatic resampling by including the SND_PCM_NO_AUTO_RESAMPLE flag. Defaults to false.
  7150. pulse.pStreamNamePlayback
  7151. PulseAudio only. Sets the stream name for playback.
  7152. pulse.pStreamNameCapture
  7153. PulseAudio only. Sets the stream name for capture.
  7154. coreaudio.allowNominalSampleRateChange
  7155. Core Audio only. Desktop only. When enabled, allows the sample rate of the device to be changed at the operating system level. This
  7156. is disabled by default in order to prevent intrusive changes to the user's system. This is useful if you want to use a sample rate
  7157. that is known to be natively supported by the hardware thereby avoiding the cost of resampling. When set to true, miniaudio will
  7158. find the closest match between the sample rate requested in the device config and the sample rates natively supported by the
  7159. hardware. When set to false, the sample rate currently set by the operating system will always be used.
  7160. opensl.streamType
  7161. OpenSL only. Explicitly sets the stream type. If left unset (`ma_opensl_stream_type_default`), the
  7162. stream type will be left unset. Think of this as the type of audio you're playing.
  7163. opensl.recordingPreset
  7164. OpenSL only. Explicitly sets the type of recording your program will be doing. When left
  7165. unset, the recording preset will be left unchanged.
  7166. aaudio.usage
  7167. AAudio only. Explicitly sets the nature of the audio the program will be consuming. When
  7168. left unset, the usage will be left unchanged.
  7169. aaudio.contentType
  7170. AAudio only. Sets the content type. When left unset, the content type will be left unchanged.
  7171. aaudio.inputPreset
  7172. AAudio only. Explicitly sets the type of recording your program will be doing. When left
  7173. unset, the input preset will be left unchanged.
  7174. aaudio.noAutoStartAfterReroute
  7175. AAudio only. Controls whether or not the device should be automatically restarted after a
  7176. stream reroute. When set to false (default) the device will be restarted automatically;
  7177. otherwise the device will be stopped.
  7178. Once initialized, the device's config is immutable. If you need to change the config you will need to initialize a new device.
  7179. After initializing the device it will be in a stopped state. To start it, use `ma_device_start()`.
  7180. If both `periodSizeInFrames` and `periodSizeInMilliseconds` are set to zero, it will default to `MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY` or
  7181. `MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE`, depending on whether or not `performanceProfile` is set to `ma_performance_profile_low_latency` or
  7182. `ma_performance_profile_conservative`.
  7183. If you request exclusive mode and the backend does not support it an error will be returned. For robustness, you may want to first try initializing the device
  7184. in exclusive mode, and then fall back to shared mode if required. Alternatively you can just request shared mode (the default if you leave it unset in the
  7185. config) which is the most reliable option. Some backends do not have a practical way of choosing whether or not the device should be exclusive or not (ALSA,
  7186. for example) in which case it just acts as a hint. Unless you have special requirements you should try avoiding exclusive mode as it's intrusive to the user.
  7187. Starting with Windows 10, miniaudio will use low-latency shared mode where possible which may make exclusive mode unnecessary.
  7188. When sending or receiving data to/from a device, miniaudio will internally perform a format conversion to convert between the format specified by the config
  7189. and the format used internally by the backend. If you pass in 0 for the sample format, channel count, sample rate _and_ channel map, data transmission will run
  7190. on an optimized pass-through fast path. You can retrieve the format, channel count and sample rate by inspecting the `playback/capture.format`,
  7191. `playback/capture.channels` and `sampleRate` members of the device object.
  7192. When compiling for UWP you must ensure you call this function on the main UI thread because the operating system may need to present the user with a message
  7193. asking for permissions. Please refer to the official documentation for ActivateAudioInterfaceAsync() for more information.
  7194. ALSA Specific: When initializing the default device, requesting shared mode will try using the "dmix" device for playback and the "dsnoop" device for capture.
  7195. If these fail it will try falling back to the "hw" device.
  7196. Example 1 - Simple Initialization
  7197. ---------------------------------
  7198. This example shows how to initialize a simple playback device using a standard configuration. If you are just needing to do simple playback from the default
  7199. playback device this is usually all you need.
  7200. ```c
  7201. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  7202. config.playback.format = ma_format_f32;
  7203. config.playback.channels = 2;
  7204. config.sampleRate = 48000;
  7205. config.dataCallback = ma_data_callback;
  7206. config.pMyUserData = pMyUserData;
  7207. ma_device device;
  7208. ma_result result = ma_device_init(NULL, &config, &device);
  7209. if (result != MA_SUCCESS) {
  7210. // Error
  7211. }
  7212. ```
  7213. Example 2 - Advanced Initialization
  7214. -----------------------------------
  7215. This example shows how you might do some more advanced initialization. In this hypothetical example we want to control the latency by setting the buffer size
  7216. and period count. We also want to allow the user to be able to choose which device to output from which means we need a context so we can perform device
  7217. enumeration.
  7218. ```c
  7219. ma_context context;
  7220. ma_result result = ma_context_init(NULL, 0, NULL, &context);
  7221. if (result != MA_SUCCESS) {
  7222. // Error
  7223. }
  7224. ma_device_info* pPlaybackDeviceInfos;
  7225. ma_uint32 playbackDeviceCount;
  7226. result = ma_context_get_devices(&context, &pPlaybackDeviceInfos, &playbackDeviceCount, NULL, NULL);
  7227. if (result != MA_SUCCESS) {
  7228. // Error
  7229. }
  7230. // ... choose a device from pPlaybackDeviceInfos ...
  7231. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  7232. config.playback.pDeviceID = pMyChosenDeviceID; // <-- Get this from the `id` member of one of the `ma_device_info` objects returned by ma_context_get_devices().
  7233. config.playback.format = ma_format_f32;
  7234. config.playback.channels = 2;
  7235. config.sampleRate = 48000;
  7236. config.dataCallback = ma_data_callback;
  7237. config.pUserData = pMyUserData;
  7238. config.periodSizeInMilliseconds = 10;
  7239. config.periods = 3;
  7240. ma_device device;
  7241. result = ma_device_init(&context, &config, &device);
  7242. if (result != MA_SUCCESS) {
  7243. // Error
  7244. }
  7245. ```
  7246. See Also
  7247. --------
  7248. ma_device_config_init()
  7249. ma_device_uninit()
  7250. ma_device_start()
  7251. ma_context_init()
  7252. ma_context_get_devices()
  7253. ma_context_enumerate_devices()
  7254. */
  7255. MA_API ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice);
  7256. /*
  7257. Initializes a device without a context, with extra parameters for controlling the configuration of the internal self-managed context.
  7258. This is the same as `ma_device_init()`, only instead of a context being passed in, the parameters from `ma_context_init()` are passed in instead. This function
  7259. allows you to configure the internally created context.
  7260. Parameters
  7261. ----------
  7262. backends (in, optional)
  7263. A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order.
  7264. backendCount (in, optional)
  7265. The number of items in `backend`. Ignored if `backend` is NULL.
  7266. pContextConfig (in, optional)
  7267. The context configuration.
  7268. pConfig (in)
  7269. A pointer to the device configuration. Cannot be null. See remarks for details.
  7270. pDevice (out)
  7271. A pointer to the device object being initialized.
  7272. Return Value
  7273. ------------
  7274. MA_SUCCESS if successful; any other error code otherwise.
  7275. Thread Safety
  7276. -------------
  7277. Unsafe. It is not safe to call this function simultaneously for different devices because some backends depend on and mutate global state. The same applies to
  7278. calling this at the same time as `ma_device_uninit()`.
  7279. Callback Safety
  7280. ---------------
  7281. Unsafe. It is not safe to call this inside any callback.
  7282. Remarks
  7283. -------
  7284. You only need to use this function if you want to configure the context differently to it's defaults. You should never use this function if you want to manage
  7285. your own context.
  7286. See the documentation for `ma_context_init()` for information on the different context configuration options.
  7287. See Also
  7288. --------
  7289. ma_device_init()
  7290. ma_device_uninit()
  7291. ma_device_config_init()
  7292. ma_context_init()
  7293. */
  7294. MA_API ma_result ma_device_init_ex(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pContextConfig, const ma_device_config* pConfig, ma_device* pDevice);
  7295. /*
  7296. Uninitializes a device.
  7297. This will explicitly stop the device. You do not need to call `ma_device_stop()` beforehand, but it's harmless if you do.
  7298. Parameters
  7299. ----------
  7300. pDevice (in)
  7301. A pointer to the device to stop.
  7302. Return Value
  7303. ------------
  7304. Nothing
  7305. Thread Safety
  7306. -------------
  7307. Unsafe. As soon as this API is called the device should be considered undefined.
  7308. Callback Safety
  7309. ---------------
  7310. Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
  7311. See Also
  7312. --------
  7313. ma_device_init()
  7314. ma_device_stop()
  7315. */
  7316. MA_API void ma_device_uninit(ma_device* pDevice);
  7317. /*
  7318. Retrieves a pointer to the context that owns the given device.
  7319. */
  7320. MA_API ma_context* ma_device_get_context(ma_device* pDevice);
  7321. /*
  7322. Helper function for retrieving the log object associated with the context that owns this device.
  7323. */
  7324. MA_API ma_log* ma_device_get_log(ma_device* pDevice);
  7325. /*
  7326. Retrieves information about the device.
  7327. Parameters
  7328. ----------
  7329. pDevice (in)
  7330. A pointer to the device whose information is being retrieved.
  7331. type (in)
  7332. The device type. This parameter is required for duplex devices. When retrieving device
  7333. information, you are doing so for an individual playback or capture device.
  7334. pDeviceInfo (out)
  7335. A pointer to the `ma_device_info` that will receive the device information.
  7336. Return Value
  7337. ------------
  7338. MA_SUCCESS if successful; any other error code otherwise.
  7339. Thread Safety
  7340. -------------
  7341. Unsafe. This should be considered unsafe because it may be calling into the backend which may or
  7342. may not be safe.
  7343. Callback Safety
  7344. ---------------
  7345. Unsafe. You should avoid calling this in the data callback because it may call into the backend
  7346. which may or may not be safe.
  7347. */
  7348. MA_API ma_result ma_device_get_info(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo);
  7349. /*
  7350. Retrieves the name of the device.
  7351. Parameters
  7352. ----------
  7353. pDevice (in)
  7354. A pointer to the device whose information is being retrieved.
  7355. type (in)
  7356. The device type. This parameter is required for duplex devices. When retrieving device
  7357. information, you are doing so for an individual playback or capture device.
  7358. pName (out)
  7359. A pointer to the buffer that will receive the name.
  7360. nameCap (in)
  7361. The capacity of the output buffer, including space for the null terminator.
  7362. pLengthNotIncludingNullTerminator (out, optional)
  7363. A pointer to the variable that will receive the length of the name, not including the null
  7364. terminator.
  7365. Return Value
  7366. ------------
  7367. MA_SUCCESS if successful; any other error code otherwise.
  7368. Thread Safety
  7369. -------------
  7370. Unsafe. This should be considered unsafe because it may be calling into the backend which may or
  7371. may not be safe.
  7372. Callback Safety
  7373. ---------------
  7374. Unsafe. You should avoid calling this in the data callback because it may call into the backend
  7375. which may or may not be safe.
  7376. Remarks
  7377. -------
  7378. If the name does not fully fit into the output buffer, it'll be truncated. You can pass in NULL to
  7379. `pName` if you want to first get the length of the name for the purpose of memory allocation of the
  7380. output buffer. Allocating a buffer of size `MA_MAX_DEVICE_NAME_LENGTH + 1` should be enough for
  7381. most cases and will avoid the need for the inefficiency of calling this function twice.
  7382. This is implemented in terms of `ma_device_get_info()`.
  7383. */
  7384. MA_API ma_result ma_device_get_name(ma_device* pDevice, ma_device_type type, char* pName, size_t nameCap, size_t* pLengthNotIncludingNullTerminator);
  7385. /*
  7386. Starts the device. For playback devices this begins playback. For capture devices it begins recording.
  7387. Use `ma_device_stop()` to stop the device.
  7388. Parameters
  7389. ----------
  7390. pDevice (in)
  7391. A pointer to the device to start.
  7392. Return Value
  7393. ------------
  7394. MA_SUCCESS if successful; any other error code otherwise.
  7395. Thread Safety
  7396. -------------
  7397. Safe. It's safe to call this from any thread with the exception of the callback thread.
  7398. Callback Safety
  7399. ---------------
  7400. Unsafe. It is not safe to call this inside any callback.
  7401. Remarks
  7402. -------
  7403. For a playback device, this will retrieve an initial chunk of audio data from the client before returning. The reason for this is to ensure there is valid
  7404. audio data in the buffer, which needs to be done before the device begins playback.
  7405. This API waits until the backend device has been started for real by the worker thread. It also waits on a mutex for thread-safety.
  7406. Do not call this in any callback.
  7407. See Also
  7408. --------
  7409. ma_device_stop()
  7410. */
  7411. MA_API ma_result ma_device_start(ma_device* pDevice);
  7412. /*
  7413. Stops the device. For playback devices this stops playback. For capture devices it stops recording.
  7414. Use `ma_device_start()` to start the device again.
  7415. Parameters
  7416. ----------
  7417. pDevice (in)
  7418. A pointer to the device to stop.
  7419. Return Value
  7420. ------------
  7421. MA_SUCCESS if successful; any other error code otherwise.
  7422. Thread Safety
  7423. -------------
  7424. Safe. It's safe to call this from any thread with the exception of the callback thread.
  7425. Callback Safety
  7426. ---------------
  7427. Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
  7428. Remarks
  7429. -------
  7430. This API needs to wait on the worker thread to stop the backend device properly before returning. It also waits on a mutex for thread-safety. In addition, some
  7431. backends need to wait for the device to finish playback/recording of the current fragment which can take some time (usually proportionate to the buffer size
  7432. that was specified at initialization time).
  7433. Backends are required to either pause the stream in-place or drain the buffer if pausing is not possible. The reason for this is that stopping the device and
  7434. the resuming it with ma_device_start() (which you might do when your program loses focus) may result in a situation where those samples are never output to the
  7435. speakers or received from the microphone which can in turn result in de-syncs.
  7436. Do not call this in any callback.
  7437. This will be called implicitly by `ma_device_uninit()`.
  7438. See Also
  7439. --------
  7440. ma_device_start()
  7441. */
  7442. MA_API ma_result ma_device_stop(ma_device* pDevice);
  7443. /*
  7444. Determines whether or not the device is started.
  7445. Parameters
  7446. ----------
  7447. pDevice (in)
  7448. A pointer to the device whose start state is being retrieved.
  7449. Return Value
  7450. ------------
  7451. True if the device is started, false otherwise.
  7452. Thread Safety
  7453. -------------
  7454. Safe. If another thread calls `ma_device_start()` or `ma_device_stop()` at this same time as this function is called, there's a very small chance the return
  7455. value will be out of sync.
  7456. Callback Safety
  7457. ---------------
  7458. Safe. This is implemented as a simple accessor.
  7459. See Also
  7460. --------
  7461. ma_device_start()
  7462. ma_device_stop()
  7463. */
  7464. MA_API ma_bool32 ma_device_is_started(const ma_device* pDevice);
  7465. /*
  7466. Retrieves the state of the device.
  7467. Parameters
  7468. ----------
  7469. pDevice (in)
  7470. A pointer to the device whose state is being retrieved.
  7471. Return Value
  7472. ------------
  7473. The current state of the device. The return value will be one of the following:
  7474. +-------------------------------+------------------------------------------------------------------------------+
  7475. | ma_device_state_uninitialized | Will only be returned if the device is in the middle of initialization. |
  7476. +-------------------------------+------------------------------------------------------------------------------+
  7477. | ma_device_state_stopped | The device is stopped. The initial state of the device after initialization. |
  7478. +-------------------------------+------------------------------------------------------------------------------+
  7479. | ma_device_state_started | The device started and requesting and/or delivering audio data. |
  7480. +-------------------------------+------------------------------------------------------------------------------+
  7481. | ma_device_state_starting | The device is in the process of starting. |
  7482. +-------------------------------+------------------------------------------------------------------------------+
  7483. | ma_device_state_stopping | The device is in the process of stopping. |
  7484. +-------------------------------+------------------------------------------------------------------------------+
  7485. Thread Safety
  7486. -------------
  7487. Safe. This is implemented as a simple accessor. Note that if the device is started or stopped at the same time as this function is called,
  7488. there's a possibility the return value could be out of sync. See remarks.
  7489. Callback Safety
  7490. ---------------
  7491. Safe. This is implemented as a simple accessor.
  7492. Remarks
  7493. -------
  7494. The general flow of a devices state goes like this:
  7495. ```
  7496. ma_device_init() -> ma_device_state_uninitialized -> ma_device_state_stopped
  7497. ma_device_start() -> ma_device_state_starting -> ma_device_state_started
  7498. ma_device_stop() -> ma_device_state_stopping -> ma_device_state_stopped
  7499. ```
  7500. When the state of the device is changed with `ma_device_start()` or `ma_device_stop()` at this same time as this function is called, the
  7501. value returned by this function could potentially be out of sync. If this is significant to your program you need to implement your own
  7502. synchronization.
  7503. */
  7504. MA_API ma_device_state ma_device_get_state(const ma_device* pDevice);
  7505. /*
  7506. Performs post backend initialization routines for setting up internal data conversion.
  7507. This should be called whenever the backend is initialized. The only time this should be called from
  7508. outside of miniaudio is if you're implementing a custom backend, and you would only do it if you
  7509. are reinitializing the backend due to rerouting or reinitializing for some reason.
  7510. Parameters
  7511. ----------
  7512. pDevice [in]
  7513. A pointer to the device.
  7514. deviceType [in]
  7515. The type of the device that was just reinitialized.
  7516. pPlaybackDescriptor [in]
  7517. The descriptor of the playback device containing the internal data format and buffer sizes.
  7518. pPlaybackDescriptor [in]
  7519. The descriptor of the capture device containing the internal data format and buffer sizes.
  7520. Return Value
  7521. ------------
  7522. MA_SUCCESS if successful; any other error otherwise.
  7523. Thread Safety
  7524. -------------
  7525. Unsafe. This will be reinitializing internal data converters which may be in use by another thread.
  7526. Callback Safety
  7527. ---------------
  7528. Unsafe. This will be reinitializing internal data converters which may be in use by the callback.
  7529. Remarks
  7530. -------
  7531. For a duplex device, you can call this for only one side of the system. This is why the deviceType
  7532. is specified as a parameter rather than deriving it from the device.
  7533. You do not need to call this manually unless you are doing a custom backend, in which case you need
  7534. only do it if you're manually performing rerouting or reinitialization.
  7535. */
  7536. MA_API ma_result ma_device_post_init(ma_device* pDevice, ma_device_type deviceType, const ma_device_descriptor* pPlaybackDescriptor, const ma_device_descriptor* pCaptureDescriptor);
  7537. /*
  7538. Sets the master volume factor for the device.
  7539. The volume factor must be between 0 (silence) and 1 (full volume). Use `ma_device_set_master_volume_db()` to use decibel notation, where 0 is full volume and
  7540. values less than 0 decreases the volume.
  7541. Parameters
  7542. ----------
  7543. pDevice (in)
  7544. A pointer to the device whose volume is being set.
  7545. volume (in)
  7546. The new volume factor. Must be >= 0.
  7547. Return Value
  7548. ------------
  7549. MA_SUCCESS if the volume was set successfully.
  7550. MA_INVALID_ARGS if pDevice is NULL.
  7551. MA_INVALID_ARGS if volume is negative.
  7552. Thread Safety
  7553. -------------
  7554. Safe. This just sets a local member of the device object.
  7555. Callback Safety
  7556. ---------------
  7557. Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied.
  7558. Remarks
  7559. -------
  7560. This applies the volume factor across all channels.
  7561. This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream.
  7562. See Also
  7563. --------
  7564. ma_device_get_master_volume()
  7565. ma_device_set_master_volume_db()
  7566. ma_device_get_master_volume_db()
  7567. */
  7568. MA_API ma_result ma_device_set_master_volume(ma_device* pDevice, float volume);
  7569. /*
  7570. Retrieves the master volume factor for the device.
  7571. Parameters
  7572. ----------
  7573. pDevice (in)
  7574. A pointer to the device whose volume factor is being retrieved.
  7575. pVolume (in)
  7576. A pointer to the variable that will receive the volume factor. The returned value will be in the range of [0, 1].
  7577. Return Value
  7578. ------------
  7579. MA_SUCCESS if successful.
  7580. MA_INVALID_ARGS if pDevice is NULL.
  7581. MA_INVALID_ARGS if pVolume is NULL.
  7582. Thread Safety
  7583. -------------
  7584. Safe. This just a simple member retrieval.
  7585. Callback Safety
  7586. ---------------
  7587. Safe.
  7588. Remarks
  7589. -------
  7590. If an error occurs, `*pVolume` will be set to 0.
  7591. See Also
  7592. --------
  7593. ma_device_set_master_volume()
  7594. ma_device_set_master_volume_gain_db()
  7595. ma_device_get_master_volume_gain_db()
  7596. */
  7597. MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume);
  7598. /*
  7599. Sets the master volume for the device as gain in decibels.
  7600. A gain of 0 is full volume, whereas a gain of < 0 will decrease the volume.
  7601. Parameters
  7602. ----------
  7603. pDevice (in)
  7604. A pointer to the device whose gain is being set.
  7605. gainDB (in)
  7606. The new volume as gain in decibels. Must be less than or equal to 0, where 0 is full volume and anything less than 0 decreases the volume.
  7607. Return Value
  7608. ------------
  7609. MA_SUCCESS if the volume was set successfully.
  7610. MA_INVALID_ARGS if pDevice is NULL.
  7611. MA_INVALID_ARGS if the gain is > 0.
  7612. Thread Safety
  7613. -------------
  7614. Safe. This just sets a local member of the device object.
  7615. Callback Safety
  7616. ---------------
  7617. Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied.
  7618. Remarks
  7619. -------
  7620. This applies the gain across all channels.
  7621. This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream.
  7622. See Also
  7623. --------
  7624. ma_device_get_master_volume_gain_db()
  7625. ma_device_set_master_volume()
  7626. ma_device_get_master_volume()
  7627. */
  7628. MA_API ma_result ma_device_set_master_volume_db(ma_device* pDevice, float gainDB);
  7629. /*
  7630. Retrieves the master gain in decibels.
  7631. Parameters
  7632. ----------
  7633. pDevice (in)
  7634. A pointer to the device whose gain is being retrieved.
  7635. pGainDB (in)
  7636. A pointer to the variable that will receive the gain in decibels. The returned value will be <= 0.
  7637. Return Value
  7638. ------------
  7639. MA_SUCCESS if successful.
  7640. MA_INVALID_ARGS if pDevice is NULL.
  7641. MA_INVALID_ARGS if pGainDB is NULL.
  7642. Thread Safety
  7643. -------------
  7644. Safe. This just a simple member retrieval.
  7645. Callback Safety
  7646. ---------------
  7647. Safe.
  7648. Remarks
  7649. -------
  7650. If an error occurs, `*pGainDB` will be set to 0.
  7651. See Also
  7652. --------
  7653. ma_device_set_master_volume_db()
  7654. ma_device_set_master_volume()
  7655. ma_device_get_master_volume()
  7656. */
  7657. MA_API ma_result ma_device_get_master_volume_db(ma_device* pDevice, float* pGainDB);
  7658. /*
  7659. Called from the data callback of asynchronous backends to allow miniaudio to process the data and fire the miniaudio data callback.
  7660. Parameters
  7661. ----------
  7662. pDevice (in)
  7663. A pointer to device whose processing the data callback.
  7664. pOutput (out)
  7665. A pointer to the buffer that will receive the output PCM frame data. On a playback device this must not be NULL. On a duplex device
  7666. this can be NULL, in which case pInput must not be NULL.
  7667. pInput (in)
  7668. A pointer to the buffer containing input PCM frame data. On a capture device this must not be NULL. On a duplex device this can be
  7669. NULL, in which case `pOutput` must not be NULL.
  7670. frameCount (in)
  7671. The number of frames being processed.
  7672. Return Value
  7673. ------------
  7674. MA_SUCCESS if successful; any other result code otherwise.
  7675. Thread Safety
  7676. -------------
  7677. This function should only ever be called from the internal data callback of the backend. It is safe to call this simultaneously between a
  7678. playback and capture device in duplex setups.
  7679. Callback Safety
  7680. ---------------
  7681. Do not call this from the miniaudio data callback. It should only ever be called from the internal data callback of the backend.
  7682. Remarks
  7683. -------
  7684. If both `pOutput` and `pInput` are NULL, and error will be returned. In duplex scenarios, both `pOutput` and `pInput` can be non-NULL, in
  7685. which case `pInput` will be processed first, followed by `pOutput`.
  7686. If you are implementing a custom backend, and that backend uses a callback for data delivery, you'll need to call this from inside that
  7687. callback.
  7688. */
  7689. MA_API ma_result ma_device_handle_backend_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
  7690. /*
  7691. Calculates an appropriate buffer size from a descriptor, native sample rate and performance profile.
  7692. This function is used by backends for helping determine an appropriately sized buffer to use with
  7693. the device depending on the values of `periodSizeInFrames` and `periodSizeInMilliseconds` in the
  7694. `pDescriptor` object. Since buffer size calculations based on time depends on the sample rate, a
  7695. best guess at the device's native sample rate is also required which is where `nativeSampleRate`
  7696. comes in. In addition, the performance profile is also needed for cases where both the period size
  7697. in frames and milliseconds are both zero.
  7698. Parameters
  7699. ----------
  7700. pDescriptor (in)
  7701. A pointer to device descriptor whose `periodSizeInFrames` and `periodSizeInMilliseconds` members
  7702. will be used for the calculation of the buffer size.
  7703. nativeSampleRate (in)
  7704. The device's native sample rate. This is only ever used when the `periodSizeInFrames` member of
  7705. `pDescriptor` is zero. In this case, `periodSizeInMilliseconds` will be used instead, in which
  7706. case a sample rate is required to convert to a size in frames.
  7707. performanceProfile (in)
  7708. When both the `periodSizeInFrames` and `periodSizeInMilliseconds` members of `pDescriptor` are
  7709. zero, miniaudio will fall back to a buffer size based on the performance profile. The profile
  7710. to use for this calculation is determine by this parameter.
  7711. Return Value
  7712. ------------
  7713. The calculated buffer size in frames.
  7714. Thread Safety
  7715. -------------
  7716. This is safe so long as nothing modifies `pDescriptor` at the same time. However, this function
  7717. should only ever be called from within the backend's device initialization routine and therefore
  7718. shouldn't have any multithreading concerns.
  7719. Callback Safety
  7720. ---------------
  7721. This is safe to call within the data callback, but there is no reason to ever do this.
  7722. Remarks
  7723. -------
  7724. If `nativeSampleRate` is zero, this function will fall back to `pDescriptor->sampleRate`. If that
  7725. is also zero, `MA_DEFAULT_SAMPLE_RATE` will be used instead.
  7726. */
  7727. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_descriptor(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile);
  7728. /*
  7729. Retrieves a friendly name for a backend.
  7730. */
  7731. MA_API const char* ma_get_backend_name(ma_backend backend);
  7732. /*
  7733. Retrieves the backend enum from the given name.
  7734. */
  7735. MA_API ma_result ma_get_backend_from_name(const char* pBackendName, ma_backend* pBackend);
  7736. /*
  7737. Determines whether or not the given backend is available by the compilation environment.
  7738. */
  7739. MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend);
  7740. /*
  7741. Retrieves compile-time enabled backends.
  7742. Parameters
  7743. ----------
  7744. pBackends (out, optional)
  7745. A pointer to the buffer that will receive the enabled backends. Set to NULL to retrieve the backend count. Setting
  7746. the capacity of the buffer to `MA_BUFFER_COUNT` will guarantee it's large enough for all backends.
  7747. backendCap (in)
  7748. The capacity of the `pBackends` buffer.
  7749. pBackendCount (out)
  7750. A pointer to the variable that will receive the enabled backend count.
  7751. Return Value
  7752. ------------
  7753. MA_SUCCESS if successful.
  7754. MA_INVALID_ARGS if `pBackendCount` is NULL.
  7755. MA_NO_SPACE if the capacity of `pBackends` is not large enough.
  7756. If `MA_NO_SPACE` is returned, the `pBackends` buffer will be filled with `*pBackendCount` values.
  7757. Thread Safety
  7758. -------------
  7759. Safe.
  7760. Callback Safety
  7761. ---------------
  7762. Safe.
  7763. Remarks
  7764. -------
  7765. If you want to retrieve the number of backends so you can determine the capacity of `pBackends` buffer, you can call
  7766. this function with `pBackends` set to NULL.
  7767. This will also enumerate the null backend. If you don't want to include this you need to check for `ma_backend_null`
  7768. when you enumerate over the returned backends and handle it appropriately. Alternatively, you can disable it at
  7769. compile time with `MA_NO_NULL`.
  7770. The returned backends are determined based on compile time settings, not the platform it's currently running on. For
  7771. example, PulseAudio will be returned if it was enabled at compile time, even when the user doesn't actually have
  7772. PulseAudio installed.
  7773. Example 1
  7774. ---------
  7775. The example below retrieves the enabled backend count using a fixed sized buffer allocated on the stack. The buffer is
  7776. given a capacity of `MA_BACKEND_COUNT` which will guarantee it'll be large enough to store all available backends.
  7777. Since `MA_BACKEND_COUNT` is always a relatively small value, this should be suitable for most scenarios.
  7778. ```
  7779. ma_backend enabledBackends[MA_BACKEND_COUNT];
  7780. size_t enabledBackendCount;
  7781. result = ma_get_enabled_backends(enabledBackends, MA_BACKEND_COUNT, &enabledBackendCount);
  7782. if (result != MA_SUCCESS) {
  7783. // Failed to retrieve enabled backends. Should never happen in this example since all inputs are valid.
  7784. }
  7785. ```
  7786. See Also
  7787. --------
  7788. ma_is_backend_enabled()
  7789. */
  7790. MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount);
  7791. /*
  7792. Determines whether or not loopback mode is support by a backend.
  7793. */
  7794. MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend);
  7795. #endif /* MA_NO_DEVICE_IO */
  7796. /************************************************************************************************************************************************************
  7797. Utilities
  7798. ************************************************************************************************************************************************************/
  7799. /*
  7800. Calculates a buffer size in milliseconds from the specified number of frames and sample rate.
  7801. */
  7802. MA_API ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate);
  7803. /*
  7804. Calculates a buffer size in frames from the specified number of milliseconds and sample rate.
  7805. */
  7806. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate);
  7807. /*
  7808. Copies PCM frames from one buffer to another.
  7809. */
  7810. MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
  7811. /*
  7812. Copies silent frames into the given buffer.
  7813. Remarks
  7814. -------
  7815. For all formats except `ma_format_u8`, the output buffer will be filled with 0. For `ma_format_u8` it will be filled with 128. The reason for this is that it
  7816. makes more sense for the purpose of mixing to initialize it to the center point.
  7817. */
  7818. MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
  7819. /*
  7820. Offsets a pointer by the specified number of PCM frames.
  7821. */
  7822. MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels);
  7823. MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels);
  7824. static MA_INLINE float* ma_offset_pcm_frames_ptr_f32(float* p, ma_uint64 offsetInFrames, ma_uint32 channels) { return (float*)ma_offset_pcm_frames_ptr((void*)p, offsetInFrames, ma_format_f32, channels); }
  7825. static MA_INLINE const float* ma_offset_pcm_frames_const_ptr_f32(const float* p, ma_uint64 offsetInFrames, ma_uint32 channels) { return (const float*)ma_offset_pcm_frames_const_ptr((const void*)p, offsetInFrames, ma_format_f32, channels); }
  7826. /*
  7827. Clips samples.
  7828. */
  7829. MA_API void ma_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count);
  7830. MA_API void ma_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count);
  7831. MA_API void ma_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count);
  7832. MA_API void ma_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count);
  7833. MA_API void ma_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count);
  7834. MA_API void ma_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
  7835. /*
  7836. Helper for applying a volume factor to samples.
  7837. Note that the source and destination buffers can be the same, in which case it'll perform the operation in-place.
  7838. */
  7839. MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor);
  7840. MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor);
  7841. MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor);
  7842. MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor);
  7843. MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor);
  7844. MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor);
  7845. MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor);
  7846. MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor);
  7847. MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor);
  7848. MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor);
  7849. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_u8(ma_uint8* pFramesOut, const ma_uint8* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7850. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s16(ma_int16* pFramesOut, const ma_int16* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7851. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s24(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7852. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s32(ma_int32* pFramesOut, const ma_int32* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7853. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7854. MA_API void ma_copy_and_apply_volume_factor_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor);
  7855. MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7856. MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7857. MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7858. MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7859. MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7860. MA_API void ma_apply_volume_factor_pcm_frames(void* pFrames, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor);
  7861. MA_API void ma_copy_and_apply_volume_factor_per_channel_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float* pChannelGains);
  7862. MA_API void ma_copy_and_apply_volume_and_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count, float volume);
  7863. MA_API void ma_copy_and_apply_volume_and_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count, float volume);
  7864. MA_API void ma_copy_and_apply_volume_and_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count, float volume);
  7865. MA_API void ma_copy_and_apply_volume_and_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count, float volume);
  7866. MA_API void ma_copy_and_apply_volume_and_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count, float volume);
  7867. MA_API void ma_copy_and_apply_volume_and_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float volume);
  7868. /*
  7869. Helper for converting a linear factor to gain in decibels.
  7870. */
  7871. MA_API float ma_volume_linear_to_db(float factor);
  7872. /*
  7873. Helper for converting gain in decibels to a linear factor.
  7874. */
  7875. MA_API float ma_volume_db_to_linear(float gain);
  7876. /*
  7877. Mixes the specified number of frames in floating point format with a volume factor.
  7878. This will run on an optimized path when the volume is equal to 1.
  7879. */
  7880. MA_API ma_result ma_mix_pcm_frames_f32(float* pDst, const float* pSrc, ma_uint64 frameCount, ma_uint32 channels, float volume);
  7881. /************************************************************************************************************************************************************
  7882. VFS
  7883. ===
  7884. The VFS object (virtual file system) is what's used to customize file access. This is useful in cases where stdio FILE* based APIs may not be entirely
  7885. appropriate for a given situation.
  7886. ************************************************************************************************************************************************************/
  7887. typedef void ma_vfs;
  7888. typedef ma_handle ma_vfs_file;
  7889. typedef enum
  7890. {
  7891. MA_OPEN_MODE_READ = 0x00000001,
  7892. MA_OPEN_MODE_WRITE = 0x00000002
  7893. } ma_open_mode_flags;
  7894. typedef enum
  7895. {
  7896. ma_seek_origin_start,
  7897. ma_seek_origin_current,
  7898. ma_seek_origin_end /* Not used by decoders. */
  7899. } ma_seek_origin;
  7900. typedef struct
  7901. {
  7902. ma_uint64 sizeInBytes;
  7903. } ma_file_info;
  7904. typedef struct
  7905. {
  7906. ma_result (* onOpen) (ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7907. ma_result (* onOpenW)(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7908. ma_result (* onClose)(ma_vfs* pVFS, ma_vfs_file file);
  7909. ma_result (* onRead) (ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead);
  7910. ma_result (* onWrite)(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten);
  7911. ma_result (* onSeek) (ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin);
  7912. ma_result (* onTell) (ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor);
  7913. ma_result (* onInfo) (ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo);
  7914. } ma_vfs_callbacks;
  7915. MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7916. MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7917. MA_API ma_result ma_vfs_close(ma_vfs* pVFS, ma_vfs_file file);
  7918. MA_API ma_result ma_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead);
  7919. MA_API ma_result ma_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten);
  7920. MA_API ma_result ma_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin);
  7921. MA_API ma_result ma_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor);
  7922. MA_API ma_result ma_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo);
  7923. MA_API ma_result ma_vfs_open_and_read_file(ma_vfs* pVFS, const char* pFilePath, void** ppData, size_t* pSize, const ma_allocation_callbacks* pAllocationCallbacks);
  7924. typedef struct
  7925. {
  7926. ma_vfs_callbacks cb;
  7927. ma_allocation_callbacks allocationCallbacks; /* Only used for the wchar_t version of open() on non-Windows platforms. */
  7928. } ma_default_vfs;
  7929. MA_API ma_result ma_default_vfs_init(ma_default_vfs* pVFS, const ma_allocation_callbacks* pAllocationCallbacks);
  7930. typedef ma_result (* ma_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead);
  7931. typedef ma_result (* ma_seek_proc)(void* pUserData, ma_int64 offset, ma_seek_origin origin);
  7932. typedef ma_result (* ma_tell_proc)(void* pUserData, ma_int64* pCursor);
  7933. #if !defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING)
  7934. typedef enum
  7935. {
  7936. ma_encoding_format_unknown = 0,
  7937. ma_encoding_format_wav,
  7938. ma_encoding_format_flac,
  7939. ma_encoding_format_mp3,
  7940. ma_encoding_format_vorbis
  7941. } ma_encoding_format;
  7942. #endif
  7943. /************************************************************************************************************************************************************
  7944. Decoding
  7945. ========
  7946. Decoders are independent of the main device API. Decoding APIs can be called freely inside the device's data callback, but they are not thread safe unless
  7947. you do your own synchronization.
  7948. ************************************************************************************************************************************************************/
  7949. #ifndef MA_NO_DECODING
  7950. typedef struct ma_decoder ma_decoder;
  7951. typedef struct
  7952. {
  7953. ma_format preferredFormat;
  7954. ma_uint32 seekPointCount; /* Set to > 0 to generate a seektable if the decoding backend supports it. */
  7955. } ma_decoding_backend_config;
  7956. MA_API ma_decoding_backend_config ma_decoding_backend_config_init(ma_format preferredFormat, ma_uint32 seekPointCount);
  7957. typedef struct
  7958. {
  7959. ma_result (* onInit )(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend);
  7960. ma_result (* onInitFile )(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend); /* Optional. */
  7961. ma_result (* onInitFileW )(void* pUserData, const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend); /* Optional. */
  7962. ma_result (* onInitMemory)(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend); /* Optional. */
  7963. void (* onUninit )(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks);
  7964. } ma_decoding_backend_vtable;
  7965. typedef ma_result (* ma_decoder_read_proc)(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead); /* Returns the number of bytes read. */
  7966. typedef ma_result (* ma_decoder_seek_proc)(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin);
  7967. typedef ma_result (* ma_decoder_tell_proc)(ma_decoder* pDecoder, ma_int64* pCursor);
  7968. typedef struct
  7969. {
  7970. ma_format format; /* Set to 0 or ma_format_unknown to use the stream's internal format. */
  7971. ma_uint32 channels; /* Set to 0 to use the stream's internal channels. */
  7972. ma_uint32 sampleRate; /* Set to 0 to use the stream's internal sample rate. */
  7973. ma_channel* pChannelMap;
  7974. ma_channel_mix_mode channelMixMode;
  7975. ma_dither_mode ditherMode;
  7976. ma_resampler_config resampling;
  7977. ma_allocation_callbacks allocationCallbacks;
  7978. ma_encoding_format encodingFormat;
  7979. ma_uint32 seekPointCount; /* When set to > 0, specifies the number of seek points to use for the generation of a seek table. Not all decoding backends support this. */
  7980. ma_decoding_backend_vtable** ppCustomBackendVTables;
  7981. ma_uint32 customBackendCount;
  7982. void* pCustomBackendUserData;
  7983. } ma_decoder_config;
  7984. struct ma_decoder
  7985. {
  7986. ma_data_source_base ds;
  7987. ma_data_source* pBackend; /* The decoding backend we'll be pulling data from. */
  7988. const ma_decoding_backend_vtable* pBackendVTable; /* The vtable for the decoding backend. This needs to be stored so we can access the onUninit() callback. */
  7989. void* pBackendUserData;
  7990. ma_decoder_read_proc onRead;
  7991. ma_decoder_seek_proc onSeek;
  7992. ma_decoder_tell_proc onTell;
  7993. void* pUserData;
  7994. ma_uint64 readPointerInPCMFrames; /* In output sample rate. Used for keeping track of how many frames are available for decoding. */
  7995. ma_format outputFormat;
  7996. ma_uint32 outputChannels;
  7997. ma_uint32 outputSampleRate;
  7998. ma_data_converter converter; /* Data conversion is achieved by running frames through this. */
  7999. void* pInputCache; /* In input format. Can be null if it's not needed. */
  8000. ma_uint64 inputCacheCap; /* The capacity of the input cache. */
  8001. ma_uint64 inputCacheConsumed; /* The number of frames that have been consumed in the cache. Used for determining the next valid frame. */
  8002. ma_uint64 inputCacheRemaining; /* The number of valid frames remaining in the cahce. */
  8003. ma_allocation_callbacks allocationCallbacks;
  8004. union
  8005. {
  8006. struct
  8007. {
  8008. ma_vfs* pVFS;
  8009. ma_vfs_file file;
  8010. } vfs;
  8011. struct
  8012. {
  8013. const ma_uint8* pData;
  8014. size_t dataSize;
  8015. size_t currentReadPos;
  8016. } memory; /* Only used for decoders that were opened against a block of memory. */
  8017. } data;
  8018. };
  8019. MA_API ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate);
  8020. MA_API ma_decoder_config ma_decoder_config_init_default(void);
  8021. MA_API ma_result ma_decoder_init(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8022. MA_API ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8023. MA_API ma_result ma_decoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8024. MA_API ma_result ma_decoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8025. MA_API ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8026. MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8027. /*
  8028. Uninitializes a decoder.
  8029. */
  8030. MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder);
  8031. /*
  8032. Reads PCM frames from the given decoder.
  8033. This is not thread safe without your own synchronization.
  8034. */
  8035. MA_API ma_result ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8036. /*
  8037. Seeks to a PCM frame based on it's absolute index.
  8038. This is not thread safe without your own synchronization.
  8039. */
  8040. MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex);
  8041. /*
  8042. Retrieves the decoder's output data format.
  8043. */
  8044. MA_API ma_result ma_decoder_get_data_format(ma_decoder* pDecoder, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  8045. /*
  8046. Retrieves the current position of the read cursor in PCM frames.
  8047. */
  8048. MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor);
  8049. /*
  8050. Retrieves the length of the decoder in PCM frames.
  8051. Do not call this on streams of an undefined length, such as internet radio.
  8052. If the length is unknown or an error occurs, 0 will be returned.
  8053. This will always return 0 for Vorbis decoders. This is due to a limitation with stb_vorbis in push mode which is what miniaudio
  8054. uses internally.
  8055. For MP3's, this will decode the entire file. Do not call this in time critical scenarios.
  8056. This function is not thread safe without your own synchronization.
  8057. */
  8058. MA_API ma_result ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pLength);
  8059. /*
  8060. Retrieves the number of frames that can be read before reaching the end.
  8061. This calls `ma_decoder_get_length_in_pcm_frames()` so you need to be aware of the rules for that function, in
  8062. particular ensuring you do not call it on streams of an undefined length, such as internet radio.
  8063. If the total length of the decoder cannot be retrieved, such as with Vorbis decoders, `MA_NOT_IMPLEMENTED` will be
  8064. returned.
  8065. */
  8066. MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames);
  8067. /*
  8068. Helper for opening and decoding a file into a heap allocated block of memory. Free the returned pointer with ma_free(). On input,
  8069. pConfig should be set to what you want. On output it will be set to what you got.
  8070. */
  8071. MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
  8072. MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
  8073. MA_API ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
  8074. #endif /* MA_NO_DECODING */
  8075. /************************************************************************************************************************************************************
  8076. Encoding
  8077. ========
  8078. Encoders do not perform any format conversion for you. If your target format does not support the format, and error will be returned.
  8079. ************************************************************************************************************************************************************/
  8080. #ifndef MA_NO_ENCODING
  8081. typedef struct ma_encoder ma_encoder;
  8082. typedef ma_result (* ma_encoder_write_proc) (ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite, size_t* pBytesWritten);
  8083. typedef ma_result (* ma_encoder_seek_proc) (ma_encoder* pEncoder, ma_int64 offset, ma_seek_origin origin);
  8084. typedef ma_result (* ma_encoder_init_proc) (ma_encoder* pEncoder);
  8085. typedef void (* ma_encoder_uninit_proc) (ma_encoder* pEncoder);
  8086. typedef ma_result (* ma_encoder_write_pcm_frames_proc)(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten);
  8087. typedef struct
  8088. {
  8089. ma_encoding_format encodingFormat;
  8090. ma_format format;
  8091. ma_uint32 channels;
  8092. ma_uint32 sampleRate;
  8093. ma_allocation_callbacks allocationCallbacks;
  8094. } ma_encoder_config;
  8095. MA_API ma_encoder_config ma_encoder_config_init(ma_encoding_format encodingFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate);
  8096. struct ma_encoder
  8097. {
  8098. ma_encoder_config config;
  8099. ma_encoder_write_proc onWrite;
  8100. ma_encoder_seek_proc onSeek;
  8101. ma_encoder_init_proc onInit;
  8102. ma_encoder_uninit_proc onUninit;
  8103. ma_encoder_write_pcm_frames_proc onWritePCMFrames;
  8104. void* pUserData;
  8105. void* pInternalEncoder; /* <-- The drwav/drflac/stb_vorbis/etc. objects. */
  8106. union
  8107. {
  8108. struct
  8109. {
  8110. ma_vfs* pVFS;
  8111. ma_vfs_file file;
  8112. } vfs;
  8113. } data;
  8114. };
  8115. MA_API ma_result ma_encoder_init(ma_encoder_write_proc onWrite, ma_encoder_seek_proc onSeek, void* pUserData, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  8116. MA_API ma_result ma_encoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  8117. MA_API ma_result ma_encoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  8118. MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  8119. MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  8120. MA_API void ma_encoder_uninit(ma_encoder* pEncoder);
  8121. MA_API ma_result ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten);
  8122. #endif /* MA_NO_ENCODING */
  8123. /************************************************************************************************************************************************************
  8124. Generation
  8125. ************************************************************************************************************************************************************/
  8126. #ifndef MA_NO_GENERATION
  8127. typedef enum
  8128. {
  8129. ma_waveform_type_sine,
  8130. ma_waveform_type_square,
  8131. ma_waveform_type_triangle,
  8132. ma_waveform_type_sawtooth
  8133. } ma_waveform_type;
  8134. typedef struct
  8135. {
  8136. ma_format format;
  8137. ma_uint32 channels;
  8138. ma_uint32 sampleRate;
  8139. ma_waveform_type type;
  8140. double amplitude;
  8141. double frequency;
  8142. } ma_waveform_config;
  8143. MA_API ma_waveform_config ma_waveform_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_waveform_type type, double amplitude, double frequency);
  8144. typedef struct
  8145. {
  8146. ma_data_source_base ds;
  8147. ma_waveform_config config;
  8148. double advance;
  8149. double time;
  8150. } ma_waveform;
  8151. MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform);
  8152. MA_API void ma_waveform_uninit(ma_waveform* pWaveform);
  8153. MA_API ma_result ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8154. MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex);
  8155. MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude);
  8156. MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency);
  8157. MA_API ma_result ma_waveform_set_type(ma_waveform* pWaveform, ma_waveform_type type);
  8158. MA_API ma_result ma_waveform_set_sample_rate(ma_waveform* pWaveform, ma_uint32 sampleRate);
  8159. typedef enum
  8160. {
  8161. ma_noise_type_white,
  8162. ma_noise_type_pink,
  8163. ma_noise_type_brownian
  8164. } ma_noise_type;
  8165. typedef struct
  8166. {
  8167. ma_format format;
  8168. ma_uint32 channels;
  8169. ma_noise_type type;
  8170. ma_int32 seed;
  8171. double amplitude;
  8172. ma_bool32 duplicateChannels;
  8173. } ma_noise_config;
  8174. MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude);
  8175. typedef struct
  8176. {
  8177. ma_data_source_vtable ds;
  8178. ma_noise_config config;
  8179. ma_lcg lcg;
  8180. union
  8181. {
  8182. struct
  8183. {
  8184. double** bin;
  8185. double* accumulation;
  8186. ma_uint32* counter;
  8187. } pink;
  8188. struct
  8189. {
  8190. double* accumulation;
  8191. } brownian;
  8192. } state;
  8193. /* Memory management. */
  8194. void* _pHeap;
  8195. ma_bool32 _ownsHeap;
  8196. } ma_noise;
  8197. MA_API ma_result ma_noise_get_heap_size(const ma_noise_config* pConfig, size_t* pHeapSizeInBytes);
  8198. MA_API ma_result ma_noise_init_preallocated(const ma_noise_config* pConfig, void* pHeap, ma_noise* pNoise);
  8199. MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_noise* pNoise);
  8200. MA_API void ma_noise_uninit(ma_noise* pNoise, const ma_allocation_callbacks* pAllocationCallbacks);
  8201. MA_API ma_result ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8202. MA_API ma_result ma_noise_set_amplitude(ma_noise* pNoise, double amplitude);
  8203. MA_API ma_result ma_noise_set_seed(ma_noise* pNoise, ma_int32 seed);
  8204. MA_API ma_result ma_noise_set_type(ma_noise* pNoise, ma_noise_type type);
  8205. #endif /* MA_NO_GENERATION */
  8206. /************************************************************************************************************************************************************
  8207. Resource Manager
  8208. ************************************************************************************************************************************************************/
  8209. /* The resource manager cannot be enabled if there is no decoder. */
  8210. #if !defined(MA_NO_RESOURCE_MANAGER) && defined(MA_NO_DECODING)
  8211. #define MA_NO_RESOURCE_MANAGER
  8212. #endif
  8213. #ifndef MA_NO_RESOURCE_MANAGER
  8214. typedef struct ma_resource_manager ma_resource_manager;
  8215. typedef struct ma_resource_manager_data_buffer_node ma_resource_manager_data_buffer_node;
  8216. typedef struct ma_resource_manager_data_buffer ma_resource_manager_data_buffer;
  8217. typedef struct ma_resource_manager_data_stream ma_resource_manager_data_stream;
  8218. typedef struct ma_resource_manager_data_source ma_resource_manager_data_source;
  8219. typedef enum
  8220. {
  8221. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM = 0x00000001, /* When set, does not load the entire data source in memory. Disk I/O will happen on job threads. */
  8222. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE = 0x00000002, /* Decode data before storing in memory. When set, decoding is done at the resource manager level rather than the mixing thread. Results in faster mixing, but higher memory usage. */
  8223. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC = 0x00000004, /* When set, the resource manager will load the data source asynchronously. */
  8224. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT = 0x00000008, /* When set, waits for initialization of the underlying data source before returning from ma_resource_manager_data_source_init(). */
  8225. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH = 0x00000010 /* Gives the resource manager a hint that the length of the data source is unknown and calling `ma_data_source_get_length_in_pcm_frames()` should be avoided. */
  8226. } ma_resource_manager_data_source_flags;
  8227. /*
  8228. Pipeline notifications used by the resource manager. Made up of both an async notification and a fence, both of which are optional.
  8229. */
  8230. typedef struct
  8231. {
  8232. ma_async_notification* pNotification;
  8233. ma_fence* pFence;
  8234. } ma_resource_manager_pipeline_stage_notification;
  8235. typedef struct
  8236. {
  8237. ma_resource_manager_pipeline_stage_notification init; /* Initialization of the decoder. */
  8238. ma_resource_manager_pipeline_stage_notification done; /* Decoding fully completed. */
  8239. } ma_resource_manager_pipeline_notifications;
  8240. MA_API ma_resource_manager_pipeline_notifications ma_resource_manager_pipeline_notifications_init(void);
  8241. /* BEGIN BACKWARDS COMPATIBILITY */
  8242. /* TODO: Remove this block in version 0.12. */
  8243. #if 1
  8244. #define ma_resource_manager_job ma_job
  8245. #define ma_resource_manager_job_init ma_job_init
  8246. #define MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_FLAG_NON_BLOCKING MA_JOB_QUEUE_FLAG_NON_BLOCKING
  8247. #define ma_resource_manager_job_queue_config ma_job_queue_config
  8248. #define ma_resource_manager_job_queue_config_init ma_job_queue_config_init
  8249. #define ma_resource_manager_job_queue ma_job_queue
  8250. #define ma_resource_manager_job_queue_get_heap_size ma_job_queue_get_heap_size
  8251. #define ma_resource_manager_job_queue_init_preallocated ma_job_queue_init_preallocated
  8252. #define ma_resource_manager_job_queue_init ma_job_queue_init
  8253. #define ma_resource_manager_job_queue_uninit ma_job_queue_uninit
  8254. #define ma_resource_manager_job_queue_post ma_job_queue_post
  8255. #define ma_resource_manager_job_queue_next ma_job_queue_next
  8256. #endif
  8257. /* END BACKWARDS COMPATIBILITY */
  8258. /* Maximum job thread count will be restricted to this, but this may be removed later and replaced with a heap allocation thereby removing any limitation. */
  8259. #ifndef MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT
  8260. #define MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT 64
  8261. #endif
  8262. typedef enum
  8263. {
  8264. /* Indicates ma_resource_manager_next_job() should not block. Only valid when the job thread count is 0. */
  8265. MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING = 0x00000001,
  8266. /* Disables any kind of multithreading. Implicitly enables MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING. */
  8267. MA_RESOURCE_MANAGER_FLAG_NO_THREADING = 0x00000002
  8268. } ma_resource_manager_flags;
  8269. typedef struct
  8270. {
  8271. const char* pFilePath;
  8272. const wchar_t* pFilePathW;
  8273. const ma_resource_manager_pipeline_notifications* pNotifications;
  8274. ma_uint64 initialSeekPointInPCMFrames;
  8275. ma_uint64 rangeBegInPCMFrames;
  8276. ma_uint64 rangeEndInPCMFrames;
  8277. ma_uint64 loopPointBegInPCMFrames;
  8278. ma_uint64 loopPointEndInPCMFrames;
  8279. ma_bool32 isLooping;
  8280. ma_uint32 flags;
  8281. } ma_resource_manager_data_source_config;
  8282. MA_API ma_resource_manager_data_source_config ma_resource_manager_data_source_config_init(void);
  8283. typedef enum
  8284. {
  8285. ma_resource_manager_data_supply_type_unknown = 0, /* Used for determining whether or the data supply has been initialized. */
  8286. ma_resource_manager_data_supply_type_encoded, /* Data supply is an encoded buffer. Connector is ma_decoder. */
  8287. ma_resource_manager_data_supply_type_decoded, /* Data supply is a decoded buffer. Connector is ma_audio_buffer. */
  8288. ma_resource_manager_data_supply_type_decoded_paged /* Data supply is a linked list of decoded buffers. Connector is ma_paged_audio_buffer. */
  8289. } ma_resource_manager_data_supply_type;
  8290. typedef struct
  8291. {
  8292. MA_ATOMIC(4, ma_resource_manager_data_supply_type) type; /* Read and written from different threads so needs to be accessed atomically. */
  8293. union
  8294. {
  8295. struct
  8296. {
  8297. const void* pData;
  8298. size_t sizeInBytes;
  8299. } encoded;
  8300. struct
  8301. {
  8302. const void* pData;
  8303. ma_uint64 totalFrameCount;
  8304. ma_uint64 decodedFrameCount;
  8305. ma_format format;
  8306. ma_uint32 channels;
  8307. ma_uint32 sampleRate;
  8308. } decoded;
  8309. struct
  8310. {
  8311. ma_paged_audio_buffer_data data;
  8312. ma_uint64 decodedFrameCount;
  8313. ma_uint32 sampleRate;
  8314. } decodedPaged;
  8315. } backend;
  8316. } ma_resource_manager_data_supply;
  8317. struct ma_resource_manager_data_buffer_node
  8318. {
  8319. ma_uint32 hashedName32; /* The hashed name. This is the key. */
  8320. ma_uint32 refCount;
  8321. MA_ATOMIC(4, ma_result) result; /* Result from asynchronous loading. When loading set to MA_BUSY. When fully loaded set to MA_SUCCESS. When deleting set to MA_UNAVAILABLE. */
  8322. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8323. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8324. ma_bool32 isDataOwnedByResourceManager; /* Set to true when the underlying data buffer was allocated the resource manager. Set to false if it is owned by the application (via ma_resource_manager_register_*()). */
  8325. ma_resource_manager_data_supply data;
  8326. ma_resource_manager_data_buffer_node* pParent;
  8327. ma_resource_manager_data_buffer_node* pChildLo;
  8328. ma_resource_manager_data_buffer_node* pChildHi;
  8329. };
  8330. struct ma_resource_manager_data_buffer
  8331. {
  8332. ma_data_source_base ds; /* Base data source. A data buffer is a data source. */
  8333. ma_resource_manager* pResourceManager; /* A pointer to the resource manager that owns this buffer. */
  8334. ma_resource_manager_data_buffer_node* pNode; /* The data node. This is reference counted and is what supplies the data. */
  8335. ma_uint32 flags; /* The flags that were passed used to initialize the buffer. */
  8336. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8337. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8338. ma_uint64 seekTargetInPCMFrames; /* Only updated by the public API. Never written nor read from the job thread. */
  8339. ma_bool32 seekToCursorOnNextRead; /* On the next read we need to seek to the frame cursor. */
  8340. MA_ATOMIC(4, ma_result) result; /* Keeps track of a result of decoding. Set to MA_BUSY while the buffer is still loading. Set to MA_SUCCESS when loading is finished successfully. Otherwise set to some other code. */
  8341. MA_ATOMIC(4, ma_bool32) isLooping; /* Can be read and written by different threads at the same time. Must be used atomically. */
  8342. ma_atomic_bool32 isConnectorInitialized; /* Used for asynchronous loading to ensure we don't try to initialize the connector multiple times while waiting for the node to fully load. */
  8343. union
  8344. {
  8345. ma_decoder decoder; /* Supply type is ma_resource_manager_data_supply_type_encoded */
  8346. ma_audio_buffer buffer; /* Supply type is ma_resource_manager_data_supply_type_decoded */
  8347. ma_paged_audio_buffer pagedBuffer; /* Supply type is ma_resource_manager_data_supply_type_decoded_paged */
  8348. } connector; /* Connects this object to the node's data supply. */
  8349. };
  8350. struct ma_resource_manager_data_stream
  8351. {
  8352. ma_data_source_base ds; /* Base data source. A data stream is a data source. */
  8353. ma_resource_manager* pResourceManager; /* A pointer to the resource manager that owns this data stream. */
  8354. ma_uint32 flags; /* The flags that were passed used to initialize the stream. */
  8355. ma_decoder decoder; /* Used for filling pages with data. This is only ever accessed by the job thread. The public API should never touch this. */
  8356. ma_bool32 isDecoderInitialized; /* Required for determining whether or not the decoder should be uninitialized in MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM. */
  8357. ma_uint64 totalLengthInPCMFrames; /* This is calculated when first loaded by the MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM. */
  8358. ma_uint32 relativeCursor; /* The playback cursor, relative to the current page. Only ever accessed by the public API. Never accessed by the job thread. */
  8359. MA_ATOMIC(8, ma_uint64) absoluteCursor; /* The playback cursor, in absolute position starting from the start of the file. */
  8360. ma_uint32 currentPageIndex; /* Toggles between 0 and 1. Index 0 is the first half of pPageData. Index 1 is the second half. Only ever accessed by the public API. Never accessed by the job thread. */
  8361. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8362. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8363. /* Written by the public API, read by the job thread. */
  8364. MA_ATOMIC(4, ma_bool32) isLooping; /* Whether or not the stream is looping. It's important to set the looping flag at the data stream level for smooth loop transitions. */
  8365. /* Written by the job thread, read by the public API. */
  8366. void* pPageData; /* Buffer containing the decoded data of each page. Allocated once at initialization time. */
  8367. MA_ATOMIC(4, ma_uint32) pageFrameCount[2]; /* The number of valid PCM frames in each page. Used to determine the last valid frame. */
  8368. /* Written and read by both the public API and the job thread. These must be atomic. */
  8369. MA_ATOMIC(4, ma_result) result; /* Result from asynchronous loading. When loading set to MA_BUSY. When initialized set to MA_SUCCESS. When deleting set to MA_UNAVAILABLE. If an error occurs when loading, set to an error code. */
  8370. MA_ATOMIC(4, ma_bool32) isDecoderAtEnd; /* Whether or not the decoder has reached the end. */
  8371. MA_ATOMIC(4, ma_bool32) isPageValid[2]; /* Booleans to indicate whether or not a page is valid. Set to false by the public API, set to true by the job thread. Set to false as the pages are consumed, true when they are filled. */
  8372. MA_ATOMIC(4, ma_bool32) seekCounter; /* When 0, no seeking is being performed. When > 0, a seek is being performed and reading should be delayed with MA_BUSY. */
  8373. };
  8374. struct ma_resource_manager_data_source
  8375. {
  8376. union
  8377. {
  8378. ma_resource_manager_data_buffer buffer;
  8379. ma_resource_manager_data_stream stream;
  8380. } backend; /* Must be the first item because we need the first item to be the data source callbacks for the buffer or stream. */
  8381. ma_uint32 flags; /* The flags that were passed in to ma_resource_manager_data_source_init(). */
  8382. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8383. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8384. };
  8385. typedef struct
  8386. {
  8387. ma_allocation_callbacks allocationCallbacks;
  8388. ma_log* pLog;
  8389. ma_format decodedFormat; /* The decoded format to use. Set to ma_format_unknown (default) to use the file's native format. */
  8390. ma_uint32 decodedChannels; /* The decoded channel count to use. Set to 0 (default) to use the file's native channel count. */
  8391. ma_uint32 decodedSampleRate; /* the decoded sample rate to use. Set to 0 (default) to use the file's native sample rate. */
  8392. ma_uint32 jobThreadCount; /* Set to 0 if you want to self-manage your job threads. Defaults to 1. */
  8393. size_t jobThreadStackSize;
  8394. ma_uint32 jobQueueCapacity; /* The maximum number of jobs that can fit in the queue at a time. Defaults to MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY. Cannot be zero. */
  8395. ma_uint32 flags;
  8396. ma_vfs* pVFS; /* Can be NULL in which case defaults will be used. */
  8397. ma_decoding_backend_vtable** ppCustomDecodingBackendVTables;
  8398. ma_uint32 customDecodingBackendCount;
  8399. void* pCustomDecodingBackendUserData;
  8400. } ma_resource_manager_config;
  8401. MA_API ma_resource_manager_config ma_resource_manager_config_init(void);
  8402. struct ma_resource_manager
  8403. {
  8404. ma_resource_manager_config config;
  8405. ma_resource_manager_data_buffer_node* pRootDataBufferNode; /* The root buffer in the binary tree. */
  8406. #ifndef MA_NO_THREADING
  8407. ma_mutex dataBufferBSTLock; /* For synchronizing access to the data buffer binary tree. */
  8408. ma_thread jobThreads[MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT]; /* The threads for executing jobs. */
  8409. #endif
  8410. ma_job_queue jobQueue; /* Multi-consumer, multi-producer job queue for managing jobs for asynchronous decoding and streaming. */
  8411. ma_default_vfs defaultVFS; /* Only used if a custom VFS is not specified. */
  8412. ma_log log; /* Only used if no log was specified in the config. */
  8413. };
  8414. /* Init. */
  8415. MA_API ma_result ma_resource_manager_init(const ma_resource_manager_config* pConfig, ma_resource_manager* pResourceManager);
  8416. MA_API void ma_resource_manager_uninit(ma_resource_manager* pResourceManager);
  8417. MA_API ma_log* ma_resource_manager_get_log(ma_resource_manager* pResourceManager);
  8418. /* Registration. */
  8419. MA_API ma_result ma_resource_manager_register_file(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags);
  8420. MA_API ma_result ma_resource_manager_register_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags);
  8421. MA_API ma_result ma_resource_manager_register_decoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate); /* Does not copy. Increments the reference count if already exists and returns MA_SUCCESS. */
  8422. MA_API ma_result ma_resource_manager_register_decoded_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate);
  8423. MA_API ma_result ma_resource_manager_register_encoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, size_t sizeInBytes); /* Does not copy. Increments the reference count if already exists and returns MA_SUCCESS. */
  8424. MA_API ma_result ma_resource_manager_register_encoded_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName, const void* pData, size_t sizeInBytes);
  8425. MA_API ma_result ma_resource_manager_unregister_file(ma_resource_manager* pResourceManager, const char* pFilePath);
  8426. MA_API ma_result ma_resource_manager_unregister_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath);
  8427. MA_API ma_result ma_resource_manager_unregister_data(ma_resource_manager* pResourceManager, const char* pName);
  8428. MA_API ma_result ma_resource_manager_unregister_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName);
  8429. /* Data Buffers. */
  8430. MA_API ma_result ma_resource_manager_data_buffer_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_buffer* pDataBuffer);
  8431. MA_API ma_result ma_resource_manager_data_buffer_init(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_buffer* pDataBuffer);
  8432. MA_API ma_result ma_resource_manager_data_buffer_init_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_buffer* pDataBuffer);
  8433. MA_API ma_result ma_resource_manager_data_buffer_init_copy(ma_resource_manager* pResourceManager, const ma_resource_manager_data_buffer* pExistingDataBuffer, ma_resource_manager_data_buffer* pDataBuffer);
  8434. MA_API ma_result ma_resource_manager_data_buffer_uninit(ma_resource_manager_data_buffer* pDataBuffer);
  8435. MA_API ma_result ma_resource_manager_data_buffer_read_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8436. MA_API ma_result ma_resource_manager_data_buffer_seek_to_pcm_frame(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64 frameIndex);
  8437. MA_API ma_result ma_resource_manager_data_buffer_get_data_format(ma_resource_manager_data_buffer* pDataBuffer, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  8438. MA_API ma_result ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pCursor);
  8439. MA_API ma_result ma_resource_manager_data_buffer_get_length_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pLength);
  8440. MA_API ma_result ma_resource_manager_data_buffer_result(const ma_resource_manager_data_buffer* pDataBuffer);
  8441. MA_API ma_result ma_resource_manager_data_buffer_set_looping(ma_resource_manager_data_buffer* pDataBuffer, ma_bool32 isLooping);
  8442. MA_API ma_bool32 ma_resource_manager_data_buffer_is_looping(const ma_resource_manager_data_buffer* pDataBuffer);
  8443. MA_API ma_result ma_resource_manager_data_buffer_get_available_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pAvailableFrames);
  8444. /* Data Streams. */
  8445. MA_API ma_result ma_resource_manager_data_stream_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_stream* pDataStream);
  8446. MA_API ma_result ma_resource_manager_data_stream_init(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_stream* pDataStream);
  8447. MA_API ma_result ma_resource_manager_data_stream_init_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_stream* pDataStream);
  8448. MA_API ma_result ma_resource_manager_data_stream_uninit(ma_resource_manager_data_stream* pDataStream);
  8449. MA_API ma_result ma_resource_manager_data_stream_read_pcm_frames(ma_resource_manager_data_stream* pDataStream, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8450. MA_API ma_result ma_resource_manager_data_stream_seek_to_pcm_frame(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameIndex);
  8451. MA_API ma_result ma_resource_manager_data_stream_get_data_format(ma_resource_manager_data_stream* pDataStream, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  8452. MA_API ma_result ma_resource_manager_data_stream_get_cursor_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pCursor);
  8453. MA_API ma_result ma_resource_manager_data_stream_get_length_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pLength);
  8454. MA_API ma_result ma_resource_manager_data_stream_result(const ma_resource_manager_data_stream* pDataStream);
  8455. MA_API ma_result ma_resource_manager_data_stream_set_looping(ma_resource_manager_data_stream* pDataStream, ma_bool32 isLooping);
  8456. MA_API ma_bool32 ma_resource_manager_data_stream_is_looping(const ma_resource_manager_data_stream* pDataStream);
  8457. MA_API ma_result ma_resource_manager_data_stream_get_available_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pAvailableFrames);
  8458. /* Data Sources. */
  8459. MA_API ma_result ma_resource_manager_data_source_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_source* pDataSource);
  8460. MA_API ma_result ma_resource_manager_data_source_init(ma_resource_manager* pResourceManager, const char* pName, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_source* pDataSource);
  8461. MA_API ma_result ma_resource_manager_data_source_init_w(ma_resource_manager* pResourceManager, const wchar_t* pName, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_source* pDataSource);
  8462. MA_API ma_result ma_resource_manager_data_source_init_copy(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source* pExistingDataSource, ma_resource_manager_data_source* pDataSource);
  8463. MA_API ma_result ma_resource_manager_data_source_uninit(ma_resource_manager_data_source* pDataSource);
  8464. MA_API ma_result ma_resource_manager_data_source_read_pcm_frames(ma_resource_manager_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8465. MA_API ma_result ma_resource_manager_data_source_seek_to_pcm_frame(ma_resource_manager_data_source* pDataSource, ma_uint64 frameIndex);
  8466. MA_API ma_result ma_resource_manager_data_source_get_data_format(ma_resource_manager_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  8467. MA_API ma_result ma_resource_manager_data_source_get_cursor_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pCursor);
  8468. MA_API ma_result ma_resource_manager_data_source_get_length_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pLength);
  8469. MA_API ma_result ma_resource_manager_data_source_result(const ma_resource_manager_data_source* pDataSource);
  8470. MA_API ma_result ma_resource_manager_data_source_set_looping(ma_resource_manager_data_source* pDataSource, ma_bool32 isLooping);
  8471. MA_API ma_bool32 ma_resource_manager_data_source_is_looping(const ma_resource_manager_data_source* pDataSource);
  8472. MA_API ma_result ma_resource_manager_data_source_get_available_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pAvailableFrames);
  8473. /* Job management. */
  8474. MA_API ma_result ma_resource_manager_post_job(ma_resource_manager* pResourceManager, const ma_job* pJob);
  8475. MA_API ma_result ma_resource_manager_post_job_quit(ma_resource_manager* pResourceManager); /* Helper for posting a quit job. */
  8476. MA_API ma_result ma_resource_manager_next_job(ma_resource_manager* pResourceManager, ma_job* pJob);
  8477. MA_API ma_result ma_resource_manager_process_job(ma_resource_manager* pResourceManager, ma_job* pJob); /* DEPRECATED. Use ma_job_process(). Will be removed in version 0.12. */
  8478. MA_API ma_result ma_resource_manager_process_next_job(ma_resource_manager* pResourceManager); /* Returns MA_CANCELLED if a MA_JOB_TYPE_QUIT job is found. In non-blocking mode, returns MA_NO_DATA_AVAILABLE if no jobs are available. */
  8479. #endif /* MA_NO_RESOURCE_MANAGER */
  8480. /************************************************************************************************************************************************************
  8481. Node Graph
  8482. ************************************************************************************************************************************************************/
  8483. #ifndef MA_NO_NODE_GRAPH
  8484. /* Must never exceed 254. */
  8485. #ifndef MA_MAX_NODE_BUS_COUNT
  8486. #define MA_MAX_NODE_BUS_COUNT 254
  8487. #endif
  8488. /* Used internally by miniaudio for memory management. Must never exceed MA_MAX_NODE_BUS_COUNT. */
  8489. #ifndef MA_MAX_NODE_LOCAL_BUS_COUNT
  8490. #define MA_MAX_NODE_LOCAL_BUS_COUNT 2
  8491. #endif
  8492. /* Use this when the bus count is determined by the node instance rather than the vtable. */
  8493. #define MA_NODE_BUS_COUNT_UNKNOWN 255
  8494. typedef struct ma_node_graph ma_node_graph;
  8495. typedef void ma_node;
  8496. /* Node flags. */
  8497. typedef enum
  8498. {
  8499. MA_NODE_FLAG_PASSTHROUGH = 0x00000001,
  8500. MA_NODE_FLAG_CONTINUOUS_PROCESSING = 0x00000002,
  8501. MA_NODE_FLAG_ALLOW_NULL_INPUT = 0x00000004,
  8502. MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES = 0x00000008,
  8503. MA_NODE_FLAG_SILENT_OUTPUT = 0x00000010
  8504. } ma_node_flags;
  8505. /* The playback state of a node. Either started or stopped. */
  8506. typedef enum
  8507. {
  8508. ma_node_state_started = 0,
  8509. ma_node_state_stopped = 1
  8510. } ma_node_state;
  8511. typedef struct
  8512. {
  8513. /*
  8514. Extended processing callback. This callback is used for effects that process input and output
  8515. at different rates (i.e. they perform resampling). This is similar to the simple version, only
  8516. they take two seperate frame counts: one for input, and one for output.
  8517. On input, `pFrameCountOut` is equal to the capacity of the output buffer for each bus, whereas
  8518. `pFrameCountIn` will be equal to the number of PCM frames in each of the buffers in `ppFramesIn`.
  8519. On output, set `pFrameCountOut` to the number of PCM frames that were actually output and set
  8520. `pFrameCountIn` to the number of input frames that were consumed.
  8521. */
  8522. void (* onProcess)(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut);
  8523. /*
  8524. A callback for retrieving the number of a input frames that are required to output the
  8525. specified number of output frames. You would only want to implement this when the node performs
  8526. resampling. This is optional, even for nodes that perform resampling, but it does offer a
  8527. small reduction in latency as it allows miniaudio to calculate the exact number of input frames
  8528. to read at a time instead of having to estimate.
  8529. */
  8530. ma_result (* onGetRequiredInputFrameCount)(ma_node* pNode, ma_uint32 outputFrameCount, ma_uint32* pInputFrameCount);
  8531. /*
  8532. The number of input buses. This is how many sub-buffers will be contained in the `ppFramesIn`
  8533. parameters of the callbacks above.
  8534. */
  8535. ma_uint8 inputBusCount;
  8536. /*
  8537. The number of output buses. This is how many sub-buffers will be contained in the `ppFramesOut`
  8538. parameters of the callbacks above.
  8539. */
  8540. ma_uint8 outputBusCount;
  8541. /*
  8542. Flags describing characteristics of the node. This is currently just a placeholder for some
  8543. ideas for later on.
  8544. */
  8545. ma_uint32 flags;
  8546. } ma_node_vtable;
  8547. typedef struct
  8548. {
  8549. const ma_node_vtable* vtable; /* Should never be null. Initialization of the node will fail if so. */
  8550. ma_node_state initialState; /* Defaults to ma_node_state_started. */
  8551. ma_uint32 inputBusCount; /* Only used if the vtable specifies an input bus count of `MA_NODE_BUS_COUNT_UNKNOWN`, otherwise must be set to `MA_NODE_BUS_COUNT_UNKNOWN` (default). */
  8552. ma_uint32 outputBusCount; /* Only used if the vtable specifies an output bus count of `MA_NODE_BUS_COUNT_UNKNOWN`, otherwise be set to `MA_NODE_BUS_COUNT_UNKNOWN` (default). */
  8553. const ma_uint32* pInputChannels; /* The number of elements are determined by the input bus count as determined by the vtable, or `inputBusCount` if the vtable specifies `MA_NODE_BUS_COUNT_UNKNOWN`. */
  8554. const ma_uint32* pOutputChannels; /* The number of elements are determined by the output bus count as determined by the vtable, or `outputBusCount` if the vtable specifies `MA_NODE_BUS_COUNT_UNKNOWN`. */
  8555. } ma_node_config;
  8556. MA_API ma_node_config ma_node_config_init(void);
  8557. /*
  8558. A node has multiple output buses. An output bus is attached to an input bus as an item in a linked
  8559. list. Think of the input bus as a linked list, with the output bus being an item in that list.
  8560. */
  8561. typedef struct ma_node_output_bus ma_node_output_bus;
  8562. struct ma_node_output_bus
  8563. {
  8564. /* Immutable. */
  8565. ma_node* pNode; /* The node that owns this output bus. The input node. Will be null for dummy head and tail nodes. */
  8566. ma_uint8 outputBusIndex; /* The index of the output bus on pNode that this output bus represents. */
  8567. ma_uint8 channels; /* The number of channels in the audio stream for this bus. */
  8568. /* Mutable via multiple threads. Must be used atomically. The weird ordering here is for packing reasons. */
  8569. ma_uint8 inputNodeInputBusIndex; /* The index of the input bus on the input. Required for detaching. Will only be used within the spinlock so does not need to be atomic. */
  8570. MA_ATOMIC(4, ma_uint32) flags; /* Some state flags for tracking the read state of the output buffer. A combination of MA_NODE_OUTPUT_BUS_FLAG_*. */
  8571. MA_ATOMIC(4, ma_uint32) refCount; /* Reference count for some thread-safety when detaching. */
  8572. MA_ATOMIC(4, ma_bool32) isAttached; /* This is used to prevent iteration of nodes that are in the middle of being detached. Used for thread safety. */
  8573. MA_ATOMIC(4, ma_spinlock) lock; /* Unfortunate lock, but significantly simplifies the implementation. Required for thread-safe attaching and detaching. */
  8574. MA_ATOMIC(4, float) volume; /* Linear. */
  8575. MA_ATOMIC(MA_SIZEOF_PTR, ma_node_output_bus*) pNext; /* If null, it's the tail node or detached. */
  8576. MA_ATOMIC(MA_SIZEOF_PTR, ma_node_output_bus*) pPrev; /* If null, it's the head node or detached. */
  8577. MA_ATOMIC(MA_SIZEOF_PTR, ma_node*) pInputNode; /* The node that this output bus is attached to. Required for detaching. */
  8578. };
  8579. /*
  8580. A node has multiple input buses. The output buses of a node are connecting to the input busses of
  8581. another. An input bus is essentially just a linked list of output buses.
  8582. */
  8583. typedef struct ma_node_input_bus ma_node_input_bus;
  8584. struct ma_node_input_bus
  8585. {
  8586. /* Mutable via multiple threads. */
  8587. ma_node_output_bus head; /* Dummy head node for simplifying some lock-free thread-safety stuff. */
  8588. MA_ATOMIC(4, ma_uint32) nextCounter; /* This is used to determine whether or not the input bus is finding the next node in the list. Used for thread safety when detaching output buses. */
  8589. MA_ATOMIC(4, ma_spinlock) lock; /* Unfortunate lock, but significantly simplifies the implementation. Required for thread-safe attaching and detaching. */
  8590. /* Set once at startup. */
  8591. ma_uint8 channels; /* The number of channels in the audio stream for this bus. */
  8592. };
  8593. typedef struct ma_node_base ma_node_base;
  8594. struct ma_node_base
  8595. {
  8596. /* These variables are set once at startup. */
  8597. ma_node_graph* pNodeGraph; /* The graph this node belongs to. */
  8598. const ma_node_vtable* vtable;
  8599. float* pCachedData; /* Allocated on the heap. Fixed size. Needs to be stored on the heap because reading from output buses is done in separate function calls. */
  8600. ma_uint16 cachedDataCapInFramesPerBus; /* The capacity of the input data cache in frames, per bus. */
  8601. /* These variables are read and written only from the audio thread. */
  8602. ma_uint16 cachedFrameCountOut;
  8603. ma_uint16 cachedFrameCountIn;
  8604. ma_uint16 consumedFrameCountIn;
  8605. /* These variables are read and written between different threads. */
  8606. MA_ATOMIC(4, ma_node_state) state; /* When set to stopped, nothing will be read, regardless of the times in stateTimes. */
  8607. MA_ATOMIC(8, ma_uint64) stateTimes[2]; /* Indexed by ma_node_state. Specifies the time based on the global clock that a node should be considered to be in the relevant state. */
  8608. MA_ATOMIC(8, ma_uint64) localTime; /* The node's local clock. This is just a running sum of the number of output frames that have been processed. Can be modified by any thread with `ma_node_set_time()`. */
  8609. ma_uint32 inputBusCount;
  8610. ma_uint32 outputBusCount;
  8611. ma_node_input_bus* pInputBuses;
  8612. ma_node_output_bus* pOutputBuses;
  8613. /* Memory management. */
  8614. ma_node_input_bus _inputBuses[MA_MAX_NODE_LOCAL_BUS_COUNT];
  8615. ma_node_output_bus _outputBuses[MA_MAX_NODE_LOCAL_BUS_COUNT];
  8616. void* _pHeap; /* A heap allocation for internal use only. pInputBuses and/or pOutputBuses will point to this if the bus count exceeds MA_MAX_NODE_LOCAL_BUS_COUNT. */
  8617. ma_bool32 _ownsHeap; /* If set to true, the node owns the heap allocation and _pHeap will be freed in ma_node_uninit(). */
  8618. };
  8619. MA_API ma_result ma_node_get_heap_size(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, size_t* pHeapSizeInBytes);
  8620. MA_API ma_result ma_node_init_preallocated(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, void* pHeap, ma_node* pNode);
  8621. MA_API ma_result ma_node_init(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node* pNode);
  8622. MA_API void ma_node_uninit(ma_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8623. MA_API ma_node_graph* ma_node_get_node_graph(const ma_node* pNode);
  8624. MA_API ma_uint32 ma_node_get_input_bus_count(const ma_node* pNode);
  8625. MA_API ma_uint32 ma_node_get_output_bus_count(const ma_node* pNode);
  8626. MA_API ma_uint32 ma_node_get_input_channels(const ma_node* pNode, ma_uint32 inputBusIndex);
  8627. MA_API ma_uint32 ma_node_get_output_channels(const ma_node* pNode, ma_uint32 outputBusIndex);
  8628. MA_API ma_result ma_node_attach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex, ma_node* pOtherNode, ma_uint32 otherNodeInputBusIndex);
  8629. MA_API ma_result ma_node_detach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex);
  8630. MA_API ma_result ma_node_detach_all_output_buses(ma_node* pNode);
  8631. MA_API ma_result ma_node_set_output_bus_volume(ma_node* pNode, ma_uint32 outputBusIndex, float volume);
  8632. MA_API float ma_node_get_output_bus_volume(const ma_node* pNode, ma_uint32 outputBusIndex);
  8633. MA_API ma_result ma_node_set_state(ma_node* pNode, ma_node_state state);
  8634. MA_API ma_node_state ma_node_get_state(const ma_node* pNode);
  8635. MA_API ma_result ma_node_set_state_time(ma_node* pNode, ma_node_state state, ma_uint64 globalTime);
  8636. MA_API ma_uint64 ma_node_get_state_time(const ma_node* pNode, ma_node_state state);
  8637. MA_API ma_node_state ma_node_get_state_by_time(const ma_node* pNode, ma_uint64 globalTime);
  8638. MA_API ma_node_state ma_node_get_state_by_time_range(const ma_node* pNode, ma_uint64 globalTimeBeg, ma_uint64 globalTimeEnd);
  8639. MA_API ma_uint64 ma_node_get_time(const ma_node* pNode);
  8640. MA_API ma_result ma_node_set_time(ma_node* pNode, ma_uint64 localTime);
  8641. typedef struct
  8642. {
  8643. ma_uint32 channels;
  8644. ma_uint16 nodeCacheCapInFrames;
  8645. } ma_node_graph_config;
  8646. MA_API ma_node_graph_config ma_node_graph_config_init(ma_uint32 channels);
  8647. struct ma_node_graph
  8648. {
  8649. /* Immutable. */
  8650. ma_node_base base; /* The node graph itself is a node so it can be connected as an input to different node graph. This has zero inputs and calls ma_node_graph_read_pcm_frames() to generate it's output. */
  8651. ma_node_base endpoint; /* Special node that all nodes eventually connect to. Data is read from this node in ma_node_graph_read_pcm_frames(). */
  8652. ma_uint16 nodeCacheCapInFrames;
  8653. /* Read and written by multiple threads. */
  8654. MA_ATOMIC(4, ma_bool32) isReading;
  8655. };
  8656. MA_API ma_result ma_node_graph_init(const ma_node_graph_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node_graph* pNodeGraph);
  8657. MA_API void ma_node_graph_uninit(ma_node_graph* pNodeGraph, const ma_allocation_callbacks* pAllocationCallbacks);
  8658. MA_API ma_node* ma_node_graph_get_endpoint(ma_node_graph* pNodeGraph);
  8659. MA_API ma_result ma_node_graph_read_pcm_frames(ma_node_graph* pNodeGraph, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8660. MA_API ma_uint32 ma_node_graph_get_channels(const ma_node_graph* pNodeGraph);
  8661. MA_API ma_uint64 ma_node_graph_get_time(const ma_node_graph* pNodeGraph);
  8662. MA_API ma_result ma_node_graph_set_time(ma_node_graph* pNodeGraph, ma_uint64 globalTime);
  8663. /* Data source node. 0 input buses, 1 output bus. Used for reading from a data source. */
  8664. typedef struct
  8665. {
  8666. ma_node_config nodeConfig;
  8667. ma_data_source* pDataSource;
  8668. } ma_data_source_node_config;
  8669. MA_API ma_data_source_node_config ma_data_source_node_config_init(ma_data_source* pDataSource);
  8670. typedef struct
  8671. {
  8672. ma_node_base base;
  8673. ma_data_source* pDataSource;
  8674. } ma_data_source_node;
  8675. MA_API ma_result ma_data_source_node_init(ma_node_graph* pNodeGraph, const ma_data_source_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source_node* pDataSourceNode);
  8676. MA_API void ma_data_source_node_uninit(ma_data_source_node* pDataSourceNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8677. MA_API ma_result ma_data_source_node_set_looping(ma_data_source_node* pDataSourceNode, ma_bool32 isLooping);
  8678. MA_API ma_bool32 ma_data_source_node_is_looping(ma_data_source_node* pDataSourceNode);
  8679. /* Splitter Node. 1 input, many outputs. Used for splitting/copying a stream so it can be as input into two separate output nodes. */
  8680. typedef struct
  8681. {
  8682. ma_node_config nodeConfig;
  8683. ma_uint32 channels;
  8684. ma_uint32 outputBusCount;
  8685. } ma_splitter_node_config;
  8686. MA_API ma_splitter_node_config ma_splitter_node_config_init(ma_uint32 channels);
  8687. typedef struct
  8688. {
  8689. ma_node_base base;
  8690. } ma_splitter_node;
  8691. MA_API ma_result ma_splitter_node_init(ma_node_graph* pNodeGraph, const ma_splitter_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_splitter_node* pSplitterNode);
  8692. MA_API void ma_splitter_node_uninit(ma_splitter_node* pSplitterNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8693. /*
  8694. Biquad Node
  8695. */
  8696. typedef struct
  8697. {
  8698. ma_node_config nodeConfig;
  8699. ma_biquad_config biquad;
  8700. } ma_biquad_node_config;
  8701. MA_API ma_biquad_node_config ma_biquad_node_config_init(ma_uint32 channels, float b0, float b1, float b2, float a0, float a1, float a2);
  8702. typedef struct
  8703. {
  8704. ma_node_base baseNode;
  8705. ma_biquad biquad;
  8706. } ma_biquad_node;
  8707. MA_API ma_result ma_biquad_node_init(ma_node_graph* pNodeGraph, const ma_biquad_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad_node* pNode);
  8708. MA_API ma_result ma_biquad_node_reinit(const ma_biquad_config* pConfig, ma_biquad_node* pNode);
  8709. MA_API void ma_biquad_node_uninit(ma_biquad_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8710. /*
  8711. Low Pass Filter Node
  8712. */
  8713. typedef struct
  8714. {
  8715. ma_node_config nodeConfig;
  8716. ma_lpf_config lpf;
  8717. } ma_lpf_node_config;
  8718. MA_API ma_lpf_node_config ma_lpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  8719. typedef struct
  8720. {
  8721. ma_node_base baseNode;
  8722. ma_lpf lpf;
  8723. } ma_lpf_node;
  8724. MA_API ma_result ma_lpf_node_init(ma_node_graph* pNodeGraph, const ma_lpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf_node* pNode);
  8725. MA_API ma_result ma_lpf_node_reinit(const ma_lpf_config* pConfig, ma_lpf_node* pNode);
  8726. MA_API void ma_lpf_node_uninit(ma_lpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8727. /*
  8728. High Pass Filter Node
  8729. */
  8730. typedef struct
  8731. {
  8732. ma_node_config nodeConfig;
  8733. ma_hpf_config hpf;
  8734. } ma_hpf_node_config;
  8735. MA_API ma_hpf_node_config ma_hpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  8736. typedef struct
  8737. {
  8738. ma_node_base baseNode;
  8739. ma_hpf hpf;
  8740. } ma_hpf_node;
  8741. MA_API ma_result ma_hpf_node_init(ma_node_graph* pNodeGraph, const ma_hpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf_node* pNode);
  8742. MA_API ma_result ma_hpf_node_reinit(const ma_hpf_config* pConfig, ma_hpf_node* pNode);
  8743. MA_API void ma_hpf_node_uninit(ma_hpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8744. /*
  8745. Band Pass Filter Node
  8746. */
  8747. typedef struct
  8748. {
  8749. ma_node_config nodeConfig;
  8750. ma_bpf_config bpf;
  8751. } ma_bpf_node_config;
  8752. MA_API ma_bpf_node_config ma_bpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  8753. typedef struct
  8754. {
  8755. ma_node_base baseNode;
  8756. ma_bpf bpf;
  8757. } ma_bpf_node;
  8758. MA_API ma_result ma_bpf_node_init(ma_node_graph* pNodeGraph, const ma_bpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf_node* pNode);
  8759. MA_API ma_result ma_bpf_node_reinit(const ma_bpf_config* pConfig, ma_bpf_node* pNode);
  8760. MA_API void ma_bpf_node_uninit(ma_bpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8761. /*
  8762. Notching Filter Node
  8763. */
  8764. typedef struct
  8765. {
  8766. ma_node_config nodeConfig;
  8767. ma_notch_config notch;
  8768. } ma_notch_node_config;
  8769. MA_API ma_notch_node_config ma_notch_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency);
  8770. typedef struct
  8771. {
  8772. ma_node_base baseNode;
  8773. ma_notch2 notch;
  8774. } ma_notch_node;
  8775. MA_API ma_result ma_notch_node_init(ma_node_graph* pNodeGraph, const ma_notch_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch_node* pNode);
  8776. MA_API ma_result ma_notch_node_reinit(const ma_notch_config* pConfig, ma_notch_node* pNode);
  8777. MA_API void ma_notch_node_uninit(ma_notch_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8778. /*
  8779. Peaking Filter Node
  8780. */
  8781. typedef struct
  8782. {
  8783. ma_node_config nodeConfig;
  8784. ma_peak_config peak;
  8785. } ma_peak_node_config;
  8786. MA_API ma_peak_node_config ma_peak_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  8787. typedef struct
  8788. {
  8789. ma_node_base baseNode;
  8790. ma_peak2 peak;
  8791. } ma_peak_node;
  8792. MA_API ma_result ma_peak_node_init(ma_node_graph* pNodeGraph, const ma_peak_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak_node* pNode);
  8793. MA_API ma_result ma_peak_node_reinit(const ma_peak_config* pConfig, ma_peak_node* pNode);
  8794. MA_API void ma_peak_node_uninit(ma_peak_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8795. /*
  8796. Low Shelf Filter Node
  8797. */
  8798. typedef struct
  8799. {
  8800. ma_node_config nodeConfig;
  8801. ma_loshelf_config loshelf;
  8802. } ma_loshelf_node_config;
  8803. MA_API ma_loshelf_node_config ma_loshelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  8804. typedef struct
  8805. {
  8806. ma_node_base baseNode;
  8807. ma_loshelf2 loshelf;
  8808. } ma_loshelf_node;
  8809. MA_API ma_result ma_loshelf_node_init(ma_node_graph* pNodeGraph, const ma_loshelf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf_node* pNode);
  8810. MA_API ma_result ma_loshelf_node_reinit(const ma_loshelf_config* pConfig, ma_loshelf_node* pNode);
  8811. MA_API void ma_loshelf_node_uninit(ma_loshelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8812. /*
  8813. High Shelf Filter Node
  8814. */
  8815. typedef struct
  8816. {
  8817. ma_node_config nodeConfig;
  8818. ma_hishelf_config hishelf;
  8819. } ma_hishelf_node_config;
  8820. MA_API ma_hishelf_node_config ma_hishelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  8821. typedef struct
  8822. {
  8823. ma_node_base baseNode;
  8824. ma_hishelf2 hishelf;
  8825. } ma_hishelf_node;
  8826. MA_API ma_result ma_hishelf_node_init(ma_node_graph* pNodeGraph, const ma_hishelf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf_node* pNode);
  8827. MA_API ma_result ma_hishelf_node_reinit(const ma_hishelf_config* pConfig, ma_hishelf_node* pNode);
  8828. MA_API void ma_hishelf_node_uninit(ma_hishelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8829. typedef struct
  8830. {
  8831. ma_node_config nodeConfig;
  8832. ma_delay_config delay;
  8833. } ma_delay_node_config;
  8834. MA_API ma_delay_node_config ma_delay_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay);
  8835. typedef struct
  8836. {
  8837. ma_node_base baseNode;
  8838. ma_delay delay;
  8839. } ma_delay_node;
  8840. MA_API ma_result ma_delay_node_init(ma_node_graph* pNodeGraph, const ma_delay_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay_node* pDelayNode);
  8841. MA_API void ma_delay_node_uninit(ma_delay_node* pDelayNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8842. MA_API void ma_delay_node_set_wet(ma_delay_node* pDelayNode, float value);
  8843. MA_API float ma_delay_node_get_wet(const ma_delay_node* pDelayNode);
  8844. MA_API void ma_delay_node_set_dry(ma_delay_node* pDelayNode, float value);
  8845. MA_API float ma_delay_node_get_dry(const ma_delay_node* pDelayNode);
  8846. MA_API void ma_delay_node_set_decay(ma_delay_node* pDelayNode, float value);
  8847. MA_API float ma_delay_node_get_decay(const ma_delay_node* pDelayNode);
  8848. #endif /* MA_NO_NODE_GRAPH */
  8849. /* SECTION: miniaudio_engine.h */
  8850. /************************************************************************************************************************************************************
  8851. Engine
  8852. ************************************************************************************************************************************************************/
  8853. #if !defined(MA_NO_ENGINE) && !defined(MA_NO_NODE_GRAPH)
  8854. typedef struct ma_engine ma_engine;
  8855. typedef struct ma_sound ma_sound;
  8856. /* Sound flags. */
  8857. typedef enum
  8858. {
  8859. /* Resource manager flags. */
  8860. MA_SOUND_FLAG_STREAM = 0x00000001, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM */
  8861. MA_SOUND_FLAG_DECODE = 0x00000002, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE */
  8862. MA_SOUND_FLAG_ASYNC = 0x00000004, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC */
  8863. MA_SOUND_FLAG_WAIT_INIT = 0x00000008, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT */
  8864. MA_SOUND_FLAG_UNKNOWN_LENGTH = 0x00000010, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH */
  8865. /* ma_sound specific flags. */
  8866. MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT = 0x00001000, /* Do not attach to the endpoint by default. Useful for when setting up nodes in a complex graph system. */
  8867. MA_SOUND_FLAG_NO_PITCH = 0x00002000, /* Disable pitch shifting with ma_sound_set_pitch() and ma_sound_group_set_pitch(). This is an optimization. */
  8868. MA_SOUND_FLAG_NO_SPATIALIZATION = 0x00004000 /* Disable spatialization. */
  8869. } ma_sound_flags;
  8870. #ifndef MA_ENGINE_MAX_LISTENERS
  8871. #define MA_ENGINE_MAX_LISTENERS 4
  8872. #endif
  8873. #define MA_LISTENER_INDEX_CLOSEST ((ma_uint8)-1)
  8874. typedef enum
  8875. {
  8876. ma_engine_node_type_sound,
  8877. ma_engine_node_type_group
  8878. } ma_engine_node_type;
  8879. typedef struct
  8880. {
  8881. ma_engine* pEngine;
  8882. ma_engine_node_type type;
  8883. ma_uint32 channelsIn;
  8884. ma_uint32 channelsOut;
  8885. ma_uint32 sampleRate; /* Only used when the type is set to ma_engine_node_type_sound. */
  8886. ma_uint32 volumeSmoothTimeInPCMFrames; /* The number of frames to smooth over volume changes. Defaults to 0 in which case no smoothing is used. */
  8887. ma_mono_expansion_mode monoExpansionMode;
  8888. ma_bool8 isPitchDisabled; /* Pitching can be explicitly disabled with MA_SOUND_FLAG_NO_PITCH to optimize processing. */
  8889. ma_bool8 isSpatializationDisabled; /* Spatialization can be explicitly disabled with MA_SOUND_FLAG_NO_SPATIALIZATION. */
  8890. ma_uint8 pinnedListenerIndex; /* The index of the listener this node should always use for spatialization. If set to MA_LISTENER_INDEX_CLOSEST the engine will use the closest listener. */
  8891. } ma_engine_node_config;
  8892. MA_API ma_engine_node_config ma_engine_node_config_init(ma_engine* pEngine, ma_engine_node_type type, ma_uint32 flags);
  8893. /* Base node object for both ma_sound and ma_sound_group. */
  8894. typedef struct
  8895. {
  8896. ma_node_base baseNode; /* Must be the first member for compatiblity with the ma_node API. */
  8897. ma_engine* pEngine; /* A pointer to the engine. Set based on the value from the config. */
  8898. ma_uint32 sampleRate; /* The sample rate of the input data. For sounds backed by a data source, this will be the data source's sample rate. Otherwise it'll be the engine's sample rate. */
  8899. ma_uint32 volumeSmoothTimeInPCMFrames;
  8900. ma_mono_expansion_mode monoExpansionMode;
  8901. ma_fader fader;
  8902. ma_linear_resampler resampler; /* For pitch shift. */
  8903. ma_spatializer spatializer;
  8904. ma_panner panner;
  8905. ma_gainer volumeGainer; /* This will only be used if volumeSmoothTimeInPCMFrames is > 0. */
  8906. ma_atomic_float volume; /* Defaults to 1. */
  8907. MA_ATOMIC(4, float) pitch;
  8908. float oldPitch; /* For determining whether or not the resampler needs to be updated to reflect the new pitch. The resampler will be updated on the mixing thread. */
  8909. float oldDopplerPitch; /* For determining whether or not the resampler needs to be updated to take a new doppler pitch into account. */
  8910. MA_ATOMIC(4, ma_bool32) isPitchDisabled; /* When set to true, pitching will be disabled which will allow the resampler to be bypassed to save some computation. */
  8911. MA_ATOMIC(4, ma_bool32) isSpatializationDisabled; /* Set to false by default. When set to false, will not have spatialisation applied. */
  8912. MA_ATOMIC(4, ma_uint32) pinnedListenerIndex; /* The index of the listener this node should always use for spatialization. If set to MA_LISTENER_INDEX_CLOSEST the engine will use the closest listener. */
  8913. /* Memory management. */
  8914. ma_bool8 _ownsHeap;
  8915. void* _pHeap;
  8916. } ma_engine_node;
  8917. MA_API ma_result ma_engine_node_get_heap_size(const ma_engine_node_config* pConfig, size_t* pHeapSizeInBytes);
  8918. MA_API ma_result ma_engine_node_init_preallocated(const ma_engine_node_config* pConfig, void* pHeap, ma_engine_node* pEngineNode);
  8919. MA_API ma_result ma_engine_node_init(const ma_engine_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_engine_node* pEngineNode);
  8920. MA_API void ma_engine_node_uninit(ma_engine_node* pEngineNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8921. #define MA_SOUND_SOURCE_CHANNEL_COUNT 0xFFFFFFFF
  8922. /* Callback for when a sound reaches the end. */
  8923. typedef void (* ma_sound_end_proc)(void* pUserData, ma_sound* pSound);
  8924. typedef struct
  8925. {
  8926. const char* pFilePath; /* Set this to load from the resource manager. */
  8927. const wchar_t* pFilePathW; /* Set this to load from the resource manager. */
  8928. ma_data_source* pDataSource; /* Set this to load from an existing data source. */
  8929. ma_node* pInitialAttachment; /* If set, the sound will be attached to an input of this node. This can be set to a ma_sound. If set to NULL, the sound will be attached directly to the endpoint unless MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT is set in `flags`. */
  8930. ma_uint32 initialAttachmentInputBusIndex; /* The index of the input bus of pInitialAttachment to attach the sound to. */
  8931. ma_uint32 channelsIn; /* Ignored if using a data source as input (the data source's channel count will be used always). Otherwise, setting to 0 will cause the engine's channel count to be used. */
  8932. ma_uint32 channelsOut; /* Set this to 0 (default) to use the engine's channel count. Set to MA_SOUND_SOURCE_CHANNEL_COUNT to use the data source's channel count (only used if using a data source as input). */
  8933. ma_mono_expansion_mode monoExpansionMode; /* Controls how the mono channel should be expanded to other channels when spatialization is disabled on a sound. */
  8934. ma_uint32 flags; /* A combination of MA_SOUND_FLAG_* flags. */
  8935. ma_uint32 volumeSmoothTimeInPCMFrames; /* The number of frames to smooth over volume changes. Defaults to 0 in which case no smoothing is used. */
  8936. ma_uint64 initialSeekPointInPCMFrames; /* Initializes the sound such that it's seeked to this location by default. */
  8937. ma_uint64 rangeBegInPCMFrames;
  8938. ma_uint64 rangeEndInPCMFrames;
  8939. ma_uint64 loopPointBegInPCMFrames;
  8940. ma_uint64 loopPointEndInPCMFrames;
  8941. ma_bool32 isLooping;
  8942. ma_sound_end_proc endCallback; /* Fired when the sound reaches the end. Will be fired from the audio thread. Do not restart, uninitialize or otherwise change the state of the sound from here. Instead fire an event or set a variable to indicate to a different thread to change the start of the sound. Will not be fired in response to a scheduled stop with ma_sound_set_stop_time_*(). */
  8943. void* pEndCallbackUserData;
  8944. #ifndef MA_NO_RESOURCE_MANAGER
  8945. ma_resource_manager_pipeline_notifications initNotifications;
  8946. #endif
  8947. ma_fence* pDoneFence; /* Deprecated. Use initNotifications instead. Released when the resource manager has finished decoding the entire sound. Not used with streams. */
  8948. } ma_sound_config;
  8949. MA_API ma_sound_config ma_sound_config_init(void); /* Deprecated. Will be removed in version 0.12. Use ma_sound_config_2() instead. */
  8950. MA_API ma_sound_config ma_sound_config_init_2(ma_engine* pEngine); /* Will be renamed to ma_sound_config_init() in version 0.12. */
  8951. struct ma_sound
  8952. {
  8953. ma_engine_node engineNode; /* Must be the first member for compatibility with the ma_node API. */
  8954. ma_data_source* pDataSource;
  8955. MA_ATOMIC(8, ma_uint64) seekTarget; /* The PCM frame index to seek to in the mixing thread. Set to (~(ma_uint64)0) to not perform any seeking. */
  8956. MA_ATOMIC(4, ma_bool32) atEnd;
  8957. ma_sound_end_proc endCallback;
  8958. void* pEndCallbackUserData;
  8959. ma_bool8 ownsDataSource;
  8960. /*
  8961. We're declaring a resource manager data source object here to save us a malloc when loading a
  8962. sound via the resource manager, which I *think* will be the most common scenario.
  8963. */
  8964. #ifndef MA_NO_RESOURCE_MANAGER
  8965. ma_resource_manager_data_source* pResourceManagerDataSource;
  8966. #endif
  8967. };
  8968. /* Structure specifically for sounds played with ma_engine_play_sound(). Making this a separate structure to reduce overhead. */
  8969. typedef struct ma_sound_inlined ma_sound_inlined;
  8970. struct ma_sound_inlined
  8971. {
  8972. ma_sound sound;
  8973. ma_sound_inlined* pNext;
  8974. ma_sound_inlined* pPrev;
  8975. };
  8976. /* A sound group is just a sound. */
  8977. typedef ma_sound_config ma_sound_group_config;
  8978. typedef ma_sound ma_sound_group;
  8979. MA_API ma_sound_group_config ma_sound_group_config_init(void); /* Deprecated. Will be removed in version 0.12. Use ma_sound_config_2() instead. */
  8980. MA_API ma_sound_group_config ma_sound_group_config_init_2(ma_engine* pEngine); /* Will be renamed to ma_sound_config_init() in version 0.12. */
  8981. typedef struct
  8982. {
  8983. #if !defined(MA_NO_RESOURCE_MANAGER)
  8984. ma_resource_manager* pResourceManager; /* Can be null in which case a resource manager will be created for you. */
  8985. #endif
  8986. #if !defined(MA_NO_DEVICE_IO)
  8987. ma_context* pContext;
  8988. ma_device* pDevice; /* If set, the caller is responsible for calling ma_engine_data_callback() in the device's data callback. */
  8989. ma_device_id* pPlaybackDeviceID; /* The ID of the playback device to use with the default listener. */
  8990. ma_device_notification_proc notificationCallback;
  8991. #endif
  8992. ma_log* pLog; /* When set to NULL, will use the context's log. */
  8993. ma_uint32 listenerCount; /* Must be between 1 and MA_ENGINE_MAX_LISTENERS. */
  8994. ma_uint32 channels; /* The number of channels to use when mixing and spatializing. When set to 0, will use the native channel count of the device. */
  8995. ma_uint32 sampleRate; /* The sample rate. When set to 0 will use the native channel count of the device. */
  8996. ma_uint32 periodSizeInFrames; /* If set to something other than 0, updates will always be exactly this size. The underlying device may be a different size, but from the perspective of the mixer that won't matter.*/
  8997. ma_uint32 periodSizeInMilliseconds; /* Used if periodSizeInFrames is unset. */
  8998. ma_uint32 gainSmoothTimeInFrames; /* The number of frames to interpolate the gain of spatialized sounds across. If set to 0, will use gainSmoothTimeInMilliseconds. */
  8999. ma_uint32 gainSmoothTimeInMilliseconds; /* When set to 0, gainSmoothTimeInFrames will be used. If both are set to 0, a default value will be used. */
  9000. ma_uint32 defaultVolumeSmoothTimeInPCMFrames; /* Defaults to 0. Controls the default amount of smoothing to apply to volume changes to sounds. High values means more smoothing at the expense of high latency (will take longer to reach the new volume). */
  9001. ma_allocation_callbacks allocationCallbacks;
  9002. ma_bool32 noAutoStart; /* When set to true, requires an explicit call to ma_engine_start(). This is false by default, meaning the engine will be started automatically in ma_engine_init(). */
  9003. ma_bool32 noDevice; /* When set to true, don't create a default device. ma_engine_read_pcm_frames() can be called manually to read data. */
  9004. ma_mono_expansion_mode monoExpansionMode; /* Controls how the mono channel should be expanded to other channels when spatialization is disabled on a sound. */
  9005. ma_vfs* pResourceManagerVFS; /* A pointer to a pre-allocated VFS object to use with the resource manager. This is ignored if pResourceManager is not NULL. */
  9006. } ma_engine_config;
  9007. MA_API ma_engine_config ma_engine_config_init(void);
  9008. struct ma_engine
  9009. {
  9010. ma_node_graph nodeGraph; /* An engine is a node graph. It should be able to be plugged into any ma_node_graph API (with a cast) which means this must be the first member of this struct. */
  9011. #if !defined(MA_NO_RESOURCE_MANAGER)
  9012. ma_resource_manager* pResourceManager;
  9013. #endif
  9014. #if !defined(MA_NO_DEVICE_IO)
  9015. ma_device* pDevice; /* Optionally set via the config, otherwise allocated by the engine in ma_engine_init(). */
  9016. #endif
  9017. ma_log* pLog;
  9018. ma_uint32 sampleRate;
  9019. ma_uint32 listenerCount;
  9020. ma_spatializer_listener listeners[MA_ENGINE_MAX_LISTENERS];
  9021. ma_allocation_callbacks allocationCallbacks;
  9022. ma_bool8 ownsResourceManager;
  9023. ma_bool8 ownsDevice;
  9024. ma_spinlock inlinedSoundLock; /* For synchronizing access so the inlined sound list. */
  9025. ma_sound_inlined* pInlinedSoundHead; /* The first inlined sound. Inlined sounds are tracked in a linked list. */
  9026. MA_ATOMIC(4, ma_uint32) inlinedSoundCount; /* The total number of allocated inlined sound objects. Used for debugging. */
  9027. ma_uint32 gainSmoothTimeInFrames; /* The number of frames to interpolate the gain of spatialized sounds across. */
  9028. ma_uint32 defaultVolumeSmoothTimeInPCMFrames;
  9029. ma_mono_expansion_mode monoExpansionMode;
  9030. };
  9031. MA_API ma_result ma_engine_init(const ma_engine_config* pConfig, ma_engine* pEngine);
  9032. MA_API void ma_engine_uninit(ma_engine* pEngine);
  9033. MA_API ma_result ma_engine_read_pcm_frames(ma_engine* pEngine, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  9034. MA_API ma_node_graph* ma_engine_get_node_graph(ma_engine* pEngine);
  9035. #if !defined(MA_NO_RESOURCE_MANAGER)
  9036. MA_API ma_resource_manager* ma_engine_get_resource_manager(ma_engine* pEngine);
  9037. #endif
  9038. MA_API ma_device* ma_engine_get_device(ma_engine* pEngine);
  9039. MA_API ma_log* ma_engine_get_log(ma_engine* pEngine);
  9040. MA_API ma_node* ma_engine_get_endpoint(ma_engine* pEngine);
  9041. MA_API ma_uint64 ma_engine_get_time_in_pcm_frames(const ma_engine* pEngine);
  9042. MA_API ma_uint64 ma_engine_get_time_in_milliseconds(const ma_engine* pEngine);
  9043. MA_API ma_result ma_engine_set_time_in_pcm_frames(ma_engine* pEngine, ma_uint64 globalTime);
  9044. MA_API ma_result ma_engine_set_time_in_milliseconds(ma_engine* pEngine, ma_uint64 globalTime);
  9045. MA_API ma_uint64 ma_engine_get_time(const ma_engine* pEngine); /* Deprecated. Use ma_engine_get_time_in_pcm_frames(). Will be removed in version 0.12. */
  9046. MA_API ma_result ma_engine_set_time(ma_engine* pEngine, ma_uint64 globalTime); /* Deprecated. Use ma_engine_set_time_in_pcm_frames(). Will be removed in version 0.12. */
  9047. MA_API ma_uint32 ma_engine_get_channels(const ma_engine* pEngine);
  9048. MA_API ma_uint32 ma_engine_get_sample_rate(const ma_engine* pEngine);
  9049. MA_API ma_result ma_engine_start(ma_engine* pEngine);
  9050. MA_API ma_result ma_engine_stop(ma_engine* pEngine);
  9051. MA_API ma_result ma_engine_set_volume(ma_engine* pEngine, float volume);
  9052. MA_API ma_result ma_engine_set_gain_db(ma_engine* pEngine, float gainDB);
  9053. MA_API ma_uint32 ma_engine_get_listener_count(const ma_engine* pEngine);
  9054. MA_API ma_uint32 ma_engine_find_closest_listener(const ma_engine* pEngine, float absolutePosX, float absolutePosY, float absolutePosZ);
  9055. MA_API void ma_engine_listener_set_position(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  9056. MA_API ma_vec3f ma_engine_listener_get_position(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9057. MA_API void ma_engine_listener_set_direction(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  9058. MA_API ma_vec3f ma_engine_listener_get_direction(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9059. MA_API void ma_engine_listener_set_velocity(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  9060. MA_API ma_vec3f ma_engine_listener_get_velocity(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9061. MA_API void ma_engine_listener_set_cone(ma_engine* pEngine, ma_uint32 listenerIndex, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  9062. MA_API void ma_engine_listener_get_cone(const ma_engine* pEngine, ma_uint32 listenerIndex, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  9063. MA_API void ma_engine_listener_set_world_up(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  9064. MA_API ma_vec3f ma_engine_listener_get_world_up(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9065. MA_API void ma_engine_listener_set_enabled(ma_engine* pEngine, ma_uint32 listenerIndex, ma_bool32 isEnabled);
  9066. MA_API ma_bool32 ma_engine_listener_is_enabled(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9067. #ifndef MA_NO_RESOURCE_MANAGER
  9068. MA_API ma_result ma_engine_play_sound_ex(ma_engine* pEngine, const char* pFilePath, ma_node* pNode, ma_uint32 nodeInputBusIndex);
  9069. MA_API ma_result ma_engine_play_sound(ma_engine* pEngine, const char* pFilePath, ma_sound_group* pGroup); /* Fire and forget. */
  9070. #endif
  9071. #ifndef MA_NO_RESOURCE_MANAGER
  9072. MA_API ma_result ma_sound_init_from_file(ma_engine* pEngine, const char* pFilePath, ma_uint32 flags, ma_sound_group* pGroup, ma_fence* pDoneFence, ma_sound* pSound);
  9073. MA_API ma_result ma_sound_init_from_file_w(ma_engine* pEngine, const wchar_t* pFilePath, ma_uint32 flags, ma_sound_group* pGroup, ma_fence* pDoneFence, ma_sound* pSound);
  9074. MA_API ma_result ma_sound_init_copy(ma_engine* pEngine, const ma_sound* pExistingSound, ma_uint32 flags, ma_sound_group* pGroup, ma_sound* pSound);
  9075. #endif
  9076. MA_API ma_result ma_sound_init_from_data_source(ma_engine* pEngine, ma_data_source* pDataSource, ma_uint32 flags, ma_sound_group* pGroup, ma_sound* pSound);
  9077. MA_API ma_result ma_sound_init_ex(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound);
  9078. MA_API void ma_sound_uninit(ma_sound* pSound);
  9079. MA_API ma_engine* ma_sound_get_engine(const ma_sound* pSound);
  9080. MA_API ma_data_source* ma_sound_get_data_source(const ma_sound* pSound);
  9081. MA_API ma_result ma_sound_start(ma_sound* pSound);
  9082. MA_API ma_result ma_sound_stop(ma_sound* pSound);
  9083. MA_API void ma_sound_set_volume(ma_sound* pSound, float volume);
  9084. MA_API float ma_sound_get_volume(const ma_sound* pSound);
  9085. MA_API void ma_sound_set_pan(ma_sound* pSound, float pan);
  9086. MA_API float ma_sound_get_pan(const ma_sound* pSound);
  9087. MA_API void ma_sound_set_pan_mode(ma_sound* pSound, ma_pan_mode panMode);
  9088. MA_API ma_pan_mode ma_sound_get_pan_mode(const ma_sound* pSound);
  9089. MA_API void ma_sound_set_pitch(ma_sound* pSound, float pitch);
  9090. MA_API float ma_sound_get_pitch(const ma_sound* pSound);
  9091. MA_API void ma_sound_set_spatialization_enabled(ma_sound* pSound, ma_bool32 enabled);
  9092. MA_API ma_bool32 ma_sound_is_spatialization_enabled(const ma_sound* pSound);
  9093. MA_API void ma_sound_set_pinned_listener_index(ma_sound* pSound, ma_uint32 listenerIndex);
  9094. MA_API ma_uint32 ma_sound_get_pinned_listener_index(const ma_sound* pSound);
  9095. MA_API ma_uint32 ma_sound_get_listener_index(const ma_sound* pSound);
  9096. MA_API ma_vec3f ma_sound_get_direction_to_listener(const ma_sound* pSound);
  9097. MA_API void ma_sound_set_position(ma_sound* pSound, float x, float y, float z);
  9098. MA_API ma_vec3f ma_sound_get_position(const ma_sound* pSound);
  9099. MA_API void ma_sound_set_direction(ma_sound* pSound, float x, float y, float z);
  9100. MA_API ma_vec3f ma_sound_get_direction(const ma_sound* pSound);
  9101. MA_API void ma_sound_set_velocity(ma_sound* pSound, float x, float y, float z);
  9102. MA_API ma_vec3f ma_sound_get_velocity(const ma_sound* pSound);
  9103. MA_API void ma_sound_set_attenuation_model(ma_sound* pSound, ma_attenuation_model attenuationModel);
  9104. MA_API ma_attenuation_model ma_sound_get_attenuation_model(const ma_sound* pSound);
  9105. MA_API void ma_sound_set_positioning(ma_sound* pSound, ma_positioning positioning);
  9106. MA_API ma_positioning ma_sound_get_positioning(const ma_sound* pSound);
  9107. MA_API void ma_sound_set_rolloff(ma_sound* pSound, float rolloff);
  9108. MA_API float ma_sound_get_rolloff(const ma_sound* pSound);
  9109. MA_API void ma_sound_set_min_gain(ma_sound* pSound, float minGain);
  9110. MA_API float ma_sound_get_min_gain(const ma_sound* pSound);
  9111. MA_API void ma_sound_set_max_gain(ma_sound* pSound, float maxGain);
  9112. MA_API float ma_sound_get_max_gain(const ma_sound* pSound);
  9113. MA_API void ma_sound_set_min_distance(ma_sound* pSound, float minDistance);
  9114. MA_API float ma_sound_get_min_distance(const ma_sound* pSound);
  9115. MA_API void ma_sound_set_max_distance(ma_sound* pSound, float maxDistance);
  9116. MA_API float ma_sound_get_max_distance(const ma_sound* pSound);
  9117. MA_API void ma_sound_set_cone(ma_sound* pSound, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  9118. MA_API void ma_sound_get_cone(const ma_sound* pSound, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  9119. MA_API void ma_sound_set_doppler_factor(ma_sound* pSound, float dopplerFactor);
  9120. MA_API float ma_sound_get_doppler_factor(const ma_sound* pSound);
  9121. MA_API void ma_sound_set_directional_attenuation_factor(ma_sound* pSound, float directionalAttenuationFactor);
  9122. MA_API float ma_sound_get_directional_attenuation_factor(const ma_sound* pSound);
  9123. MA_API void ma_sound_set_fade_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames);
  9124. MA_API void ma_sound_set_fade_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds);
  9125. MA_API float ma_sound_get_current_fade_volume(const ma_sound* pSound);
  9126. MA_API void ma_sound_set_start_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames);
  9127. MA_API void ma_sound_set_start_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds);
  9128. MA_API void ma_sound_set_stop_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames);
  9129. MA_API void ma_sound_set_stop_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds);
  9130. MA_API ma_bool32 ma_sound_is_playing(const ma_sound* pSound);
  9131. MA_API ma_uint64 ma_sound_get_time_in_pcm_frames(const ma_sound* pSound);
  9132. MA_API void ma_sound_set_looping(ma_sound* pSound, ma_bool32 isLooping);
  9133. MA_API ma_bool32 ma_sound_is_looping(const ma_sound* pSound);
  9134. MA_API ma_bool32 ma_sound_at_end(const ma_sound* pSound);
  9135. MA_API ma_result ma_sound_seek_to_pcm_frame(ma_sound* pSound, ma_uint64 frameIndex); /* Just a wrapper around ma_data_source_seek_to_pcm_frame(). */
  9136. MA_API ma_result ma_sound_get_data_format(ma_sound* pSound, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  9137. MA_API ma_result ma_sound_get_cursor_in_pcm_frames(ma_sound* pSound, ma_uint64* pCursor);
  9138. MA_API ma_result ma_sound_get_length_in_pcm_frames(ma_sound* pSound, ma_uint64* pLength);
  9139. MA_API ma_result ma_sound_get_cursor_in_seconds(ma_sound* pSound, float* pCursor);
  9140. MA_API ma_result ma_sound_get_length_in_seconds(ma_sound* pSound, float* pLength);
  9141. MA_API ma_result ma_sound_set_end_callback(ma_sound* pSound, ma_sound_end_proc callback, void* pUserData);
  9142. MA_API ma_result ma_sound_group_init(ma_engine* pEngine, ma_uint32 flags, ma_sound_group* pParentGroup, ma_sound_group* pGroup);
  9143. MA_API ma_result ma_sound_group_init_ex(ma_engine* pEngine, const ma_sound_group_config* pConfig, ma_sound_group* pGroup);
  9144. MA_API void ma_sound_group_uninit(ma_sound_group* pGroup);
  9145. MA_API ma_engine* ma_sound_group_get_engine(const ma_sound_group* pGroup);
  9146. MA_API ma_result ma_sound_group_start(ma_sound_group* pGroup);
  9147. MA_API ma_result ma_sound_group_stop(ma_sound_group* pGroup);
  9148. MA_API void ma_sound_group_set_volume(ma_sound_group* pGroup, float volume);
  9149. MA_API float ma_sound_group_get_volume(const ma_sound_group* pGroup);
  9150. MA_API void ma_sound_group_set_pan(ma_sound_group* pGroup, float pan);
  9151. MA_API float ma_sound_group_get_pan(const ma_sound_group* pGroup);
  9152. MA_API void ma_sound_group_set_pan_mode(ma_sound_group* pGroup, ma_pan_mode panMode);
  9153. MA_API ma_pan_mode ma_sound_group_get_pan_mode(const ma_sound_group* pGroup);
  9154. MA_API void ma_sound_group_set_pitch(ma_sound_group* pGroup, float pitch);
  9155. MA_API float ma_sound_group_get_pitch(const ma_sound_group* pGroup);
  9156. MA_API void ma_sound_group_set_spatialization_enabled(ma_sound_group* pGroup, ma_bool32 enabled);
  9157. MA_API ma_bool32 ma_sound_group_is_spatialization_enabled(const ma_sound_group* pGroup);
  9158. MA_API void ma_sound_group_set_pinned_listener_index(ma_sound_group* pGroup, ma_uint32 listenerIndex);
  9159. MA_API ma_uint32 ma_sound_group_get_pinned_listener_index(const ma_sound_group* pGroup);
  9160. MA_API ma_uint32 ma_sound_group_get_listener_index(const ma_sound_group* pGroup);
  9161. MA_API ma_vec3f ma_sound_group_get_direction_to_listener(const ma_sound_group* pGroup);
  9162. MA_API void ma_sound_group_set_position(ma_sound_group* pGroup, float x, float y, float z);
  9163. MA_API ma_vec3f ma_sound_group_get_position(const ma_sound_group* pGroup);
  9164. MA_API void ma_sound_group_set_direction(ma_sound_group* pGroup, float x, float y, float z);
  9165. MA_API ma_vec3f ma_sound_group_get_direction(const ma_sound_group* pGroup);
  9166. MA_API void ma_sound_group_set_velocity(ma_sound_group* pGroup, float x, float y, float z);
  9167. MA_API ma_vec3f ma_sound_group_get_velocity(const ma_sound_group* pGroup);
  9168. MA_API void ma_sound_group_set_attenuation_model(ma_sound_group* pGroup, ma_attenuation_model attenuationModel);
  9169. MA_API ma_attenuation_model ma_sound_group_get_attenuation_model(const ma_sound_group* pGroup);
  9170. MA_API void ma_sound_group_set_positioning(ma_sound_group* pGroup, ma_positioning positioning);
  9171. MA_API ma_positioning ma_sound_group_get_positioning(const ma_sound_group* pGroup);
  9172. MA_API void ma_sound_group_set_rolloff(ma_sound_group* pGroup, float rolloff);
  9173. MA_API float ma_sound_group_get_rolloff(const ma_sound_group* pGroup);
  9174. MA_API void ma_sound_group_set_min_gain(ma_sound_group* pGroup, float minGain);
  9175. MA_API float ma_sound_group_get_min_gain(const ma_sound_group* pGroup);
  9176. MA_API void ma_sound_group_set_max_gain(ma_sound_group* pGroup, float maxGain);
  9177. MA_API float ma_sound_group_get_max_gain(const ma_sound_group* pGroup);
  9178. MA_API void ma_sound_group_set_min_distance(ma_sound_group* pGroup, float minDistance);
  9179. MA_API float ma_sound_group_get_min_distance(const ma_sound_group* pGroup);
  9180. MA_API void ma_sound_group_set_max_distance(ma_sound_group* pGroup, float maxDistance);
  9181. MA_API float ma_sound_group_get_max_distance(const ma_sound_group* pGroup);
  9182. MA_API void ma_sound_group_set_cone(ma_sound_group* pGroup, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  9183. MA_API void ma_sound_group_get_cone(const ma_sound_group* pGroup, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  9184. MA_API void ma_sound_group_set_doppler_factor(ma_sound_group* pGroup, float dopplerFactor);
  9185. MA_API float ma_sound_group_get_doppler_factor(const ma_sound_group* pGroup);
  9186. MA_API void ma_sound_group_set_directional_attenuation_factor(ma_sound_group* pGroup, float directionalAttenuationFactor);
  9187. MA_API float ma_sound_group_get_directional_attenuation_factor(const ma_sound_group* pGroup);
  9188. MA_API void ma_sound_group_set_fade_in_pcm_frames(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames);
  9189. MA_API void ma_sound_group_set_fade_in_milliseconds(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds);
  9190. MA_API float ma_sound_group_get_current_fade_volume(ma_sound_group* pGroup);
  9191. MA_API void ma_sound_group_set_start_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames);
  9192. MA_API void ma_sound_group_set_start_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds);
  9193. MA_API void ma_sound_group_set_stop_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames);
  9194. MA_API void ma_sound_group_set_stop_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds);
  9195. MA_API ma_bool32 ma_sound_group_is_playing(const ma_sound_group* pGroup);
  9196. MA_API ma_uint64 ma_sound_group_get_time_in_pcm_frames(const ma_sound_group* pGroup);
  9197. #endif /* MA_NO_ENGINE */
  9198. /* END SECTION: miniaudio_engine.h */
  9199. #ifdef __cplusplus
  9200. }
  9201. #endif
  9202. #endif /* miniaudio_h */
  9203. /*
  9204. This is for preventing greying out of the implementation section.
  9205. */
  9206. #if defined(Q_CREATOR_RUN) || defined(__INTELLISENSE__) || defined(__CDT_PARSER__)
  9207. #define MINIAUDIO_IMPLEMENTATION
  9208. #endif
  9209. /************************************************************************************************************************************************************
  9210. *************************************************************************************************************************************************************
  9211. IMPLEMENTATION
  9212. *************************************************************************************************************************************************************
  9213. ************************************************************************************************************************************************************/
  9214. #if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION)
  9215. #ifndef miniaudio_c
  9216. #define miniaudio_c
  9217. #include <assert.h>
  9218. #include <limits.h> /* For INT_MAX */
  9219. #include <math.h> /* sin(), etc. */
  9220. #include <stdlib.h> /* For malloc(), free(), wcstombs(). */
  9221. #include <string.h> /* For memset() */
  9222. #include <stdarg.h>
  9223. #include <stdio.h>
  9224. #if !defined(_MSC_VER) && !defined(__DMC__)
  9225. #include <strings.h> /* For strcasecmp(). */
  9226. #include <wchar.h> /* For wcslen(), wcsrtombs() */
  9227. #endif
  9228. #ifdef _MSC_VER
  9229. #include <float.h> /* For _controlfp_s constants */
  9230. #endif
  9231. #if defined(MA_WIN32)
  9232. #include <windows.h>
  9233. /*
  9234. There's a possibility that WIN32_LEAN_AND_MEAN has been defined which will exclude some symbols
  9235. such as STGM_READ and CLSCTL_ALL. We need to check these and define them ourselves if they're
  9236. unavailable.
  9237. */
  9238. #ifndef STGM_READ
  9239. #define STGM_READ 0x00000000L
  9240. #endif
  9241. #ifndef CLSCTX_ALL
  9242. #define CLSCTX_ALL 23
  9243. #endif
  9244. /* IUnknown is used by both the WASAPI and DirectSound backends. It easier to just declare our version here. */
  9245. typedef struct ma_IUnknown ma_IUnknown;
  9246. #endif
  9247. #if !defined(MA_WIN32)
  9248. #include <sched.h>
  9249. #include <sys/time.h> /* select() (used for ma_sleep()). */
  9250. #include <pthread.h>
  9251. #endif
  9252. #ifdef MA_NX
  9253. #include <time.h> /* For nanosleep() */
  9254. #endif
  9255. #include <sys/stat.h> /* For fstat(), etc. */
  9256. #ifdef MA_EMSCRIPTEN
  9257. #include <emscripten/emscripten.h>
  9258. #endif
  9259. #if !defined(MA_64BIT) && !defined(MA_32BIT)
  9260. #ifdef _WIN32
  9261. #ifdef _WIN64
  9262. #define MA_64BIT
  9263. #else
  9264. #define MA_32BIT
  9265. #endif
  9266. #endif
  9267. #endif
  9268. #if !defined(MA_64BIT) && !defined(MA_32BIT)
  9269. #ifdef __GNUC__
  9270. #ifdef __LP64__
  9271. #define MA_64BIT
  9272. #else
  9273. #define MA_32BIT
  9274. #endif
  9275. #endif
  9276. #endif
  9277. #if !defined(MA_64BIT) && !defined(MA_32BIT)
  9278. #include <stdint.h>
  9279. #if INTPTR_MAX == INT64_MAX
  9280. #define MA_64BIT
  9281. #else
  9282. #define MA_32BIT
  9283. #endif
  9284. #endif
  9285. /* Architecture Detection */
  9286. #if defined(__x86_64__) || defined(_M_X64)
  9287. #define MA_X64
  9288. #elif defined(__i386) || defined(_M_IX86)
  9289. #define MA_X86
  9290. #elif defined(__arm__) || defined(_M_ARM) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
  9291. #define MA_ARM
  9292. #endif
  9293. /* Intrinsics Support */
  9294. #if (defined(MA_X64) || defined(MA_X86)) && !defined(__COSMOPOLITAN__)
  9295. #if defined(_MSC_VER) && !defined(__clang__)
  9296. /* MSVC. */
  9297. #if _MSC_VER >= 1400 && !defined(MA_NO_SSE2) /* 2005 */
  9298. #define MA_SUPPORT_SSE2
  9299. #endif
  9300. /*#if _MSC_VER >= 1600 && !defined(MA_NO_AVX)*/ /* 2010 */
  9301. /* #define MA_SUPPORT_AVX*/
  9302. /*#endif*/
  9303. #if _MSC_VER >= 1700 && !defined(MA_NO_AVX2) /* 2012 */
  9304. #define MA_SUPPORT_AVX2
  9305. #endif
  9306. #else
  9307. /* Assume GNUC-style. */
  9308. #if defined(__SSE2__) && !defined(MA_NO_SSE2)
  9309. #define MA_SUPPORT_SSE2
  9310. #endif
  9311. /*#if defined(__AVX__) && !defined(MA_NO_AVX)*/
  9312. /* #define MA_SUPPORT_AVX*/
  9313. /*#endif*/
  9314. #if defined(__AVX2__) && !defined(MA_NO_AVX2)
  9315. #define MA_SUPPORT_AVX2
  9316. #endif
  9317. #endif
  9318. /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */
  9319. #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
  9320. #if !defined(MA_SUPPORT_SSE2) && !defined(MA_NO_SSE2) && __has_include(<emmintrin.h>)
  9321. #define MA_SUPPORT_SSE2
  9322. #endif
  9323. /*#if !defined(MA_SUPPORT_AVX) && !defined(MA_NO_AVX) && __has_include(<immintrin.h>)*/
  9324. /* #define MA_SUPPORT_AVX*/
  9325. /*#endif*/
  9326. #if !defined(MA_SUPPORT_AVX2) && !defined(MA_NO_AVX2) && __has_include(<immintrin.h>)
  9327. #define MA_SUPPORT_AVX2
  9328. #endif
  9329. #endif
  9330. #if defined(MA_SUPPORT_AVX2) || defined(MA_SUPPORT_AVX)
  9331. #include <immintrin.h>
  9332. #elif defined(MA_SUPPORT_SSE2)
  9333. #include <emmintrin.h>
  9334. #endif
  9335. #endif
  9336. #if defined(MA_ARM)
  9337. #if !defined(MA_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  9338. #define MA_SUPPORT_NEON
  9339. #include <arm_neon.h>
  9340. #endif
  9341. #endif
  9342. /* Begin globally disabled warnings. */
  9343. #if defined(_MSC_VER)
  9344. #pragma warning(push)
  9345. #pragma warning(disable:4752) /* found Intel(R) Advanced Vector Extensions; consider using /arch:AVX */
  9346. #pragma warning(disable:4049) /* compiler limit : terminating line number emission */
  9347. #endif
  9348. #if defined(MA_X64) || defined(MA_X86)
  9349. #if defined(_MSC_VER) && !defined(__clang__)
  9350. #if _MSC_VER >= 1400
  9351. #include <intrin.h>
  9352. static MA_INLINE void ma_cpuid(int info[4], int fid)
  9353. {
  9354. __cpuid(info, fid);
  9355. }
  9356. #else
  9357. #define MA_NO_CPUID
  9358. #endif
  9359. #if _MSC_VER >= 1600 && (defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 160040219)
  9360. static MA_INLINE unsigned __int64 ma_xgetbv(int reg)
  9361. {
  9362. return _xgetbv(reg);
  9363. }
  9364. #else
  9365. #define MA_NO_XGETBV
  9366. #endif
  9367. #elif (defined(__GNUC__) || defined(__clang__)) && !defined(MA_ANDROID)
  9368. static MA_INLINE void ma_cpuid(int info[4], int fid)
  9369. {
  9370. /*
  9371. It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the
  9372. specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for
  9373. supporting different assembly dialects.
  9374. What's basically happening is that we're saving and restoring the ebx register manually.
  9375. */
  9376. #if defined(DRFLAC_X86) && defined(__PIC__)
  9377. __asm__ __volatile__ (
  9378. "xchg{l} {%%}ebx, %k1;"
  9379. "cpuid;"
  9380. "xchg{l} {%%}ebx, %k1;"
  9381. : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  9382. );
  9383. #else
  9384. __asm__ __volatile__ (
  9385. "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  9386. );
  9387. #endif
  9388. }
  9389. static MA_INLINE ma_uint64 ma_xgetbv(int reg)
  9390. {
  9391. unsigned int hi;
  9392. unsigned int lo;
  9393. __asm__ __volatile__ (
  9394. "xgetbv" : "=a"(lo), "=d"(hi) : "c"(reg)
  9395. );
  9396. return ((ma_uint64)hi << 32) | (ma_uint64)lo;
  9397. }
  9398. #else
  9399. #define MA_NO_CPUID
  9400. #define MA_NO_XGETBV
  9401. #endif
  9402. #else
  9403. #define MA_NO_CPUID
  9404. #define MA_NO_XGETBV
  9405. #endif
  9406. static MA_INLINE ma_bool32 ma_has_sse2(void)
  9407. {
  9408. #if defined(MA_SUPPORT_SSE2)
  9409. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_SSE2)
  9410. #if defined(MA_X64)
  9411. return MA_TRUE; /* 64-bit targets always support SSE2. */
  9412. #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
  9413. return MA_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */
  9414. #else
  9415. #if defined(MA_NO_CPUID)
  9416. return MA_FALSE;
  9417. #else
  9418. int info[4];
  9419. ma_cpuid(info, 1);
  9420. return (info[3] & (1 << 26)) != 0;
  9421. #endif
  9422. #endif
  9423. #else
  9424. return MA_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */
  9425. #endif
  9426. #else
  9427. return MA_FALSE; /* No compiler support. */
  9428. #endif
  9429. }
  9430. #if 0
  9431. static MA_INLINE ma_bool32 ma_has_avx()
  9432. {
  9433. #if defined(MA_SUPPORT_AVX)
  9434. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX)
  9435. #if defined(_AVX_) || defined(__AVX__)
  9436. return MA_TRUE; /* If the compiler is allowed to freely generate AVX code we can assume support. */
  9437. #else
  9438. /* AVX requires both CPU and OS support. */
  9439. #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV)
  9440. return MA_FALSE;
  9441. #else
  9442. int info[4];
  9443. ma_cpuid(info, 1);
  9444. if (((info[2] & (1 << 27)) != 0) && ((info[2] & (1 << 28)) != 0)) {
  9445. ma_uint64 xrc = ma_xgetbv(0);
  9446. if ((xrc & 0x06) == 0x06) {
  9447. return MA_TRUE;
  9448. } else {
  9449. return MA_FALSE;
  9450. }
  9451. } else {
  9452. return MA_FALSE;
  9453. }
  9454. #endif
  9455. #endif
  9456. #else
  9457. return MA_FALSE; /* AVX is only supported on x86 and x64 architectures. */
  9458. #endif
  9459. #else
  9460. return MA_FALSE; /* No compiler support. */
  9461. #endif
  9462. }
  9463. #endif
  9464. static MA_INLINE ma_bool32 ma_has_avx2(void)
  9465. {
  9466. #if defined(MA_SUPPORT_AVX2)
  9467. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX2)
  9468. #if defined(_AVX2_) || defined(__AVX2__)
  9469. return MA_TRUE; /* If the compiler is allowed to freely generate AVX2 code we can assume support. */
  9470. #else
  9471. /* AVX2 requires both CPU and OS support. */
  9472. #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV)
  9473. return MA_FALSE;
  9474. #else
  9475. int info1[4];
  9476. int info7[4];
  9477. ma_cpuid(info1, 1);
  9478. ma_cpuid(info7, 7);
  9479. if (((info1[2] & (1 << 27)) != 0) && ((info7[1] & (1 << 5)) != 0)) {
  9480. ma_uint64 xrc = ma_xgetbv(0);
  9481. if ((xrc & 0x06) == 0x06) {
  9482. return MA_TRUE;
  9483. } else {
  9484. return MA_FALSE;
  9485. }
  9486. } else {
  9487. return MA_FALSE;
  9488. }
  9489. #endif
  9490. #endif
  9491. #else
  9492. return MA_FALSE; /* AVX2 is only supported on x86 and x64 architectures. */
  9493. #endif
  9494. #else
  9495. return MA_FALSE; /* No compiler support. */
  9496. #endif
  9497. }
  9498. static MA_INLINE ma_bool32 ma_has_neon(void)
  9499. {
  9500. #if defined(MA_SUPPORT_NEON)
  9501. #if defined(MA_ARM) && !defined(MA_NO_NEON)
  9502. #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  9503. return MA_TRUE; /* If the compiler is allowed to freely generate NEON code we can assume support. */
  9504. #else
  9505. /* TODO: Runtime check. */
  9506. return MA_FALSE;
  9507. #endif
  9508. #else
  9509. return MA_FALSE; /* NEON is only supported on ARM architectures. */
  9510. #endif
  9511. #else
  9512. return MA_FALSE; /* No compiler support. */
  9513. #endif
  9514. }
  9515. #if defined(__has_builtin)
  9516. #define MA_COMPILER_HAS_BUILTIN(x) __has_builtin(x)
  9517. #else
  9518. #define MA_COMPILER_HAS_BUILTIN(x) 0
  9519. #endif
  9520. #ifndef MA_ASSUME
  9521. #if MA_COMPILER_HAS_BUILTIN(__builtin_assume)
  9522. #define MA_ASSUME(x) __builtin_assume(x)
  9523. #elif MA_COMPILER_HAS_BUILTIN(__builtin_unreachable)
  9524. #define MA_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while (0)
  9525. #elif defined(_MSC_VER)
  9526. #define MA_ASSUME(x) __assume(x)
  9527. #else
  9528. #define MA_ASSUME(x) (void)(x)
  9529. #endif
  9530. #endif
  9531. #ifndef MA_RESTRICT
  9532. #if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER)
  9533. #define MA_RESTRICT __restrict
  9534. #else
  9535. #define MA_RESTRICT
  9536. #endif
  9537. #endif
  9538. #if defined(_MSC_VER) && _MSC_VER >= 1400
  9539. #define MA_HAS_BYTESWAP16_INTRINSIC
  9540. #define MA_HAS_BYTESWAP32_INTRINSIC
  9541. #define MA_HAS_BYTESWAP64_INTRINSIC
  9542. #elif defined(__clang__)
  9543. #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap16)
  9544. #define MA_HAS_BYTESWAP16_INTRINSIC
  9545. #endif
  9546. #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap32)
  9547. #define MA_HAS_BYTESWAP32_INTRINSIC
  9548. #endif
  9549. #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap64)
  9550. #define MA_HAS_BYTESWAP64_INTRINSIC
  9551. #endif
  9552. #elif defined(__GNUC__)
  9553. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  9554. #define MA_HAS_BYTESWAP32_INTRINSIC
  9555. #define MA_HAS_BYTESWAP64_INTRINSIC
  9556. #endif
  9557. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  9558. #define MA_HAS_BYTESWAP16_INTRINSIC
  9559. #endif
  9560. #endif
  9561. static MA_INLINE ma_bool32 ma_is_little_endian(void)
  9562. {
  9563. #if defined(MA_X86) || defined(MA_X64)
  9564. return MA_TRUE;
  9565. #else
  9566. int n = 1;
  9567. return (*(char*)&n) == 1;
  9568. #endif
  9569. }
  9570. static MA_INLINE ma_bool32 ma_is_big_endian(void)
  9571. {
  9572. return !ma_is_little_endian();
  9573. }
  9574. static MA_INLINE ma_uint32 ma_swap_endian_uint32(ma_uint32 n)
  9575. {
  9576. #ifdef MA_HAS_BYTESWAP32_INTRINSIC
  9577. #if defined(_MSC_VER)
  9578. return _byteswap_ulong(n);
  9579. #elif defined(__GNUC__) || defined(__clang__)
  9580. #if defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(MA_64BIT) /* <-- 64-bit inline assembly has not been tested, so disabling for now. */
  9581. /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */
  9582. ma_uint32 r;
  9583. __asm__ __volatile__ (
  9584. #if defined(MA_64BIT)
  9585. "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n) /* <-- This is untested. If someone in the community could test this, that would be appreciated! */
  9586. #else
  9587. "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  9588. #endif
  9589. );
  9590. return r;
  9591. #else
  9592. return __builtin_bswap32(n);
  9593. #endif
  9594. #else
  9595. #error "This compiler does not support the byte swap intrinsic."
  9596. #endif
  9597. #else
  9598. return ((n & 0xFF000000) >> 24) |
  9599. ((n & 0x00FF0000) >> 8) |
  9600. ((n & 0x0000FF00) << 8) |
  9601. ((n & 0x000000FF) << 24);
  9602. #endif
  9603. }
  9604. #if !defined(MA_EMSCRIPTEN)
  9605. #ifdef MA_WIN32
  9606. static void ma_sleep__win32(ma_uint32 milliseconds)
  9607. {
  9608. Sleep((DWORD)milliseconds);
  9609. }
  9610. #endif
  9611. #ifdef MA_POSIX
  9612. static void ma_sleep__posix(ma_uint32 milliseconds)
  9613. {
  9614. #ifdef MA_EMSCRIPTEN
  9615. (void)milliseconds;
  9616. MA_ASSERT(MA_FALSE); /* The Emscripten build should never sleep. */
  9617. #else
  9618. #if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L) || defined(MA_NX)
  9619. struct timespec ts;
  9620. ts.tv_sec = milliseconds / 1000;
  9621. ts.tv_nsec = milliseconds % 1000 * 1000000;
  9622. nanosleep(&ts, NULL);
  9623. #else
  9624. struct timeval tv;
  9625. tv.tv_sec = milliseconds / 1000;
  9626. tv.tv_usec = milliseconds % 1000 * 1000;
  9627. select(0, NULL, NULL, NULL, &tv);
  9628. #endif
  9629. #endif
  9630. }
  9631. #endif
  9632. static MA_INLINE void ma_sleep(ma_uint32 milliseconds)
  9633. {
  9634. #ifdef MA_WIN32
  9635. ma_sleep__win32(milliseconds);
  9636. #endif
  9637. #ifdef MA_POSIX
  9638. ma_sleep__posix(milliseconds);
  9639. #endif
  9640. }
  9641. #endif
  9642. static MA_INLINE void ma_yield(void)
  9643. {
  9644. #if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
  9645. /* x86/x64 */
  9646. #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DMC__)) && !defined(__clang__)
  9647. #if _MSC_VER >= 1400
  9648. _mm_pause();
  9649. #else
  9650. #if defined(__DMC__)
  9651. /* Digital Mars does not recognize the PAUSE opcode. Fall back to NOP. */
  9652. __asm nop;
  9653. #else
  9654. __asm pause;
  9655. #endif
  9656. #endif
  9657. #else
  9658. __asm__ __volatile__ ("pause");
  9659. #endif
  9660. #elif (defined(__arm__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7) || defined(_M_ARM64) || (defined(_M_ARM) && _M_ARM >= 7) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__)
  9661. /* ARM */
  9662. #if defined(_MSC_VER)
  9663. /* Apparently there is a __yield() intrinsic that's compatible with ARM, but I cannot find documentation for it nor can I find where it's declared. */
  9664. __yield();
  9665. #else
  9666. __asm__ __volatile__ ("yield"); /* ARMv6K/ARMv6T2 and above. */
  9667. #endif
  9668. #else
  9669. /* Unknown or unsupported architecture. No-op. */
  9670. #endif
  9671. }
  9672. #define MA_MM_DENORMALS_ZERO_MASK 0x0040
  9673. #define MA_MM_FLUSH_ZERO_MASK 0x8000
  9674. static MA_INLINE unsigned int ma_disable_denormals(void)
  9675. {
  9676. unsigned int prevState;
  9677. #if defined(_MSC_VER)
  9678. {
  9679. /*
  9680. Older versions of Visual Studio don't support the "safe" versions of _controlfp_s(). I don't
  9681. know which version of Visual Studio first added support for _controlfp_s(), but I do know
  9682. that VC6 lacks support. _MSC_VER = 1200 is VC6, but if you get compilation errors on older
  9683. versions of Visual Studio, let me know and I'll make the necessary adjustment.
  9684. */
  9685. #if _MSC_VER <= 1200
  9686. {
  9687. prevState = _statusfp();
  9688. _controlfp(prevState | _DN_FLUSH, _MCW_DN);
  9689. }
  9690. #else
  9691. {
  9692. unsigned int unused;
  9693. _controlfp_s(&prevState, 0, 0);
  9694. _controlfp_s(&unused, prevState | _DN_FLUSH, _MCW_DN);
  9695. }
  9696. #endif
  9697. }
  9698. #elif defined(MA_X86) || defined(MA_X64)
  9699. {
  9700. #if defined(__SSE2__) && !(defined(__TINYC__) || defined(__WATCOMC__) || defined(__COSMOPOLITAN__)) /* <-- Add compilers that lack support for _mm_getcsr() and _mm_setcsr() to this list. */
  9701. {
  9702. prevState = _mm_getcsr();
  9703. _mm_setcsr(prevState | MA_MM_DENORMALS_ZERO_MASK | MA_MM_FLUSH_ZERO_MASK);
  9704. }
  9705. #else
  9706. {
  9707. /* x88/64, but no support for _mm_getcsr()/_mm_setcsr(). May need to fall back to inlined assembly here. */
  9708. prevState = 0;
  9709. }
  9710. #endif
  9711. }
  9712. #else
  9713. {
  9714. /* Unknown or unsupported architecture. No-op. */
  9715. prevState = 0;
  9716. }
  9717. #endif
  9718. return prevState;
  9719. }
  9720. static MA_INLINE void ma_restore_denormals(unsigned int prevState)
  9721. {
  9722. #if defined(_MSC_VER)
  9723. {
  9724. /* Older versions of Visual Studio do not support _controlfp_s(). See ma_disable_denormals(). */
  9725. #if _MSC_VER <= 1200
  9726. {
  9727. _controlfp(prevState, _MCW_DN);
  9728. }
  9729. #else
  9730. {
  9731. unsigned int unused;
  9732. _controlfp_s(&unused, prevState, _MCW_DN);
  9733. }
  9734. #endif
  9735. }
  9736. #elif defined(MA_X86) || defined(MA_X64)
  9737. {
  9738. #if defined(__SSE2__) && !(defined(__TINYC__) || defined(__WATCOMC__) || defined(__COSMOPOLITAN__)) /* <-- Add compilers that lack support for _mm_getcsr() and _mm_setcsr() to this list. */
  9739. {
  9740. _mm_setcsr(prevState);
  9741. }
  9742. #else
  9743. {
  9744. /* x88/64, but no support for _mm_getcsr()/_mm_setcsr(). May need to fall back to inlined assembly here. */
  9745. (void)prevState;
  9746. }
  9747. #endif
  9748. }
  9749. #else
  9750. {
  9751. /* Unknown or unsupported architecture. No-op. */
  9752. (void)prevState;
  9753. }
  9754. #endif
  9755. }
  9756. #ifdef MA_ANDROID
  9757. #include <sys/system_properties.h>
  9758. int ma_android_sdk_version()
  9759. {
  9760. char sdkVersion[PROP_VALUE_MAX + 1] = {0, };
  9761. if (__system_property_get("ro.build.version.sdk", sdkVersion)) {
  9762. return atoi(sdkVersion);
  9763. }
  9764. return 0;
  9765. }
  9766. #endif
  9767. #ifndef MA_COINIT_VALUE
  9768. #define MA_COINIT_VALUE 0 /* 0 = COINIT_MULTITHREADED */
  9769. #endif
  9770. #ifndef MA_FLT_MAX
  9771. #ifdef FLT_MAX
  9772. #define MA_FLT_MAX FLT_MAX
  9773. #else
  9774. #define MA_FLT_MAX 3.402823466e+38F
  9775. #endif
  9776. #endif
  9777. #ifndef MA_PI
  9778. #define MA_PI 3.14159265358979323846264f
  9779. #endif
  9780. #ifndef MA_PI_D
  9781. #define MA_PI_D 3.14159265358979323846264
  9782. #endif
  9783. #ifndef MA_TAU
  9784. #define MA_TAU 6.28318530717958647693f
  9785. #endif
  9786. #ifndef MA_TAU_D
  9787. #define MA_TAU_D 6.28318530717958647693
  9788. #endif
  9789. /* The default format when ma_format_unknown (0) is requested when initializing a device. */
  9790. #ifndef MA_DEFAULT_FORMAT
  9791. #define MA_DEFAULT_FORMAT ma_format_f32
  9792. #endif
  9793. /* The default channel count to use when 0 is used when initializing a device. */
  9794. #ifndef MA_DEFAULT_CHANNELS
  9795. #define MA_DEFAULT_CHANNELS 2
  9796. #endif
  9797. /* The default sample rate to use when 0 is used when initializing a device. */
  9798. #ifndef MA_DEFAULT_SAMPLE_RATE
  9799. #define MA_DEFAULT_SAMPLE_RATE 48000
  9800. #endif
  9801. /* Default periods when none is specified in ma_device_init(). More periods means more work on the CPU. */
  9802. #ifndef MA_DEFAULT_PERIODS
  9803. #define MA_DEFAULT_PERIODS 3
  9804. #endif
  9805. /* The default period size in milliseconds for low latency mode. */
  9806. #ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY
  9807. #define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY 10
  9808. #endif
  9809. /* The default buffer size in milliseconds for conservative mode. */
  9810. #ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE
  9811. #define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE 100
  9812. #endif
  9813. /* The default LPF filter order for linear resampling. Note that this is clamped to MA_MAX_FILTER_ORDER. */
  9814. #ifndef MA_DEFAULT_RESAMPLER_LPF_ORDER
  9815. #if MA_MAX_FILTER_ORDER >= 4
  9816. #define MA_DEFAULT_RESAMPLER_LPF_ORDER 4
  9817. #else
  9818. #define MA_DEFAULT_RESAMPLER_LPF_ORDER MA_MAX_FILTER_ORDER
  9819. #endif
  9820. #endif
  9821. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  9822. #pragma GCC diagnostic push
  9823. #pragma GCC diagnostic ignored "-Wunused-variable"
  9824. #endif
  9825. /* Standard sample rates, in order of priority. */
  9826. static ma_uint32 g_maStandardSampleRatePriorities[] = {
  9827. (ma_uint32)ma_standard_sample_rate_48000,
  9828. (ma_uint32)ma_standard_sample_rate_44100,
  9829. (ma_uint32)ma_standard_sample_rate_32000,
  9830. (ma_uint32)ma_standard_sample_rate_24000,
  9831. (ma_uint32)ma_standard_sample_rate_22050,
  9832. (ma_uint32)ma_standard_sample_rate_88200,
  9833. (ma_uint32)ma_standard_sample_rate_96000,
  9834. (ma_uint32)ma_standard_sample_rate_176400,
  9835. (ma_uint32)ma_standard_sample_rate_192000,
  9836. (ma_uint32)ma_standard_sample_rate_16000,
  9837. (ma_uint32)ma_standard_sample_rate_11025,
  9838. (ma_uint32)ma_standard_sample_rate_8000,
  9839. (ma_uint32)ma_standard_sample_rate_352800,
  9840. (ma_uint32)ma_standard_sample_rate_384000
  9841. };
  9842. static MA_INLINE ma_bool32 ma_is_standard_sample_rate(ma_uint32 sampleRate)
  9843. {
  9844. ma_uint32 iSampleRate;
  9845. for (iSampleRate = 0; iSampleRate < sizeof(g_maStandardSampleRatePriorities) / sizeof(g_maStandardSampleRatePriorities[0]); iSampleRate += 1) {
  9846. if (g_maStandardSampleRatePriorities[iSampleRate] == sampleRate) {
  9847. return MA_TRUE;
  9848. }
  9849. }
  9850. /* Getting here means the sample rate is not supported. */
  9851. return MA_FALSE;
  9852. }
  9853. static ma_format g_maFormatPriorities[] = {
  9854. ma_format_s16, /* Most common */
  9855. ma_format_f32,
  9856. /*ma_format_s24_32,*/ /* Clean alignment */
  9857. ma_format_s32,
  9858. ma_format_s24, /* Unclean alignment */
  9859. ma_format_u8 /* Low quality */
  9860. };
  9861. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  9862. #pragma GCC diagnostic pop
  9863. #endif
  9864. MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision)
  9865. {
  9866. if (pMajor) {
  9867. *pMajor = MA_VERSION_MAJOR;
  9868. }
  9869. if (pMinor) {
  9870. *pMinor = MA_VERSION_MINOR;
  9871. }
  9872. if (pRevision) {
  9873. *pRevision = MA_VERSION_REVISION;
  9874. }
  9875. }
  9876. MA_API const char* ma_version_string(void)
  9877. {
  9878. return MA_VERSION_STRING;
  9879. }
  9880. /******************************************************************************
  9881. Standard Library Stuff
  9882. ******************************************************************************/
  9883. #ifndef MA_ASSERT
  9884. #define MA_ASSERT(condition) assert(condition)
  9885. #endif
  9886. #ifndef MA_MALLOC
  9887. #define MA_MALLOC(sz) malloc((sz))
  9888. #endif
  9889. #ifndef MA_REALLOC
  9890. #define MA_REALLOC(p, sz) realloc((p), (sz))
  9891. #endif
  9892. #ifndef MA_FREE
  9893. #define MA_FREE(p) free((p))
  9894. #endif
  9895. static MA_INLINE void ma_zero_memory_default(void* p, size_t sz)
  9896. {
  9897. if (p == NULL) {
  9898. MA_ASSERT(sz == 0); /* If this is triggered there's an error with the calling code. */
  9899. return;
  9900. }
  9901. if (sz > 0) {
  9902. memset(p, 0, sz);
  9903. }
  9904. }
  9905. #ifndef MA_ZERO_MEMORY
  9906. #define MA_ZERO_MEMORY(p, sz) ma_zero_memory_default((p), (sz))
  9907. #endif
  9908. #ifndef MA_COPY_MEMORY
  9909. #define MA_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  9910. #endif
  9911. #ifndef MA_MOVE_MEMORY
  9912. #define MA_MOVE_MEMORY(dst, src, sz) memmove((dst), (src), (sz))
  9913. #endif
  9914. #define MA_ZERO_OBJECT(p) MA_ZERO_MEMORY((p), sizeof(*(p)))
  9915. #define ma_countof(x) (sizeof(x) / sizeof(x[0]))
  9916. #define ma_max(x, y) (((x) > (y)) ? (x) : (y))
  9917. #define ma_min(x, y) (((x) < (y)) ? (x) : (y))
  9918. #define ma_abs(x) (((x) > 0) ? (x) : -(x))
  9919. #define ma_clamp(x, lo, hi) (ma_max(lo, ma_min(x, hi)))
  9920. #define ma_offset_ptr(p, offset) (((ma_uint8*)(p)) + (offset))
  9921. #define ma_align(x, a) ((x + (a-1)) & ~(a-1))
  9922. #define ma_align_64(x) ma_align(x, 8)
  9923. #define ma_buffer_frame_capacity(buffer, channels, format) (sizeof(buffer) / ma_get_bytes_per_sample(format) / (channels))
  9924. static MA_INLINE double ma_sind(double x)
  9925. {
  9926. /* TODO: Implement custom sin(x). */
  9927. return sin(x);
  9928. }
  9929. static MA_INLINE double ma_expd(double x)
  9930. {
  9931. /* TODO: Implement custom exp(x). */
  9932. return exp(x);
  9933. }
  9934. static MA_INLINE double ma_logd(double x)
  9935. {
  9936. /* TODO: Implement custom log(x). */
  9937. return log(x);
  9938. }
  9939. static MA_INLINE double ma_powd(double x, double y)
  9940. {
  9941. /* TODO: Implement custom pow(x, y). */
  9942. return pow(x, y);
  9943. }
  9944. static MA_INLINE double ma_sqrtd(double x)
  9945. {
  9946. /* TODO: Implement custom sqrt(x). */
  9947. return sqrt(x);
  9948. }
  9949. static MA_INLINE float ma_rsqrtf(float x)
  9950. {
  9951. #if defined(MA_SUPPORT_SSE2) && !defined(MA_NO_SSE2) && (defined(MA_X64) || (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__))
  9952. {
  9953. /*
  9954. For SSE we can use RSQRTSS.
  9955. This Stack Overflow post suggests that compilers don't necessarily generate optimal code
  9956. when using intrinsics:
  9957. https://web.archive.org/web/20221211012522/https://stackoverflow.com/questions/32687079/getting-fewest-instructions-for-rsqrtss-wrapper
  9958. I'm going to do something similar here, but a bit simpler.
  9959. */
  9960. #if defined(__GNUC__) || defined(__clang__)
  9961. {
  9962. float result;
  9963. __asm__ __volatile__("rsqrtss %1, %0" : "=x"(result) : "x"(x));
  9964. return result;
  9965. }
  9966. #else
  9967. {
  9968. return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ps1(x)));
  9969. }
  9970. #endif
  9971. }
  9972. #else
  9973. {
  9974. return 1 / (float)ma_sqrtd(x);
  9975. }
  9976. #endif
  9977. }
  9978. static MA_INLINE float ma_sinf(float x)
  9979. {
  9980. return (float)ma_sind((float)x);
  9981. }
  9982. static MA_INLINE double ma_cosd(double x)
  9983. {
  9984. return ma_sind((MA_PI_D*0.5) - x);
  9985. }
  9986. static MA_INLINE float ma_cosf(float x)
  9987. {
  9988. return (float)ma_cosd((float)x);
  9989. }
  9990. static MA_INLINE double ma_log10d(double x)
  9991. {
  9992. return ma_logd(x) * 0.43429448190325182765;
  9993. }
  9994. static MA_INLINE float ma_powf(float x, float y)
  9995. {
  9996. return (float)ma_powd((double)x, (double)y);
  9997. }
  9998. static MA_INLINE float ma_log10f(float x)
  9999. {
  10000. return (float)ma_log10d((double)x);
  10001. }
  10002. static MA_INLINE double ma_degrees_to_radians(double degrees)
  10003. {
  10004. return degrees * 0.01745329252;
  10005. }
  10006. static MA_INLINE double ma_radians_to_degrees(double radians)
  10007. {
  10008. return radians * 57.295779512896;
  10009. }
  10010. static MA_INLINE float ma_degrees_to_radians_f(float degrees)
  10011. {
  10012. return degrees * 0.01745329252f;
  10013. }
  10014. static MA_INLINE float ma_radians_to_degrees_f(float radians)
  10015. {
  10016. return radians * 57.295779512896f;
  10017. }
  10018. /*
  10019. Return Values:
  10020. 0: Success
  10021. 22: EINVAL
  10022. 34: ERANGE
  10023. Not using symbolic constants for errors because I want to avoid #including errno.h
  10024. */
  10025. MA_API int ma_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src)
  10026. {
  10027. size_t i;
  10028. if (dst == 0) {
  10029. return 22;
  10030. }
  10031. if (dstSizeInBytes == 0) {
  10032. return 34;
  10033. }
  10034. if (src == 0) {
  10035. dst[0] = '\0';
  10036. return 22;
  10037. }
  10038. for (i = 0; i < dstSizeInBytes && src[i] != '\0'; ++i) {
  10039. dst[i] = src[i];
  10040. }
  10041. if (i < dstSizeInBytes) {
  10042. dst[i] = '\0';
  10043. return 0;
  10044. }
  10045. dst[0] = '\0';
  10046. return 34;
  10047. }
  10048. MA_API int ma_wcscpy_s(wchar_t* dst, size_t dstCap, const wchar_t* src)
  10049. {
  10050. size_t i;
  10051. if (dst == 0) {
  10052. return 22;
  10053. }
  10054. if (dstCap == 0) {
  10055. return 34;
  10056. }
  10057. if (src == 0) {
  10058. dst[0] = '\0';
  10059. return 22;
  10060. }
  10061. for (i = 0; i < dstCap && src[i] != '\0'; ++i) {
  10062. dst[i] = src[i];
  10063. }
  10064. if (i < dstCap) {
  10065. dst[i] = '\0';
  10066. return 0;
  10067. }
  10068. dst[0] = '\0';
  10069. return 34;
  10070. }
  10071. MA_API int ma_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
  10072. {
  10073. size_t maxcount;
  10074. size_t i;
  10075. if (dst == 0) {
  10076. return 22;
  10077. }
  10078. if (dstSizeInBytes == 0) {
  10079. return 34;
  10080. }
  10081. if (src == 0) {
  10082. dst[0] = '\0';
  10083. return 22;
  10084. }
  10085. maxcount = count;
  10086. if (count == ((size_t)-1) || count >= dstSizeInBytes) { /* -1 = _TRUNCATE */
  10087. maxcount = dstSizeInBytes - 1;
  10088. }
  10089. for (i = 0; i < maxcount && src[i] != '\0'; ++i) {
  10090. dst[i] = src[i];
  10091. }
  10092. if (src[i] == '\0' || i == count || count == ((size_t)-1)) {
  10093. dst[i] = '\0';
  10094. return 0;
  10095. }
  10096. dst[0] = '\0';
  10097. return 34;
  10098. }
  10099. MA_API int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src)
  10100. {
  10101. char* dstorig;
  10102. if (dst == 0) {
  10103. return 22;
  10104. }
  10105. if (dstSizeInBytes == 0) {
  10106. return 34;
  10107. }
  10108. if (src == 0) {
  10109. dst[0] = '\0';
  10110. return 22;
  10111. }
  10112. dstorig = dst;
  10113. while (dstSizeInBytes > 0 && dst[0] != '\0') {
  10114. dst += 1;
  10115. dstSizeInBytes -= 1;
  10116. }
  10117. if (dstSizeInBytes == 0) {
  10118. return 22; /* Unterminated. */
  10119. }
  10120. while (dstSizeInBytes > 0 && src[0] != '\0') {
  10121. *dst++ = *src++;
  10122. dstSizeInBytes -= 1;
  10123. }
  10124. if (dstSizeInBytes > 0) {
  10125. dst[0] = '\0';
  10126. } else {
  10127. dstorig[0] = '\0';
  10128. return 34;
  10129. }
  10130. return 0;
  10131. }
  10132. MA_API int ma_strncat_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
  10133. {
  10134. char* dstorig;
  10135. if (dst == 0) {
  10136. return 22;
  10137. }
  10138. if (dstSizeInBytes == 0) {
  10139. return 34;
  10140. }
  10141. if (src == 0) {
  10142. return 22;
  10143. }
  10144. dstorig = dst;
  10145. while (dstSizeInBytes > 0 && dst[0] != '\0') {
  10146. dst += 1;
  10147. dstSizeInBytes -= 1;
  10148. }
  10149. if (dstSizeInBytes == 0) {
  10150. return 22; /* Unterminated. */
  10151. }
  10152. if (count == ((size_t)-1)) { /* _TRUNCATE */
  10153. count = dstSizeInBytes - 1;
  10154. }
  10155. while (dstSizeInBytes > 0 && src[0] != '\0' && count > 0) {
  10156. *dst++ = *src++;
  10157. dstSizeInBytes -= 1;
  10158. count -= 1;
  10159. }
  10160. if (dstSizeInBytes > 0) {
  10161. dst[0] = '\0';
  10162. } else {
  10163. dstorig[0] = '\0';
  10164. return 34;
  10165. }
  10166. return 0;
  10167. }
  10168. MA_API int ma_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix)
  10169. {
  10170. int sign;
  10171. unsigned int valueU;
  10172. char* dstEnd;
  10173. if (dst == NULL || dstSizeInBytes == 0) {
  10174. return 22;
  10175. }
  10176. if (radix < 2 || radix > 36) {
  10177. dst[0] = '\0';
  10178. return 22;
  10179. }
  10180. sign = (value < 0 && radix == 10) ? -1 : 1; /* The negative sign is only used when the base is 10. */
  10181. if (value < 0) {
  10182. valueU = -value;
  10183. } else {
  10184. valueU = value;
  10185. }
  10186. dstEnd = dst;
  10187. do
  10188. {
  10189. int remainder = valueU % radix;
  10190. if (remainder > 9) {
  10191. *dstEnd = (char)((remainder - 10) + 'a');
  10192. } else {
  10193. *dstEnd = (char)(remainder + '0');
  10194. }
  10195. dstEnd += 1;
  10196. dstSizeInBytes -= 1;
  10197. valueU /= radix;
  10198. } while (dstSizeInBytes > 0 && valueU > 0);
  10199. if (dstSizeInBytes == 0) {
  10200. dst[0] = '\0';
  10201. return 22; /* Ran out of room in the output buffer. */
  10202. }
  10203. if (sign < 0) {
  10204. *dstEnd++ = '-';
  10205. dstSizeInBytes -= 1;
  10206. }
  10207. if (dstSizeInBytes == 0) {
  10208. dst[0] = '\0';
  10209. return 22; /* Ran out of room in the output buffer. */
  10210. }
  10211. *dstEnd = '\0';
  10212. /* At this point the string will be reversed. */
  10213. dstEnd -= 1;
  10214. while (dst < dstEnd) {
  10215. char temp = *dst;
  10216. *dst = *dstEnd;
  10217. *dstEnd = temp;
  10218. dst += 1;
  10219. dstEnd -= 1;
  10220. }
  10221. return 0;
  10222. }
  10223. MA_API int ma_strcmp(const char* str1, const char* str2)
  10224. {
  10225. if (str1 == str2) return 0;
  10226. /* These checks differ from the standard implementation. It's not important, but I prefer it just for sanity. */
  10227. if (str1 == NULL) return -1;
  10228. if (str2 == NULL) return 1;
  10229. for (;;) {
  10230. if (str1[0] == '\0') {
  10231. break;
  10232. }
  10233. if (str1[0] != str2[0]) {
  10234. break;
  10235. }
  10236. str1 += 1;
  10237. str2 += 1;
  10238. }
  10239. return ((unsigned char*)str1)[0] - ((unsigned char*)str2)[0];
  10240. }
  10241. MA_API int ma_strappend(char* dst, size_t dstSize, const char* srcA, const char* srcB)
  10242. {
  10243. int result;
  10244. result = ma_strncpy_s(dst, dstSize, srcA, (size_t)-1);
  10245. if (result != 0) {
  10246. return result;
  10247. }
  10248. result = ma_strncat_s(dst, dstSize, srcB, (size_t)-1);
  10249. if (result != 0) {
  10250. return result;
  10251. }
  10252. return result;
  10253. }
  10254. MA_API char* ma_copy_string(const char* src, const ma_allocation_callbacks* pAllocationCallbacks)
  10255. {
  10256. size_t sz;
  10257. char* dst;
  10258. if (src == NULL) {
  10259. return NULL;
  10260. }
  10261. sz = strlen(src)+1;
  10262. dst = (char*)ma_malloc(sz, pAllocationCallbacks);
  10263. if (dst == NULL) {
  10264. return NULL;
  10265. }
  10266. ma_strcpy_s(dst, sz, src);
  10267. return dst;
  10268. }
  10269. MA_API wchar_t* ma_copy_string_w(const wchar_t* src, const ma_allocation_callbacks* pAllocationCallbacks)
  10270. {
  10271. size_t sz = wcslen(src)+1;
  10272. wchar_t* dst = (wchar_t*)ma_malloc(sz * sizeof(*dst), pAllocationCallbacks);
  10273. if (dst == NULL) {
  10274. return NULL;
  10275. }
  10276. ma_wcscpy_s(dst, sz, src);
  10277. return dst;
  10278. }
  10279. #include <errno.h>
  10280. static ma_result ma_result_from_errno(int e)
  10281. {
  10282. if (e == 0) {
  10283. return MA_SUCCESS;
  10284. }
  10285. #ifdef EPERM
  10286. else if (e == EPERM) { return MA_INVALID_OPERATION; }
  10287. #endif
  10288. #ifdef ENOENT
  10289. else if (e == ENOENT) { return MA_DOES_NOT_EXIST; }
  10290. #endif
  10291. #ifdef ESRCH
  10292. else if (e == ESRCH) { return MA_DOES_NOT_EXIST; }
  10293. #endif
  10294. #ifdef EINTR
  10295. else if (e == EINTR) { return MA_INTERRUPT; }
  10296. #endif
  10297. #ifdef EIO
  10298. else if (e == EIO) { return MA_IO_ERROR; }
  10299. #endif
  10300. #ifdef ENXIO
  10301. else if (e == ENXIO) { return MA_DOES_NOT_EXIST; }
  10302. #endif
  10303. #ifdef E2BIG
  10304. else if (e == E2BIG) { return MA_INVALID_ARGS; }
  10305. #endif
  10306. #ifdef ENOEXEC
  10307. else if (e == ENOEXEC) { return MA_INVALID_FILE; }
  10308. #endif
  10309. #ifdef EBADF
  10310. else if (e == EBADF) { return MA_INVALID_FILE; }
  10311. #endif
  10312. #ifdef ECHILD
  10313. else if (e == ECHILD) { return MA_ERROR; }
  10314. #endif
  10315. #ifdef EAGAIN
  10316. else if (e == EAGAIN) { return MA_UNAVAILABLE; }
  10317. #endif
  10318. #ifdef ENOMEM
  10319. else if (e == ENOMEM) { return MA_OUT_OF_MEMORY; }
  10320. #endif
  10321. #ifdef EACCES
  10322. else if (e == EACCES) { return MA_ACCESS_DENIED; }
  10323. #endif
  10324. #ifdef EFAULT
  10325. else if (e == EFAULT) { return MA_BAD_ADDRESS; }
  10326. #endif
  10327. #ifdef ENOTBLK
  10328. else if (e == ENOTBLK) { return MA_ERROR; }
  10329. #endif
  10330. #ifdef EBUSY
  10331. else if (e == EBUSY) { return MA_BUSY; }
  10332. #endif
  10333. #ifdef EEXIST
  10334. else if (e == EEXIST) { return MA_ALREADY_EXISTS; }
  10335. #endif
  10336. #ifdef EXDEV
  10337. else if (e == EXDEV) { return MA_ERROR; }
  10338. #endif
  10339. #ifdef ENODEV
  10340. else if (e == ENODEV) { return MA_DOES_NOT_EXIST; }
  10341. #endif
  10342. #ifdef ENOTDIR
  10343. else if (e == ENOTDIR) { return MA_NOT_DIRECTORY; }
  10344. #endif
  10345. #ifdef EISDIR
  10346. else if (e == EISDIR) { return MA_IS_DIRECTORY; }
  10347. #endif
  10348. #ifdef EINVAL
  10349. else if (e == EINVAL) { return MA_INVALID_ARGS; }
  10350. #endif
  10351. #ifdef ENFILE
  10352. else if (e == ENFILE) { return MA_TOO_MANY_OPEN_FILES; }
  10353. #endif
  10354. #ifdef EMFILE
  10355. else if (e == EMFILE) { return MA_TOO_MANY_OPEN_FILES; }
  10356. #endif
  10357. #ifdef ENOTTY
  10358. else if (e == ENOTTY) { return MA_INVALID_OPERATION; }
  10359. #endif
  10360. #ifdef ETXTBSY
  10361. else if (e == ETXTBSY) { return MA_BUSY; }
  10362. #endif
  10363. #ifdef EFBIG
  10364. else if (e == EFBIG) { return MA_TOO_BIG; }
  10365. #endif
  10366. #ifdef ENOSPC
  10367. else if (e == ENOSPC) { return MA_NO_SPACE; }
  10368. #endif
  10369. #ifdef ESPIPE
  10370. else if (e == ESPIPE) { return MA_BAD_SEEK; }
  10371. #endif
  10372. #ifdef EROFS
  10373. else if (e == EROFS) { return MA_ACCESS_DENIED; }
  10374. #endif
  10375. #ifdef EMLINK
  10376. else if (e == EMLINK) { return MA_TOO_MANY_LINKS; }
  10377. #endif
  10378. #ifdef EPIPE
  10379. else if (e == EPIPE) { return MA_BAD_PIPE; }
  10380. #endif
  10381. #ifdef EDOM
  10382. else if (e == EDOM) { return MA_OUT_OF_RANGE; }
  10383. #endif
  10384. #ifdef ERANGE
  10385. else if (e == ERANGE) { return MA_OUT_OF_RANGE; }
  10386. #endif
  10387. #ifdef EDEADLK
  10388. else if (e == EDEADLK) { return MA_DEADLOCK; }
  10389. #endif
  10390. #ifdef ENAMETOOLONG
  10391. else if (e == ENAMETOOLONG) { return MA_PATH_TOO_LONG; }
  10392. #endif
  10393. #ifdef ENOLCK
  10394. else if (e == ENOLCK) { return MA_ERROR; }
  10395. #endif
  10396. #ifdef ENOSYS
  10397. else if (e == ENOSYS) { return MA_NOT_IMPLEMENTED; }
  10398. #endif
  10399. #ifdef ENOTEMPTY
  10400. else if (e == ENOTEMPTY) { return MA_DIRECTORY_NOT_EMPTY; }
  10401. #endif
  10402. #ifdef ELOOP
  10403. else if (e == ELOOP) { return MA_TOO_MANY_LINKS; }
  10404. #endif
  10405. #ifdef ENOMSG
  10406. else if (e == ENOMSG) { return MA_NO_MESSAGE; }
  10407. #endif
  10408. #ifdef EIDRM
  10409. else if (e == EIDRM) { return MA_ERROR; }
  10410. #endif
  10411. #ifdef ECHRNG
  10412. else if (e == ECHRNG) { return MA_ERROR; }
  10413. #endif
  10414. #ifdef EL2NSYNC
  10415. else if (e == EL2NSYNC) { return MA_ERROR; }
  10416. #endif
  10417. #ifdef EL3HLT
  10418. else if (e == EL3HLT) { return MA_ERROR; }
  10419. #endif
  10420. #ifdef EL3RST
  10421. else if (e == EL3RST) { return MA_ERROR; }
  10422. #endif
  10423. #ifdef ELNRNG
  10424. else if (e == ELNRNG) { return MA_OUT_OF_RANGE; }
  10425. #endif
  10426. #ifdef EUNATCH
  10427. else if (e == EUNATCH) { return MA_ERROR; }
  10428. #endif
  10429. #ifdef ENOCSI
  10430. else if (e == ENOCSI) { return MA_ERROR; }
  10431. #endif
  10432. #ifdef EL2HLT
  10433. else if (e == EL2HLT) { return MA_ERROR; }
  10434. #endif
  10435. #ifdef EBADE
  10436. else if (e == EBADE) { return MA_ERROR; }
  10437. #endif
  10438. #ifdef EBADR
  10439. else if (e == EBADR) { return MA_ERROR; }
  10440. #endif
  10441. #ifdef EXFULL
  10442. else if (e == EXFULL) { return MA_ERROR; }
  10443. #endif
  10444. #ifdef ENOANO
  10445. else if (e == ENOANO) { return MA_ERROR; }
  10446. #endif
  10447. #ifdef EBADRQC
  10448. else if (e == EBADRQC) { return MA_ERROR; }
  10449. #endif
  10450. #ifdef EBADSLT
  10451. else if (e == EBADSLT) { return MA_ERROR; }
  10452. #endif
  10453. #ifdef EBFONT
  10454. else if (e == EBFONT) { return MA_INVALID_FILE; }
  10455. #endif
  10456. #ifdef ENOSTR
  10457. else if (e == ENOSTR) { return MA_ERROR; }
  10458. #endif
  10459. #ifdef ENODATA
  10460. else if (e == ENODATA) { return MA_NO_DATA_AVAILABLE; }
  10461. #endif
  10462. #ifdef ETIME
  10463. else if (e == ETIME) { return MA_TIMEOUT; }
  10464. #endif
  10465. #ifdef ENOSR
  10466. else if (e == ENOSR) { return MA_NO_DATA_AVAILABLE; }
  10467. #endif
  10468. #ifdef ENONET
  10469. else if (e == ENONET) { return MA_NO_NETWORK; }
  10470. #endif
  10471. #ifdef ENOPKG
  10472. else if (e == ENOPKG) { return MA_ERROR; }
  10473. #endif
  10474. #ifdef EREMOTE
  10475. else if (e == EREMOTE) { return MA_ERROR; }
  10476. #endif
  10477. #ifdef ENOLINK
  10478. else if (e == ENOLINK) { return MA_ERROR; }
  10479. #endif
  10480. #ifdef EADV
  10481. else if (e == EADV) { return MA_ERROR; }
  10482. #endif
  10483. #ifdef ESRMNT
  10484. else if (e == ESRMNT) { return MA_ERROR; }
  10485. #endif
  10486. #ifdef ECOMM
  10487. else if (e == ECOMM) { return MA_ERROR; }
  10488. #endif
  10489. #ifdef EPROTO
  10490. else if (e == EPROTO) { return MA_ERROR; }
  10491. #endif
  10492. #ifdef EMULTIHOP
  10493. else if (e == EMULTIHOP) { return MA_ERROR; }
  10494. #endif
  10495. #ifdef EDOTDOT
  10496. else if (e == EDOTDOT) { return MA_ERROR; }
  10497. #endif
  10498. #ifdef EBADMSG
  10499. else if (e == EBADMSG) { return MA_BAD_MESSAGE; }
  10500. #endif
  10501. #ifdef EOVERFLOW
  10502. else if (e == EOVERFLOW) { return MA_TOO_BIG; }
  10503. #endif
  10504. #ifdef ENOTUNIQ
  10505. else if (e == ENOTUNIQ) { return MA_NOT_UNIQUE; }
  10506. #endif
  10507. #ifdef EBADFD
  10508. else if (e == EBADFD) { return MA_ERROR; }
  10509. #endif
  10510. #ifdef EREMCHG
  10511. else if (e == EREMCHG) { return MA_ERROR; }
  10512. #endif
  10513. #ifdef ELIBACC
  10514. else if (e == ELIBACC) { return MA_ACCESS_DENIED; }
  10515. #endif
  10516. #ifdef ELIBBAD
  10517. else if (e == ELIBBAD) { return MA_INVALID_FILE; }
  10518. #endif
  10519. #ifdef ELIBSCN
  10520. else if (e == ELIBSCN) { return MA_INVALID_FILE; }
  10521. #endif
  10522. #ifdef ELIBMAX
  10523. else if (e == ELIBMAX) { return MA_ERROR; }
  10524. #endif
  10525. #ifdef ELIBEXEC
  10526. else if (e == ELIBEXEC) { return MA_ERROR; }
  10527. #endif
  10528. #ifdef EILSEQ
  10529. else if (e == EILSEQ) { return MA_INVALID_DATA; }
  10530. #endif
  10531. #ifdef ERESTART
  10532. else if (e == ERESTART) { return MA_ERROR; }
  10533. #endif
  10534. #ifdef ESTRPIPE
  10535. else if (e == ESTRPIPE) { return MA_ERROR; }
  10536. #endif
  10537. #ifdef EUSERS
  10538. else if (e == EUSERS) { return MA_ERROR; }
  10539. #endif
  10540. #ifdef ENOTSOCK
  10541. else if (e == ENOTSOCK) { return MA_NOT_SOCKET; }
  10542. #endif
  10543. #ifdef EDESTADDRREQ
  10544. else if (e == EDESTADDRREQ) { return MA_NO_ADDRESS; }
  10545. #endif
  10546. #ifdef EMSGSIZE
  10547. else if (e == EMSGSIZE) { return MA_TOO_BIG; }
  10548. #endif
  10549. #ifdef EPROTOTYPE
  10550. else if (e == EPROTOTYPE) { return MA_BAD_PROTOCOL; }
  10551. #endif
  10552. #ifdef ENOPROTOOPT
  10553. else if (e == ENOPROTOOPT) { return MA_PROTOCOL_UNAVAILABLE; }
  10554. #endif
  10555. #ifdef EPROTONOSUPPORT
  10556. else if (e == EPROTONOSUPPORT) { return MA_PROTOCOL_NOT_SUPPORTED; }
  10557. #endif
  10558. #ifdef ESOCKTNOSUPPORT
  10559. else if (e == ESOCKTNOSUPPORT) { return MA_SOCKET_NOT_SUPPORTED; }
  10560. #endif
  10561. #ifdef EOPNOTSUPP
  10562. else if (e == EOPNOTSUPP) { return MA_INVALID_OPERATION; }
  10563. #endif
  10564. #ifdef EPFNOSUPPORT
  10565. else if (e == EPFNOSUPPORT) { return MA_PROTOCOL_FAMILY_NOT_SUPPORTED; }
  10566. #endif
  10567. #ifdef EAFNOSUPPORT
  10568. else if (e == EAFNOSUPPORT) { return MA_ADDRESS_FAMILY_NOT_SUPPORTED; }
  10569. #endif
  10570. #ifdef EADDRINUSE
  10571. else if (e == EADDRINUSE) { return MA_ALREADY_IN_USE; }
  10572. #endif
  10573. #ifdef EADDRNOTAVAIL
  10574. else if (e == EADDRNOTAVAIL) { return MA_ERROR; }
  10575. #endif
  10576. #ifdef ENETDOWN
  10577. else if (e == ENETDOWN) { return MA_NO_NETWORK; }
  10578. #endif
  10579. #ifdef ENETUNREACH
  10580. else if (e == ENETUNREACH) { return MA_NO_NETWORK; }
  10581. #endif
  10582. #ifdef ENETRESET
  10583. else if (e == ENETRESET) { return MA_NO_NETWORK; }
  10584. #endif
  10585. #ifdef ECONNABORTED
  10586. else if (e == ECONNABORTED) { return MA_NO_NETWORK; }
  10587. #endif
  10588. #ifdef ECONNRESET
  10589. else if (e == ECONNRESET) { return MA_CONNECTION_RESET; }
  10590. #endif
  10591. #ifdef ENOBUFS
  10592. else if (e == ENOBUFS) { return MA_NO_SPACE; }
  10593. #endif
  10594. #ifdef EISCONN
  10595. else if (e == EISCONN) { return MA_ALREADY_CONNECTED; }
  10596. #endif
  10597. #ifdef ENOTCONN
  10598. else if (e == ENOTCONN) { return MA_NOT_CONNECTED; }
  10599. #endif
  10600. #ifdef ESHUTDOWN
  10601. else if (e == ESHUTDOWN) { return MA_ERROR; }
  10602. #endif
  10603. #ifdef ETOOMANYREFS
  10604. else if (e == ETOOMANYREFS) { return MA_ERROR; }
  10605. #endif
  10606. #ifdef ETIMEDOUT
  10607. else if (e == ETIMEDOUT) { return MA_TIMEOUT; }
  10608. #endif
  10609. #ifdef ECONNREFUSED
  10610. else if (e == ECONNREFUSED) { return MA_CONNECTION_REFUSED; }
  10611. #endif
  10612. #ifdef EHOSTDOWN
  10613. else if (e == EHOSTDOWN) { return MA_NO_HOST; }
  10614. #endif
  10615. #ifdef EHOSTUNREACH
  10616. else if (e == EHOSTUNREACH) { return MA_NO_HOST; }
  10617. #endif
  10618. #ifdef EALREADY
  10619. else if (e == EALREADY) { return MA_IN_PROGRESS; }
  10620. #endif
  10621. #ifdef EINPROGRESS
  10622. else if (e == EINPROGRESS) { return MA_IN_PROGRESS; }
  10623. #endif
  10624. #ifdef ESTALE
  10625. else if (e == ESTALE) { return MA_INVALID_FILE; }
  10626. #endif
  10627. #ifdef EUCLEAN
  10628. else if (e == EUCLEAN) { return MA_ERROR; }
  10629. #endif
  10630. #ifdef ENOTNAM
  10631. else if (e == ENOTNAM) { return MA_ERROR; }
  10632. #endif
  10633. #ifdef ENAVAIL
  10634. else if (e == ENAVAIL) { return MA_ERROR; }
  10635. #endif
  10636. #ifdef EISNAM
  10637. else if (e == EISNAM) { return MA_ERROR; }
  10638. #endif
  10639. #ifdef EREMOTEIO
  10640. else if (e == EREMOTEIO) { return MA_IO_ERROR; }
  10641. #endif
  10642. #ifdef EDQUOT
  10643. else if (e == EDQUOT) { return MA_NO_SPACE; }
  10644. #endif
  10645. #ifdef ENOMEDIUM
  10646. else if (e == ENOMEDIUM) { return MA_DOES_NOT_EXIST; }
  10647. #endif
  10648. #ifdef EMEDIUMTYPE
  10649. else if (e == EMEDIUMTYPE) { return MA_ERROR; }
  10650. #endif
  10651. #ifdef ECANCELED
  10652. else if (e == ECANCELED) { return MA_CANCELLED; }
  10653. #endif
  10654. #ifdef ENOKEY
  10655. else if (e == ENOKEY) { return MA_ERROR; }
  10656. #endif
  10657. #ifdef EKEYEXPIRED
  10658. else if (e == EKEYEXPIRED) { return MA_ERROR; }
  10659. #endif
  10660. #ifdef EKEYREVOKED
  10661. else if (e == EKEYREVOKED) { return MA_ERROR; }
  10662. #endif
  10663. #ifdef EKEYREJECTED
  10664. else if (e == EKEYREJECTED) { return MA_ERROR; }
  10665. #endif
  10666. #ifdef EOWNERDEAD
  10667. else if (e == EOWNERDEAD) { return MA_ERROR; }
  10668. #endif
  10669. #ifdef ENOTRECOVERABLE
  10670. else if (e == ENOTRECOVERABLE) { return MA_ERROR; }
  10671. #endif
  10672. #ifdef ERFKILL
  10673. else if (e == ERFKILL) { return MA_ERROR; }
  10674. #endif
  10675. #ifdef EHWPOISON
  10676. else if (e == EHWPOISON) { return MA_ERROR; }
  10677. #endif
  10678. else {
  10679. return MA_ERROR;
  10680. }
  10681. }
  10682. MA_API ma_result ma_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  10683. {
  10684. #if defined(_MSC_VER) && _MSC_VER >= 1400
  10685. errno_t err;
  10686. #endif
  10687. if (ppFile != NULL) {
  10688. *ppFile = NULL; /* Safety. */
  10689. }
  10690. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  10691. return MA_INVALID_ARGS;
  10692. }
  10693. #if defined(_MSC_VER) && _MSC_VER >= 1400
  10694. err = fopen_s(ppFile, pFilePath, pOpenMode);
  10695. if (err != 0) {
  10696. return ma_result_from_errno(err);
  10697. }
  10698. #else
  10699. #if defined(_WIN32) || defined(__APPLE__)
  10700. *ppFile = fopen(pFilePath, pOpenMode);
  10701. #else
  10702. #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  10703. *ppFile = fopen64(pFilePath, pOpenMode);
  10704. #else
  10705. *ppFile = fopen(pFilePath, pOpenMode);
  10706. #endif
  10707. #endif
  10708. if (*ppFile == NULL) {
  10709. ma_result result = ma_result_from_errno(errno);
  10710. if (result == MA_SUCCESS) {
  10711. result = MA_ERROR; /* Just a safety check to make sure we never ever return success when pFile == NULL. */
  10712. }
  10713. return result;
  10714. }
  10715. #endif
  10716. return MA_SUCCESS;
  10717. }
  10718. /*
  10719. _wfopen() isn't always available in all compilation environments.
  10720. * Windows only.
  10721. * MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back).
  10722. * MinGW-64 (both 32- and 64-bit) seems to support it.
  10723. * MinGW wraps it in !defined(__STRICT_ANSI__).
  10724. * OpenWatcom wraps it in !defined(_NO_EXT_KEYS).
  10725. This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs()
  10726. fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support.
  10727. */
  10728. #if defined(_WIN32)
  10729. #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
  10730. #define MA_HAS_WFOPEN
  10731. #endif
  10732. #endif
  10733. MA_API ma_result ma_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const ma_allocation_callbacks* pAllocationCallbacks)
  10734. {
  10735. if (ppFile != NULL) {
  10736. *ppFile = NULL; /* Safety. */
  10737. }
  10738. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  10739. return MA_INVALID_ARGS;
  10740. }
  10741. #if defined(MA_HAS_WFOPEN)
  10742. {
  10743. /* Use _wfopen() on Windows. */
  10744. #if defined(_MSC_VER) && _MSC_VER >= 1400
  10745. errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  10746. if (err != 0) {
  10747. return ma_result_from_errno(err);
  10748. }
  10749. #else
  10750. *ppFile = _wfopen(pFilePath, pOpenMode);
  10751. if (*ppFile == NULL) {
  10752. return ma_result_from_errno(errno);
  10753. }
  10754. #endif
  10755. (void)pAllocationCallbacks;
  10756. }
  10757. #else
  10758. /*
  10759. Use fopen() on anything other than Windows. Requires a conversion. This is annoying because fopen() is locale specific. The only real way I can
  10760. think of to do this is with wcsrtombs(). Note that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for
  10761. maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler error I'll look into improving compatibility.
  10762. */
  10763. {
  10764. mbstate_t mbs;
  10765. size_t lenMB;
  10766. const wchar_t* pFilePathTemp = pFilePath;
  10767. char* pFilePathMB = NULL;
  10768. char pOpenModeMB[32] = {0};
  10769. /* Get the length first. */
  10770. MA_ZERO_OBJECT(&mbs);
  10771. lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  10772. if (lenMB == (size_t)-1) {
  10773. return ma_result_from_errno(errno);
  10774. }
  10775. pFilePathMB = (char*)ma_malloc(lenMB + 1, pAllocationCallbacks);
  10776. if (pFilePathMB == NULL) {
  10777. return MA_OUT_OF_MEMORY;
  10778. }
  10779. pFilePathTemp = pFilePath;
  10780. MA_ZERO_OBJECT(&mbs);
  10781. wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  10782. /* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */
  10783. {
  10784. size_t i = 0;
  10785. for (;;) {
  10786. if (pOpenMode[i] == 0) {
  10787. pOpenModeMB[i] = '\0';
  10788. break;
  10789. }
  10790. pOpenModeMB[i] = (char)pOpenMode[i];
  10791. i += 1;
  10792. }
  10793. }
  10794. *ppFile = fopen(pFilePathMB, pOpenModeMB);
  10795. ma_free(pFilePathMB, pAllocationCallbacks);
  10796. }
  10797. if (*ppFile == NULL) {
  10798. return MA_ERROR;
  10799. }
  10800. #endif
  10801. return MA_SUCCESS;
  10802. }
  10803. static MA_INLINE void ma_copy_memory_64(void* dst, const void* src, ma_uint64 sizeInBytes)
  10804. {
  10805. #if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX
  10806. MA_COPY_MEMORY(dst, src, (size_t)sizeInBytes);
  10807. #else
  10808. while (sizeInBytes > 0) {
  10809. ma_uint64 bytesToCopyNow = sizeInBytes;
  10810. if (bytesToCopyNow > MA_SIZE_MAX) {
  10811. bytesToCopyNow = MA_SIZE_MAX;
  10812. }
  10813. MA_COPY_MEMORY(dst, src, (size_t)bytesToCopyNow); /* Safe cast to size_t. */
  10814. sizeInBytes -= bytesToCopyNow;
  10815. dst = ( void*)(( ma_uint8*)dst + bytesToCopyNow);
  10816. src = (const void*)((const ma_uint8*)src + bytesToCopyNow);
  10817. }
  10818. #endif
  10819. }
  10820. static MA_INLINE void ma_zero_memory_64(void* dst, ma_uint64 sizeInBytes)
  10821. {
  10822. #if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX
  10823. MA_ZERO_MEMORY(dst, (size_t)sizeInBytes);
  10824. #else
  10825. while (sizeInBytes > 0) {
  10826. ma_uint64 bytesToZeroNow = sizeInBytes;
  10827. if (bytesToZeroNow > MA_SIZE_MAX) {
  10828. bytesToZeroNow = MA_SIZE_MAX;
  10829. }
  10830. MA_ZERO_MEMORY(dst, (size_t)bytesToZeroNow); /* Safe cast to size_t. */
  10831. sizeInBytes -= bytesToZeroNow;
  10832. dst = (void*)((ma_uint8*)dst + bytesToZeroNow);
  10833. }
  10834. #endif
  10835. }
  10836. /* Thanks to good old Bit Twiddling Hacks for this one: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 */
  10837. static MA_INLINE unsigned int ma_next_power_of_2(unsigned int x)
  10838. {
  10839. x--;
  10840. x |= x >> 1;
  10841. x |= x >> 2;
  10842. x |= x >> 4;
  10843. x |= x >> 8;
  10844. x |= x >> 16;
  10845. x++;
  10846. return x;
  10847. }
  10848. static MA_INLINE unsigned int ma_prev_power_of_2(unsigned int x)
  10849. {
  10850. return ma_next_power_of_2(x) >> 1;
  10851. }
  10852. static MA_INLINE unsigned int ma_round_to_power_of_2(unsigned int x)
  10853. {
  10854. unsigned int prev = ma_prev_power_of_2(x);
  10855. unsigned int next = ma_next_power_of_2(x);
  10856. if ((next - x) > (x - prev)) {
  10857. return prev;
  10858. } else {
  10859. return next;
  10860. }
  10861. }
  10862. static MA_INLINE unsigned int ma_count_set_bits(unsigned int x)
  10863. {
  10864. unsigned int count = 0;
  10865. while (x != 0) {
  10866. if (x & 1) {
  10867. count += 1;
  10868. }
  10869. x = x >> 1;
  10870. }
  10871. return count;
  10872. }
  10873. /**************************************************************************************************************************************************************
  10874. Allocation Callbacks
  10875. **************************************************************************************************************************************************************/
  10876. static void* ma__malloc_default(size_t sz, void* pUserData)
  10877. {
  10878. (void)pUserData;
  10879. return MA_MALLOC(sz);
  10880. }
  10881. static void* ma__realloc_default(void* p, size_t sz, void* pUserData)
  10882. {
  10883. (void)pUserData;
  10884. return MA_REALLOC(p, sz);
  10885. }
  10886. static void ma__free_default(void* p, void* pUserData)
  10887. {
  10888. (void)pUserData;
  10889. MA_FREE(p);
  10890. }
  10891. static ma_allocation_callbacks ma_allocation_callbacks_init_default(void)
  10892. {
  10893. ma_allocation_callbacks callbacks;
  10894. callbacks.pUserData = NULL;
  10895. callbacks.onMalloc = ma__malloc_default;
  10896. callbacks.onRealloc = ma__realloc_default;
  10897. callbacks.onFree = ma__free_default;
  10898. return callbacks;
  10899. }
  10900. static ma_result ma_allocation_callbacks_init_copy(ma_allocation_callbacks* pDst, const ma_allocation_callbacks* pSrc)
  10901. {
  10902. if (pDst == NULL) {
  10903. return MA_INVALID_ARGS;
  10904. }
  10905. if (pSrc == NULL) {
  10906. *pDst = ma_allocation_callbacks_init_default();
  10907. } else {
  10908. if (pSrc->pUserData == NULL && pSrc->onFree == NULL && pSrc->onMalloc == NULL && pSrc->onRealloc == NULL) {
  10909. *pDst = ma_allocation_callbacks_init_default();
  10910. } else {
  10911. if (pSrc->onFree == NULL || (pSrc->onMalloc == NULL && pSrc->onRealloc == NULL)) {
  10912. return MA_INVALID_ARGS; /* Invalid allocation callbacks. */
  10913. } else {
  10914. *pDst = *pSrc;
  10915. }
  10916. }
  10917. }
  10918. return MA_SUCCESS;
  10919. }
  10920. /**************************************************************************************************************************************************************
  10921. Logging
  10922. **************************************************************************************************************************************************************/
  10923. MA_API const char* ma_log_level_to_string(ma_uint32 logLevel)
  10924. {
  10925. switch (logLevel)
  10926. {
  10927. case MA_LOG_LEVEL_DEBUG: return "DEBUG";
  10928. case MA_LOG_LEVEL_INFO: return "INFO";
  10929. case MA_LOG_LEVEL_WARNING: return "WARNING";
  10930. case MA_LOG_LEVEL_ERROR: return "ERROR";
  10931. default: return "ERROR";
  10932. }
  10933. }
  10934. #if defined(MA_DEBUG_OUTPUT)
  10935. #if defined(MA_ANDROID)
  10936. #include <android/log.h>
  10937. #endif
  10938. /* Customize this to use a specific tag in __android_log_print() for debug output messages. */
  10939. #ifndef MA_ANDROID_LOG_TAG
  10940. #define MA_ANDROID_LOG_TAG "miniaudio"
  10941. #endif
  10942. void ma_log_callback_debug(void* pUserData, ma_uint32 level, const char* pMessage)
  10943. {
  10944. (void)pUserData;
  10945. /* Special handling for some platforms. */
  10946. #if defined(MA_ANDROID)
  10947. {
  10948. /* Android. */
  10949. __android_log_print(ANDROID_LOG_DEBUG, MA_ANDROID_LOG_TAG, "%s: %s", ma_log_level_to_string(level), pMessage);
  10950. }
  10951. #else
  10952. {
  10953. /* Everything else. */
  10954. printf("%s: %s", ma_log_level_to_string(level), pMessage);
  10955. }
  10956. #endif
  10957. }
  10958. #endif
  10959. MA_API ma_log_callback ma_log_callback_init(ma_log_callback_proc onLog, void* pUserData)
  10960. {
  10961. ma_log_callback callback;
  10962. MA_ZERO_OBJECT(&callback);
  10963. callback.onLog = onLog;
  10964. callback.pUserData = pUserData;
  10965. return callback;
  10966. }
  10967. MA_API ma_result ma_log_init(const ma_allocation_callbacks* pAllocationCallbacks, ma_log* pLog)
  10968. {
  10969. if (pLog == NULL) {
  10970. return MA_INVALID_ARGS;
  10971. }
  10972. MA_ZERO_OBJECT(pLog);
  10973. ma_allocation_callbacks_init_copy(&pLog->allocationCallbacks, pAllocationCallbacks);
  10974. /* We need a mutex for thread safety. */
  10975. #ifndef MA_NO_THREADING
  10976. {
  10977. ma_result result = ma_mutex_init(&pLog->lock);
  10978. if (result != MA_SUCCESS) {
  10979. return result;
  10980. }
  10981. }
  10982. #endif
  10983. /* If we're using debug output, enable it. */
  10984. #if defined(MA_DEBUG_OUTPUT)
  10985. {
  10986. ma_log_register_callback(pLog, ma_log_callback_init(ma_log_callback_debug, NULL)); /* Doesn't really matter if this fails. */
  10987. }
  10988. #endif
  10989. return MA_SUCCESS;
  10990. }
  10991. MA_API void ma_log_uninit(ma_log* pLog)
  10992. {
  10993. if (pLog == NULL) {
  10994. return;
  10995. }
  10996. #ifndef MA_NO_THREADING
  10997. ma_mutex_uninit(&pLog->lock);
  10998. #endif
  10999. }
  11000. static void ma_log_lock(ma_log* pLog)
  11001. {
  11002. #ifndef MA_NO_THREADING
  11003. ma_mutex_lock(&pLog->lock);
  11004. #else
  11005. (void)pLog;
  11006. #endif
  11007. }
  11008. static void ma_log_unlock(ma_log* pLog)
  11009. {
  11010. #ifndef MA_NO_THREADING
  11011. ma_mutex_unlock(&pLog->lock);
  11012. #else
  11013. (void)pLog;
  11014. #endif
  11015. }
  11016. MA_API ma_result ma_log_register_callback(ma_log* pLog, ma_log_callback callback)
  11017. {
  11018. ma_result result = MA_SUCCESS;
  11019. if (pLog == NULL || callback.onLog == NULL) {
  11020. return MA_INVALID_ARGS;
  11021. }
  11022. ma_log_lock(pLog);
  11023. {
  11024. if (pLog->callbackCount == ma_countof(pLog->callbacks)) {
  11025. result = MA_OUT_OF_MEMORY; /* Reached the maximum allowed log callbacks. */
  11026. } else {
  11027. pLog->callbacks[pLog->callbackCount] = callback;
  11028. pLog->callbackCount += 1;
  11029. }
  11030. }
  11031. ma_log_unlock(pLog);
  11032. return result;
  11033. }
  11034. MA_API ma_result ma_log_unregister_callback(ma_log* pLog, ma_log_callback callback)
  11035. {
  11036. if (pLog == NULL) {
  11037. return MA_INVALID_ARGS;
  11038. }
  11039. ma_log_lock(pLog);
  11040. {
  11041. ma_uint32 iLog;
  11042. for (iLog = 0; iLog < pLog->callbackCount; ) {
  11043. if (pLog->callbacks[iLog].onLog == callback.onLog) {
  11044. /* Found. Move everything down a slot. */
  11045. ma_uint32 jLog;
  11046. for (jLog = iLog; jLog < pLog->callbackCount-1; jLog += 1) {
  11047. pLog->callbacks[jLog] = pLog->callbacks[jLog + 1];
  11048. }
  11049. pLog->callbackCount -= 1;
  11050. } else {
  11051. /* Not found. */
  11052. iLog += 1;
  11053. }
  11054. }
  11055. }
  11056. ma_log_unlock(pLog);
  11057. return MA_SUCCESS;
  11058. }
  11059. MA_API ma_result ma_log_post(ma_log* pLog, ma_uint32 level, const char* pMessage)
  11060. {
  11061. if (pLog == NULL || pMessage == NULL) {
  11062. return MA_INVALID_ARGS;
  11063. }
  11064. ma_log_lock(pLog);
  11065. {
  11066. ma_uint32 iLog;
  11067. for (iLog = 0; iLog < pLog->callbackCount; iLog += 1) {
  11068. if (pLog->callbacks[iLog].onLog) {
  11069. pLog->callbacks[iLog].onLog(pLog->callbacks[iLog].pUserData, level, pMessage);
  11070. }
  11071. }
  11072. }
  11073. ma_log_unlock(pLog);
  11074. return MA_SUCCESS;
  11075. }
  11076. /*
  11077. We need to emulate _vscprintf() for the VC6 build. This can be more efficient, but since it's only VC6, and it's just a
  11078. logging function, I'm happy to keep this simple. In the VC6 build we can implement this in terms of _vsnprintf().
  11079. */
  11080. #if defined(_MSC_VER) && _MSC_VER < 1900
  11081. static int ma_vscprintf(const ma_allocation_callbacks* pAllocationCallbacks, const char* format, va_list args)
  11082. {
  11083. #if _MSC_VER > 1200
  11084. return _vscprintf(format, args);
  11085. #else
  11086. int result;
  11087. char* pTempBuffer = NULL;
  11088. size_t tempBufferCap = 1024;
  11089. if (format == NULL) {
  11090. errno = EINVAL;
  11091. return -1;
  11092. }
  11093. for (;;) {
  11094. char* pNewTempBuffer = (char*)ma_realloc(pTempBuffer, tempBufferCap, pAllocationCallbacks);
  11095. if (pNewTempBuffer == NULL) {
  11096. ma_free(pTempBuffer, pAllocationCallbacks);
  11097. errno = ENOMEM;
  11098. return -1; /* Out of memory. */
  11099. }
  11100. pTempBuffer = pNewTempBuffer;
  11101. result = _vsnprintf(pTempBuffer, tempBufferCap, format, args);
  11102. ma_free(pTempBuffer, NULL);
  11103. if (result != -1) {
  11104. break; /* Got it. */
  11105. }
  11106. /* Buffer wasn't big enough. Ideally it'd be nice to use an error code to know the reason for sure, but this is reliable enough. */
  11107. tempBufferCap *= 2;
  11108. }
  11109. return result;
  11110. #endif
  11111. }
  11112. #endif
  11113. MA_API ma_result ma_log_postv(ma_log* pLog, ma_uint32 level, const char* pFormat, va_list args)
  11114. {
  11115. if (pLog == NULL || pFormat == NULL) {
  11116. return MA_INVALID_ARGS;
  11117. }
  11118. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || ((!defined(_MSC_VER) || _MSC_VER >= 1900) && !defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS)) || (defined(__cplusplus) && __cplusplus >= 201103L)
  11119. {
  11120. ma_result result;
  11121. int length;
  11122. char pFormattedMessageStack[1024];
  11123. char* pFormattedMessageHeap = NULL;
  11124. /* First try formatting into our fixed sized stack allocated buffer. If this is too small we'll fallback to a heap allocation. */
  11125. length = vsnprintf(pFormattedMessageStack, sizeof(pFormattedMessageStack), pFormat, args);
  11126. if (length < 0) {
  11127. return MA_INVALID_OPERATION; /* An error occured when trying to convert the buffer. */
  11128. }
  11129. if ((size_t)length < sizeof(pFormattedMessageStack)) {
  11130. /* The string was written to the stack. */
  11131. result = ma_log_post(pLog, level, pFormattedMessageStack);
  11132. } else {
  11133. /* The stack buffer was too small, try the heap. */
  11134. pFormattedMessageHeap = (char*)ma_malloc(length + 1, &pLog->allocationCallbacks);
  11135. if (pFormattedMessageHeap == NULL) {
  11136. return MA_OUT_OF_MEMORY;
  11137. }
  11138. length = vsnprintf(pFormattedMessageHeap, length + 1, pFormat, args);
  11139. if (length < 0) {
  11140. ma_free(pFormattedMessageHeap, &pLog->allocationCallbacks);
  11141. return MA_INVALID_OPERATION;
  11142. }
  11143. result = ma_log_post(pLog, level, pFormattedMessageHeap);
  11144. ma_free(pFormattedMessageHeap, &pLog->allocationCallbacks);
  11145. }
  11146. return result;
  11147. }
  11148. #else
  11149. {
  11150. /*
  11151. Without snprintf() we need to first measure the string and then heap allocate it. I'm only aware of Visual Studio having support for this without snprintf(), so we'll
  11152. need to restrict this branch to Visual Studio. For other compilers we need to just not support formatted logging because I don't want the security risk of overflowing
  11153. a fixed sized stack allocated buffer.
  11154. */
  11155. #if defined(_MSC_VER) && _MSC_VER >= 1200 /* 1200 = VC6 */
  11156. {
  11157. ma_result result;
  11158. int formattedLen;
  11159. char* pFormattedMessage = NULL;
  11160. va_list args2;
  11161. #if _MSC_VER >= 1800
  11162. {
  11163. va_copy(args2, args);
  11164. }
  11165. #else
  11166. {
  11167. args2 = args;
  11168. }
  11169. #endif
  11170. formattedLen = ma_vscprintf(&pLog->allocationCallbacks, pFormat, args2);
  11171. va_end(args2);
  11172. if (formattedLen <= 0) {
  11173. return MA_INVALID_OPERATION;
  11174. }
  11175. pFormattedMessage = (char*)ma_malloc(formattedLen + 1, &pLog->allocationCallbacks);
  11176. if (pFormattedMessage == NULL) {
  11177. return MA_OUT_OF_MEMORY;
  11178. }
  11179. /* We'll get errors on newer versions of Visual Studio if we try to use vsprintf(). */
  11180. #if _MSC_VER >= 1400 /* 1400 = Visual Studio 2005 */
  11181. {
  11182. vsprintf_s(pFormattedMessage, formattedLen + 1, pFormat, args);
  11183. }
  11184. #else
  11185. {
  11186. vsprintf(pFormattedMessage, pFormat, args);
  11187. }
  11188. #endif
  11189. result = ma_log_post(pLog, level, pFormattedMessage);
  11190. ma_free(pFormattedMessage, &pLog->allocationCallbacks);
  11191. return result;
  11192. }
  11193. #else
  11194. {
  11195. /* Can't do anything because we don't have a safe way of to emulate vsnprintf() without a manual solution. */
  11196. (void)level;
  11197. (void)args;
  11198. return MA_INVALID_OPERATION;
  11199. }
  11200. #endif
  11201. }
  11202. #endif
  11203. }
  11204. MA_API ma_result ma_log_postf(ma_log* pLog, ma_uint32 level, const char* pFormat, ...)
  11205. {
  11206. ma_result result;
  11207. va_list args;
  11208. if (pLog == NULL || pFormat == NULL) {
  11209. return MA_INVALID_ARGS;
  11210. }
  11211. va_start(args, pFormat);
  11212. {
  11213. result = ma_log_postv(pLog, level, pFormat, args);
  11214. }
  11215. va_end(args);
  11216. return result;
  11217. }
  11218. static MA_INLINE ma_uint8 ma_clip_u8(ma_int32 x)
  11219. {
  11220. return (ma_uint8)(ma_clamp(x, -128, 127) + 128);
  11221. }
  11222. static MA_INLINE ma_int16 ma_clip_s16(ma_int32 x)
  11223. {
  11224. return (ma_int16)ma_clamp(x, -32768, 32767);
  11225. }
  11226. static MA_INLINE ma_int64 ma_clip_s24(ma_int64 x)
  11227. {
  11228. return (ma_int64)ma_clamp(x, -8388608, 8388607);
  11229. }
  11230. static MA_INLINE ma_int32 ma_clip_s32(ma_int64 x)
  11231. {
  11232. /* This dance is to silence warnings with -std=c89. A good compiler should be able to optimize this away. */
  11233. ma_int64 clipMin;
  11234. ma_int64 clipMax;
  11235. clipMin = -((ma_int64)2147483647 + 1);
  11236. clipMax = (ma_int64)2147483647;
  11237. return (ma_int32)ma_clamp(x, clipMin, clipMax);
  11238. }
  11239. static MA_INLINE float ma_clip_f32(float x)
  11240. {
  11241. if (x < -1) return -1;
  11242. if (x > +1) return +1;
  11243. return x;
  11244. }
  11245. static MA_INLINE float ma_mix_f32(float x, float y, float a)
  11246. {
  11247. return x*(1-a) + y*a;
  11248. }
  11249. static MA_INLINE float ma_mix_f32_fast(float x, float y, float a)
  11250. {
  11251. float r0 = (y - x);
  11252. float r1 = r0*a;
  11253. return x + r1;
  11254. /*return x + (y - x)*a;*/
  11255. }
  11256. #if defined(MA_SUPPORT_SSE2)
  11257. static MA_INLINE __m128 ma_mix_f32_fast__sse2(__m128 x, __m128 y, __m128 a)
  11258. {
  11259. return _mm_add_ps(x, _mm_mul_ps(_mm_sub_ps(y, x), a));
  11260. }
  11261. #endif
  11262. #if defined(MA_SUPPORT_AVX2)
  11263. static MA_INLINE __m256 ma_mix_f32_fast__avx2(__m256 x, __m256 y, __m256 a)
  11264. {
  11265. return _mm256_add_ps(x, _mm256_mul_ps(_mm256_sub_ps(y, x), a));
  11266. }
  11267. #endif
  11268. #if defined(MA_SUPPORT_NEON)
  11269. static MA_INLINE float32x4_t ma_mix_f32_fast__neon(float32x4_t x, float32x4_t y, float32x4_t a)
  11270. {
  11271. return vaddq_f32(x, vmulq_f32(vsubq_f32(y, x), a));
  11272. }
  11273. #endif
  11274. static MA_INLINE double ma_mix_f64(double x, double y, double a)
  11275. {
  11276. return x*(1-a) + y*a;
  11277. }
  11278. static MA_INLINE double ma_mix_f64_fast(double x, double y, double a)
  11279. {
  11280. return x + (y - x)*a;
  11281. }
  11282. static MA_INLINE float ma_scale_to_range_f32(float x, float lo, float hi)
  11283. {
  11284. return lo + x*(hi-lo);
  11285. }
  11286. /*
  11287. Greatest common factor using Euclid's algorithm iteratively.
  11288. */
  11289. static MA_INLINE ma_uint32 ma_gcf_u32(ma_uint32 a, ma_uint32 b)
  11290. {
  11291. for (;;) {
  11292. if (b == 0) {
  11293. break;
  11294. } else {
  11295. ma_uint32 t = a;
  11296. a = b;
  11297. b = t % a;
  11298. }
  11299. }
  11300. return a;
  11301. }
  11302. static ma_uint32 ma_ffs_32(ma_uint32 x)
  11303. {
  11304. ma_uint32 i;
  11305. /* Just a naive implementation just to get things working for now. Will optimize this later. */
  11306. for (i = 0; i < 32; i += 1) {
  11307. if ((x & (1 << i)) != 0) {
  11308. return i;
  11309. }
  11310. }
  11311. return i;
  11312. }
  11313. static MA_INLINE ma_int16 ma_float_to_fixed_16(float x)
  11314. {
  11315. return (ma_int16)(x * (1 << 8));
  11316. }
  11317. /*
  11318. Random Number Generation
  11319. miniaudio uses the LCG random number generation algorithm. This is good enough for audio.
  11320. Note that miniaudio's global LCG implementation uses global state which is _not_ thread-local. When this is called across
  11321. multiple threads, results will be unpredictable. However, it won't crash and results will still be random enough for
  11322. miniaudio's purposes.
  11323. */
  11324. #ifndef MA_DEFAULT_LCG_SEED
  11325. #define MA_DEFAULT_LCG_SEED 4321
  11326. #endif
  11327. #define MA_LCG_M 2147483647
  11328. #define MA_LCG_A 48271
  11329. #define MA_LCG_C 0
  11330. static ma_lcg g_maLCG = {MA_DEFAULT_LCG_SEED}; /* Non-zero initial seed. Use ma_seed() to use an explicit seed. */
  11331. static MA_INLINE void ma_lcg_seed(ma_lcg* pLCG, ma_int32 seed)
  11332. {
  11333. MA_ASSERT(pLCG != NULL);
  11334. pLCG->state = seed;
  11335. }
  11336. static MA_INLINE ma_int32 ma_lcg_rand_s32(ma_lcg* pLCG)
  11337. {
  11338. pLCG->state = (MA_LCG_A * pLCG->state + MA_LCG_C) % MA_LCG_M;
  11339. return pLCG->state;
  11340. }
  11341. static MA_INLINE ma_uint32 ma_lcg_rand_u32(ma_lcg* pLCG)
  11342. {
  11343. return (ma_uint32)ma_lcg_rand_s32(pLCG);
  11344. }
  11345. static MA_INLINE ma_int16 ma_lcg_rand_s16(ma_lcg* pLCG)
  11346. {
  11347. return (ma_int16)(ma_lcg_rand_s32(pLCG) & 0xFFFF);
  11348. }
  11349. static MA_INLINE double ma_lcg_rand_f64(ma_lcg* pLCG)
  11350. {
  11351. return ma_lcg_rand_s32(pLCG) / (double)0x7FFFFFFF;
  11352. }
  11353. static MA_INLINE float ma_lcg_rand_f32(ma_lcg* pLCG)
  11354. {
  11355. return (float)ma_lcg_rand_f64(pLCG);
  11356. }
  11357. static MA_INLINE float ma_lcg_rand_range_f32(ma_lcg* pLCG, float lo, float hi)
  11358. {
  11359. return ma_scale_to_range_f32(ma_lcg_rand_f32(pLCG), lo, hi);
  11360. }
  11361. static MA_INLINE ma_int32 ma_lcg_rand_range_s32(ma_lcg* pLCG, ma_int32 lo, ma_int32 hi)
  11362. {
  11363. if (lo == hi) {
  11364. return lo;
  11365. }
  11366. return lo + ma_lcg_rand_u32(pLCG) / (0xFFFFFFFF / (hi - lo + 1) + 1);
  11367. }
  11368. static MA_INLINE void ma_seed(ma_int32 seed)
  11369. {
  11370. ma_lcg_seed(&g_maLCG, seed);
  11371. }
  11372. static MA_INLINE ma_int32 ma_rand_s32(void)
  11373. {
  11374. return ma_lcg_rand_s32(&g_maLCG);
  11375. }
  11376. static MA_INLINE ma_uint32 ma_rand_u32(void)
  11377. {
  11378. return ma_lcg_rand_u32(&g_maLCG);
  11379. }
  11380. static MA_INLINE double ma_rand_f64(void)
  11381. {
  11382. return ma_lcg_rand_f64(&g_maLCG);
  11383. }
  11384. static MA_INLINE float ma_rand_f32(void)
  11385. {
  11386. return ma_lcg_rand_f32(&g_maLCG);
  11387. }
  11388. static MA_INLINE float ma_rand_range_f32(float lo, float hi)
  11389. {
  11390. return ma_lcg_rand_range_f32(&g_maLCG, lo, hi);
  11391. }
  11392. static MA_INLINE ma_int32 ma_rand_range_s32(ma_int32 lo, ma_int32 hi)
  11393. {
  11394. return ma_lcg_rand_range_s32(&g_maLCG, lo, hi);
  11395. }
  11396. static MA_INLINE float ma_dither_f32_rectangle(float ditherMin, float ditherMax)
  11397. {
  11398. return ma_rand_range_f32(ditherMin, ditherMax);
  11399. }
  11400. static MA_INLINE float ma_dither_f32_triangle(float ditherMin, float ditherMax)
  11401. {
  11402. float a = ma_rand_range_f32(ditherMin, 0);
  11403. float b = ma_rand_range_f32(0, ditherMax);
  11404. return a + b;
  11405. }
  11406. static MA_INLINE float ma_dither_f32(ma_dither_mode ditherMode, float ditherMin, float ditherMax)
  11407. {
  11408. if (ditherMode == ma_dither_mode_rectangle) {
  11409. return ma_dither_f32_rectangle(ditherMin, ditherMax);
  11410. }
  11411. if (ditherMode == ma_dither_mode_triangle) {
  11412. return ma_dither_f32_triangle(ditherMin, ditherMax);
  11413. }
  11414. return 0;
  11415. }
  11416. static MA_INLINE ma_int32 ma_dither_s32(ma_dither_mode ditherMode, ma_int32 ditherMin, ma_int32 ditherMax)
  11417. {
  11418. if (ditherMode == ma_dither_mode_rectangle) {
  11419. ma_int32 a = ma_rand_range_s32(ditherMin, ditherMax);
  11420. return a;
  11421. }
  11422. if (ditherMode == ma_dither_mode_triangle) {
  11423. ma_int32 a = ma_rand_range_s32(ditherMin, 0);
  11424. ma_int32 b = ma_rand_range_s32(0, ditherMax);
  11425. return a + b;
  11426. }
  11427. return 0;
  11428. }
  11429. /**************************************************************************************************************************************************************
  11430. Atomics
  11431. **************************************************************************************************************************************************************/
  11432. /* c89atomic.h begin */
  11433. #ifndef c89atomic_h
  11434. #define c89atomic_h
  11435. #if defined(__cplusplus)
  11436. extern "C" {
  11437. #endif
  11438. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  11439. #pragma GCC diagnostic push
  11440. #pragma GCC diagnostic ignored "-Wlong-long"
  11441. #if defined(__clang__)
  11442. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  11443. #endif
  11444. #endif
  11445. typedef signed char c89atomic_int8;
  11446. typedef unsigned char c89atomic_uint8;
  11447. typedef signed short c89atomic_int16;
  11448. typedef unsigned short c89atomic_uint16;
  11449. typedef signed int c89atomic_int32;
  11450. typedef unsigned int c89atomic_uint32;
  11451. #if defined(_MSC_VER) && !defined(__clang__)
  11452. typedef signed __int64 c89atomic_int64;
  11453. typedef unsigned __int64 c89atomic_uint64;
  11454. #else
  11455. typedef signed long long c89atomic_int64;
  11456. typedef unsigned long long c89atomic_uint64;
  11457. #endif
  11458. typedef int c89atomic_memory_order;
  11459. typedef unsigned char c89atomic_bool;
  11460. #if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT)
  11461. #ifdef _WIN32
  11462. #ifdef _WIN64
  11463. #define C89ATOMIC_64BIT
  11464. #else
  11465. #define C89ATOMIC_32BIT
  11466. #endif
  11467. #endif
  11468. #endif
  11469. #if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT)
  11470. #ifdef __GNUC__
  11471. #ifdef __LP64__
  11472. #define C89ATOMIC_64BIT
  11473. #else
  11474. #define C89ATOMIC_32BIT
  11475. #endif
  11476. #endif
  11477. #endif
  11478. #if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT)
  11479. #include <stdint.h>
  11480. #if INTPTR_MAX == INT64_MAX
  11481. #define C89ATOMIC_64BIT
  11482. #else
  11483. #define C89ATOMIC_32BIT
  11484. #endif
  11485. #endif
  11486. #if defined(__arm__) || defined(_M_ARM)
  11487. #define C89ATOMIC_ARM32
  11488. #endif
  11489. #if defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
  11490. #define C89ATOMIC_ARM64
  11491. #endif
  11492. #if defined(__x86_64__) || defined(_M_X64)
  11493. #define C89ATOMIC_X64
  11494. #elif defined(__i386) || defined(_M_IX86)
  11495. #define C89ATOMIC_X86
  11496. #elif defined(C89ATOMIC_ARM32) || defined(C89ATOMIC_ARM64)
  11497. #define C89ATOMIC_ARM
  11498. #endif
  11499. #if defined(_MSC_VER)
  11500. #define C89ATOMIC_INLINE __forceinline
  11501. #elif defined(__GNUC__)
  11502. #if defined(__STRICT_ANSI__)
  11503. #define C89ATOMIC_INLINE __inline__ __attribute__((always_inline))
  11504. #else
  11505. #define C89ATOMIC_INLINE inline __attribute__((always_inline))
  11506. #endif
  11507. #elif defined(__WATCOMC__) || defined(__DMC__)
  11508. #define C89ATOMIC_INLINE __inline
  11509. #else
  11510. #define C89ATOMIC_INLINE
  11511. #endif
  11512. #define C89ATOMIC_HAS_8
  11513. #define C89ATOMIC_HAS_16
  11514. #define C89ATOMIC_HAS_32
  11515. #define C89ATOMIC_HAS_64
  11516. #if (defined(_MSC_VER) ) || defined(__WATCOMC__) || defined(__DMC__)
  11517. #define C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, intrin, c89atomicType, msvcType) \
  11518. c89atomicType result; \
  11519. switch (order) \
  11520. { \
  11521. case c89atomic_memory_order_relaxed: \
  11522. { \
  11523. result = (c89atomicType)intrin##_nf((volatile msvcType*)dst, (msvcType)src); \
  11524. } break; \
  11525. case c89atomic_memory_order_consume: \
  11526. case c89atomic_memory_order_acquire: \
  11527. { \
  11528. result = (c89atomicType)intrin##_acq((volatile msvcType*)dst, (msvcType)src); \
  11529. } break; \
  11530. case c89atomic_memory_order_release: \
  11531. { \
  11532. result = (c89atomicType)intrin##_rel((volatile msvcType*)dst, (msvcType)src); \
  11533. } break; \
  11534. case c89atomic_memory_order_acq_rel: \
  11535. case c89atomic_memory_order_seq_cst: \
  11536. default: \
  11537. { \
  11538. result = (c89atomicType)intrin((volatile msvcType*)dst, (msvcType)src); \
  11539. } break; \
  11540. } \
  11541. return result;
  11542. #define C89ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, expected, desired, order, intrin, c89atomicType, msvcType) \
  11543. c89atomicType result; \
  11544. switch (order) \
  11545. { \
  11546. case c89atomic_memory_order_relaxed: \
  11547. { \
  11548. result = (c89atomicType)intrin##_nf((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \
  11549. } break; \
  11550. case c89atomic_memory_order_consume: \
  11551. case c89atomic_memory_order_acquire: \
  11552. { \
  11553. result = (c89atomicType)intrin##_acq((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \
  11554. } break; \
  11555. case c89atomic_memory_order_release: \
  11556. { \
  11557. result = (c89atomicType)intrin##_rel((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \
  11558. } break; \
  11559. case c89atomic_memory_order_acq_rel: \
  11560. case c89atomic_memory_order_seq_cst: \
  11561. default: \
  11562. { \
  11563. result = (c89atomicType)intrin((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \
  11564. } break; \
  11565. } \
  11566. return result;
  11567. #define c89atomic_memory_order_relaxed 0
  11568. #define c89atomic_memory_order_consume 1
  11569. #define c89atomic_memory_order_acquire 2
  11570. #define c89atomic_memory_order_release 3
  11571. #define c89atomic_memory_order_acq_rel 4
  11572. #define c89atomic_memory_order_seq_cst 5
  11573. #if _MSC_VER < 1600 && defined(C89ATOMIC_X86)
  11574. #define C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY
  11575. #endif
  11576. #if _MSC_VER < 1600
  11577. #undef C89ATOMIC_HAS_8
  11578. #undef C89ATOMIC_HAS_16
  11579. #endif
  11580. #if !defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11581. #include <intrin.h>
  11582. #endif
  11583. #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11584. #if defined(C89ATOMIC_HAS_8)
  11585. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_compare_and_swap_8(volatile c89atomic_uint8* dst, c89atomic_uint8 expected, c89atomic_uint8 desired)
  11586. {
  11587. c89atomic_uint8 result = 0;
  11588. __asm {
  11589. mov ecx, dst
  11590. mov al, expected
  11591. mov dl, desired
  11592. lock cmpxchg [ecx], dl
  11593. mov result, al
  11594. }
  11595. return result;
  11596. }
  11597. #endif
  11598. #if defined(C89ATOMIC_HAS_16)
  11599. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_compare_and_swap_16(volatile c89atomic_uint16* dst, c89atomic_uint16 expected, c89atomic_uint16 desired)
  11600. {
  11601. c89atomic_uint16 result = 0;
  11602. __asm {
  11603. mov ecx, dst
  11604. mov ax, expected
  11605. mov dx, desired
  11606. lock cmpxchg [ecx], dx
  11607. mov result, ax
  11608. }
  11609. return result;
  11610. }
  11611. #endif
  11612. #if defined(C89ATOMIC_HAS_32)
  11613. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_compare_and_swap_32(volatile c89atomic_uint32* dst, c89atomic_uint32 expected, c89atomic_uint32 desired)
  11614. {
  11615. c89atomic_uint32 result = 0;
  11616. __asm {
  11617. mov ecx, dst
  11618. mov eax, expected
  11619. mov edx, desired
  11620. lock cmpxchg [ecx], edx
  11621. mov result, eax
  11622. }
  11623. return result;
  11624. }
  11625. #endif
  11626. #if defined(C89ATOMIC_HAS_64)
  11627. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_compare_and_swap_64(volatile c89atomic_uint64* dst, c89atomic_uint64 expected, c89atomic_uint64 desired)
  11628. {
  11629. c89atomic_uint32 resultEAX = 0;
  11630. c89atomic_uint32 resultEDX = 0;
  11631. __asm {
  11632. mov esi, dst
  11633. mov eax, dword ptr expected
  11634. mov edx, dword ptr expected + 4
  11635. mov ebx, dword ptr desired
  11636. mov ecx, dword ptr desired + 4
  11637. lock cmpxchg8b qword ptr [esi]
  11638. mov resultEAX, eax
  11639. mov resultEDX, edx
  11640. }
  11641. return ((c89atomic_uint64)resultEDX << 32) | resultEAX;
  11642. }
  11643. #endif
  11644. #else
  11645. #if defined(C89ATOMIC_HAS_8)
  11646. #define c89atomic_compare_and_swap_8( dst, expected, desired) (c89atomic_uint8 )_InterlockedCompareExchange8((volatile char*)dst, (char)desired, (char)expected)
  11647. #endif
  11648. #if defined(C89ATOMIC_HAS_16)
  11649. #define c89atomic_compare_and_swap_16(dst, expected, desired) (c89atomic_uint16)_InterlockedCompareExchange16((volatile short*)dst, (short)desired, (short)expected)
  11650. #endif
  11651. #if defined(C89ATOMIC_HAS_32)
  11652. #define c89atomic_compare_and_swap_32(dst, expected, desired) (c89atomic_uint32)_InterlockedCompareExchange((volatile long*)dst, (long)desired, (long)expected)
  11653. #endif
  11654. #if defined(C89ATOMIC_HAS_64)
  11655. #define c89atomic_compare_and_swap_64(dst, expected, desired) (c89atomic_uint64)_InterlockedCompareExchange64((volatile c89atomic_int64*)dst, (c89atomic_int64)desired, (c89atomic_int64)expected)
  11656. #endif
  11657. #endif
  11658. #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11659. #if defined(C89ATOMIC_HAS_8)
  11660. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11661. {
  11662. c89atomic_uint8 result = 0;
  11663. (void)order;
  11664. __asm {
  11665. mov ecx, dst
  11666. mov al, src
  11667. lock xchg [ecx], al
  11668. mov result, al
  11669. }
  11670. return result;
  11671. }
  11672. #endif
  11673. #if defined(C89ATOMIC_HAS_16)
  11674. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11675. {
  11676. c89atomic_uint16 result = 0;
  11677. (void)order;
  11678. __asm {
  11679. mov ecx, dst
  11680. mov ax, src
  11681. lock xchg [ecx], ax
  11682. mov result, ax
  11683. }
  11684. return result;
  11685. }
  11686. #endif
  11687. #if defined(C89ATOMIC_HAS_32)
  11688. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11689. {
  11690. c89atomic_uint32 result = 0;
  11691. (void)order;
  11692. __asm {
  11693. mov ecx, dst
  11694. mov eax, src
  11695. lock xchg [ecx], eax
  11696. mov result, eax
  11697. }
  11698. return result;
  11699. }
  11700. #endif
  11701. #else
  11702. #if defined(C89ATOMIC_HAS_8)
  11703. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11704. {
  11705. #if defined(C89ATOMIC_ARM)
  11706. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange8, c89atomic_uint8, char);
  11707. #else
  11708. (void)order;
  11709. return (c89atomic_uint8)_InterlockedExchange8((volatile char*)dst, (char)src);
  11710. #endif
  11711. }
  11712. #endif
  11713. #if defined(C89ATOMIC_HAS_16)
  11714. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11715. {
  11716. #if defined(C89ATOMIC_ARM)
  11717. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange16, c89atomic_uint16, short);
  11718. #else
  11719. (void)order;
  11720. return (c89atomic_uint16)_InterlockedExchange16((volatile short*)dst, (short)src);
  11721. #endif
  11722. }
  11723. #endif
  11724. #if defined(C89ATOMIC_HAS_32)
  11725. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11726. {
  11727. #if defined(C89ATOMIC_ARM)
  11728. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange, c89atomic_uint32, long);
  11729. #else
  11730. (void)order;
  11731. return (c89atomic_uint32)_InterlockedExchange((volatile long*)dst, (long)src);
  11732. #endif
  11733. }
  11734. #endif
  11735. #if defined(C89ATOMIC_HAS_64) && defined(C89ATOMIC_64BIT)
  11736. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11737. {
  11738. #if defined(C89ATOMIC_ARM)
  11739. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange64, c89atomic_uint64, long long);
  11740. #else
  11741. (void)order;
  11742. return (c89atomic_uint64)_InterlockedExchange64((volatile long long*)dst, (long long)src);
  11743. #endif
  11744. }
  11745. #else
  11746. #endif
  11747. #endif
  11748. #if defined(C89ATOMIC_HAS_64) && !defined(C89ATOMIC_64BIT)
  11749. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11750. {
  11751. c89atomic_uint64 oldValue;
  11752. do {
  11753. oldValue = *dst;
  11754. } while (c89atomic_compare_and_swap_64(dst, oldValue, src) != oldValue);
  11755. (void)order;
  11756. return oldValue;
  11757. }
  11758. #endif
  11759. #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11760. #if defined(C89ATOMIC_HAS_8)
  11761. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11762. {
  11763. c89atomic_uint8 result = 0;
  11764. (void)order;
  11765. __asm {
  11766. mov ecx, dst
  11767. mov al, src
  11768. lock xadd [ecx], al
  11769. mov result, al
  11770. }
  11771. return result;
  11772. }
  11773. #endif
  11774. #if defined(C89ATOMIC_HAS_16)
  11775. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11776. {
  11777. c89atomic_uint16 result = 0;
  11778. (void)order;
  11779. __asm {
  11780. mov ecx, dst
  11781. mov ax, src
  11782. lock xadd [ecx], ax
  11783. mov result, ax
  11784. }
  11785. return result;
  11786. }
  11787. #endif
  11788. #if defined(C89ATOMIC_HAS_32)
  11789. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11790. {
  11791. c89atomic_uint32 result = 0;
  11792. (void)order;
  11793. __asm {
  11794. mov ecx, dst
  11795. mov eax, src
  11796. lock xadd [ecx], eax
  11797. mov result, eax
  11798. }
  11799. return result;
  11800. }
  11801. #endif
  11802. #else
  11803. #if defined(C89ATOMIC_HAS_8)
  11804. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11805. {
  11806. #if defined(C89ATOMIC_ARM)
  11807. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd8, c89atomic_uint8, char);
  11808. #else
  11809. (void)order;
  11810. return (c89atomic_uint8)_InterlockedExchangeAdd8((volatile char*)dst, (char)src);
  11811. #endif
  11812. }
  11813. #endif
  11814. #if defined(C89ATOMIC_HAS_16)
  11815. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11816. {
  11817. #if defined(C89ATOMIC_ARM)
  11818. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd16, c89atomic_uint16, short);
  11819. #else
  11820. (void)order;
  11821. return (c89atomic_uint16)_InterlockedExchangeAdd16((volatile short*)dst, (short)src);
  11822. #endif
  11823. }
  11824. #endif
  11825. #if defined(C89ATOMIC_HAS_32)
  11826. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11827. {
  11828. #if defined(C89ATOMIC_ARM)
  11829. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd, c89atomic_uint32, long);
  11830. #else
  11831. (void)order;
  11832. return (c89atomic_uint32)_InterlockedExchangeAdd((volatile long*)dst, (long)src);
  11833. #endif
  11834. }
  11835. #endif
  11836. #if defined(C89ATOMIC_HAS_64) && defined(C89ATOMIC_64BIT)
  11837. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11838. {
  11839. #if defined(C89ATOMIC_ARM)
  11840. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd64, c89atomic_uint64, long long);
  11841. #else
  11842. (void)order;
  11843. return (c89atomic_uint64)_InterlockedExchangeAdd64((volatile long long*)dst, (long long)src);
  11844. #endif
  11845. }
  11846. #else
  11847. #endif
  11848. #endif
  11849. #if defined(C89ATOMIC_HAS_64) && !defined(C89ATOMIC_64BIT)
  11850. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11851. {
  11852. c89atomic_uint64 oldValue;
  11853. c89atomic_uint64 newValue;
  11854. do {
  11855. oldValue = *dst;
  11856. newValue = oldValue + src;
  11857. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  11858. (void)order;
  11859. return oldValue;
  11860. }
  11861. #endif
  11862. #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11863. static C89ATOMIC_INLINE void __stdcall c89atomic_thread_fence(c89atomic_memory_order order)
  11864. {
  11865. (void)order;
  11866. __asm {
  11867. lock add [esp], 0
  11868. }
  11869. }
  11870. #else
  11871. #if defined(C89ATOMIC_X64)
  11872. #define c89atomic_thread_fence(order) __faststorefence(), (void)order
  11873. #elif defined(C89ATOMIC_ARM64)
  11874. #define c89atomic_thread_fence(order) __dmb(_ARM64_BARRIER_ISH), (void)order
  11875. #else
  11876. static C89ATOMIC_INLINE void c89atomic_thread_fence(c89atomic_memory_order order)
  11877. {
  11878. volatile c89atomic_uint32 barrier = 0;
  11879. c89atomic_fetch_add_explicit_32(&barrier, 0, order);
  11880. }
  11881. #endif
  11882. #endif
  11883. #define c89atomic_compiler_fence() c89atomic_thread_fence(c89atomic_memory_order_seq_cst)
  11884. #define c89atomic_signal_fence(order) c89atomic_thread_fence(order)
  11885. #if defined(C89ATOMIC_HAS_8)
  11886. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_load_explicit_8(volatile const c89atomic_uint8* ptr, c89atomic_memory_order order)
  11887. {
  11888. #if defined(C89ATOMIC_ARM)
  11889. C89ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange8, c89atomic_uint8, char);
  11890. #else
  11891. (void)order;
  11892. return c89atomic_compare_and_swap_8((volatile c89atomic_uint8*)ptr, 0, 0);
  11893. #endif
  11894. }
  11895. #endif
  11896. #if defined(C89ATOMIC_HAS_16)
  11897. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_load_explicit_16(volatile const c89atomic_uint16* ptr, c89atomic_memory_order order)
  11898. {
  11899. #if defined(C89ATOMIC_ARM)
  11900. C89ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange16, c89atomic_uint16, short);
  11901. #else
  11902. (void)order;
  11903. return c89atomic_compare_and_swap_16((volatile c89atomic_uint16*)ptr, 0, 0);
  11904. #endif
  11905. }
  11906. #endif
  11907. #if defined(C89ATOMIC_HAS_32)
  11908. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_load_explicit_32(volatile const c89atomic_uint32* ptr, c89atomic_memory_order order)
  11909. {
  11910. #if defined(C89ATOMIC_ARM)
  11911. C89ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange, c89atomic_uint32, long);
  11912. #else
  11913. (void)order;
  11914. return c89atomic_compare_and_swap_32((volatile c89atomic_uint32*)ptr, 0, 0);
  11915. #endif
  11916. }
  11917. #endif
  11918. #if defined(C89ATOMIC_HAS_64)
  11919. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_load_explicit_64(volatile const c89atomic_uint64* ptr, c89atomic_memory_order order)
  11920. {
  11921. #if defined(C89ATOMIC_ARM)
  11922. C89ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange64, c89atomic_uint64, long long);
  11923. #else
  11924. (void)order;
  11925. return c89atomic_compare_and_swap_64((volatile c89atomic_uint64*)ptr, 0, 0);
  11926. #endif
  11927. }
  11928. #endif
  11929. #if defined(C89ATOMIC_HAS_8)
  11930. #define c89atomic_store_explicit_8( dst, src, order) (void)c89atomic_exchange_explicit_8 (dst, src, order)
  11931. #endif
  11932. #if defined(C89ATOMIC_HAS_16)
  11933. #define c89atomic_store_explicit_16(dst, src, order) (void)c89atomic_exchange_explicit_16(dst, src, order)
  11934. #endif
  11935. #if defined(C89ATOMIC_HAS_32)
  11936. #define c89atomic_store_explicit_32(dst, src, order) (void)c89atomic_exchange_explicit_32(dst, src, order)
  11937. #endif
  11938. #if defined(C89ATOMIC_HAS_64)
  11939. #define c89atomic_store_explicit_64(dst, src, order) (void)c89atomic_exchange_explicit_64(dst, src, order)
  11940. #endif
  11941. #if defined(C89ATOMIC_HAS_8)
  11942. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11943. {
  11944. c89atomic_uint8 oldValue;
  11945. c89atomic_uint8 newValue;
  11946. do {
  11947. oldValue = *dst;
  11948. newValue = (c89atomic_uint8)(oldValue - src);
  11949. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  11950. (void)order;
  11951. return oldValue;
  11952. }
  11953. #endif
  11954. #if defined(C89ATOMIC_HAS_16)
  11955. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11956. {
  11957. c89atomic_uint16 oldValue;
  11958. c89atomic_uint16 newValue;
  11959. do {
  11960. oldValue = *dst;
  11961. newValue = (c89atomic_uint16)(oldValue - src);
  11962. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  11963. (void)order;
  11964. return oldValue;
  11965. }
  11966. #endif
  11967. #if defined(C89ATOMIC_HAS_32)
  11968. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11969. {
  11970. c89atomic_uint32 oldValue;
  11971. c89atomic_uint32 newValue;
  11972. do {
  11973. oldValue = *dst;
  11974. newValue = oldValue - src;
  11975. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  11976. (void)order;
  11977. return oldValue;
  11978. }
  11979. #endif
  11980. #if defined(C89ATOMIC_HAS_64)
  11981. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11982. {
  11983. c89atomic_uint64 oldValue;
  11984. c89atomic_uint64 newValue;
  11985. do {
  11986. oldValue = *dst;
  11987. newValue = oldValue - src;
  11988. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  11989. (void)order;
  11990. return oldValue;
  11991. }
  11992. #endif
  11993. #if defined(C89ATOMIC_HAS_8)
  11994. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11995. {
  11996. #if defined(C89ATOMIC_ARM)
  11997. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd8, c89atomic_uint8, char);
  11998. #else
  11999. c89atomic_uint8 oldValue;
  12000. c89atomic_uint8 newValue;
  12001. do {
  12002. oldValue = *dst;
  12003. newValue = (c89atomic_uint8)(oldValue & src);
  12004. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12005. (void)order;
  12006. return oldValue;
  12007. #endif
  12008. }
  12009. #endif
  12010. #if defined(C89ATOMIC_HAS_16)
  12011. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12012. {
  12013. #if defined(C89ATOMIC_ARM)
  12014. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd16, c89atomic_uint16, short);
  12015. #else
  12016. c89atomic_uint16 oldValue;
  12017. c89atomic_uint16 newValue;
  12018. do {
  12019. oldValue = *dst;
  12020. newValue = (c89atomic_uint16)(oldValue & src);
  12021. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12022. (void)order;
  12023. return oldValue;
  12024. #endif
  12025. }
  12026. #endif
  12027. #if defined(C89ATOMIC_HAS_32)
  12028. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12029. {
  12030. #if defined(C89ATOMIC_ARM)
  12031. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd, c89atomic_uint32, long);
  12032. #else
  12033. c89atomic_uint32 oldValue;
  12034. c89atomic_uint32 newValue;
  12035. do {
  12036. oldValue = *dst;
  12037. newValue = oldValue & src;
  12038. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12039. (void)order;
  12040. return oldValue;
  12041. #endif
  12042. }
  12043. #endif
  12044. #if defined(C89ATOMIC_HAS_64)
  12045. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12046. {
  12047. #if defined(C89ATOMIC_ARM)
  12048. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd64, c89atomic_uint64, long long);
  12049. #else
  12050. c89atomic_uint64 oldValue;
  12051. c89atomic_uint64 newValue;
  12052. do {
  12053. oldValue = *dst;
  12054. newValue = oldValue & src;
  12055. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12056. (void)order;
  12057. return oldValue;
  12058. #endif
  12059. }
  12060. #endif
  12061. #if defined(C89ATOMIC_HAS_8)
  12062. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12063. {
  12064. #if defined(C89ATOMIC_ARM)
  12065. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor8, c89atomic_uint8, char);
  12066. #else
  12067. c89atomic_uint8 oldValue;
  12068. c89atomic_uint8 newValue;
  12069. do {
  12070. oldValue = *dst;
  12071. newValue = (c89atomic_uint8)(oldValue ^ src);
  12072. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12073. (void)order;
  12074. return oldValue;
  12075. #endif
  12076. }
  12077. #endif
  12078. #if defined(C89ATOMIC_HAS_16)
  12079. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12080. {
  12081. #if defined(C89ATOMIC_ARM)
  12082. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor16, c89atomic_uint16, short);
  12083. #else
  12084. c89atomic_uint16 oldValue;
  12085. c89atomic_uint16 newValue;
  12086. do {
  12087. oldValue = *dst;
  12088. newValue = (c89atomic_uint16)(oldValue ^ src);
  12089. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12090. (void)order;
  12091. return oldValue;
  12092. #endif
  12093. }
  12094. #endif
  12095. #if defined(C89ATOMIC_HAS_32)
  12096. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12097. {
  12098. #if defined(C89ATOMIC_ARM)
  12099. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor, c89atomic_uint32, long);
  12100. #else
  12101. c89atomic_uint32 oldValue;
  12102. c89atomic_uint32 newValue;
  12103. do {
  12104. oldValue = *dst;
  12105. newValue = oldValue ^ src;
  12106. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12107. (void)order;
  12108. return oldValue;
  12109. #endif
  12110. }
  12111. #endif
  12112. #if defined(C89ATOMIC_HAS_64)
  12113. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12114. {
  12115. #if defined(C89ATOMIC_ARM)
  12116. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor64, c89atomic_uint64, long long);
  12117. #else
  12118. c89atomic_uint64 oldValue;
  12119. c89atomic_uint64 newValue;
  12120. do {
  12121. oldValue = *dst;
  12122. newValue = oldValue ^ src;
  12123. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12124. (void)order;
  12125. return oldValue;
  12126. #endif
  12127. }
  12128. #endif
  12129. #if defined(C89ATOMIC_HAS_8)
  12130. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12131. {
  12132. #if defined(C89ATOMIC_ARM)
  12133. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr8, c89atomic_uint8, char);
  12134. #else
  12135. c89atomic_uint8 oldValue;
  12136. c89atomic_uint8 newValue;
  12137. do {
  12138. oldValue = *dst;
  12139. newValue = (c89atomic_uint8)(oldValue | src);
  12140. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12141. (void)order;
  12142. return oldValue;
  12143. #endif
  12144. }
  12145. #endif
  12146. #if defined(C89ATOMIC_HAS_16)
  12147. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12148. {
  12149. #if defined(C89ATOMIC_ARM)
  12150. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr16, c89atomic_uint16, short);
  12151. #else
  12152. c89atomic_uint16 oldValue;
  12153. c89atomic_uint16 newValue;
  12154. do {
  12155. oldValue = *dst;
  12156. newValue = (c89atomic_uint16)(oldValue | src);
  12157. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12158. (void)order;
  12159. return oldValue;
  12160. #endif
  12161. }
  12162. #endif
  12163. #if defined(C89ATOMIC_HAS_32)
  12164. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12165. {
  12166. #if defined(C89ATOMIC_ARM)
  12167. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr, c89atomic_uint32, long);
  12168. #else
  12169. c89atomic_uint32 oldValue;
  12170. c89atomic_uint32 newValue;
  12171. do {
  12172. oldValue = *dst;
  12173. newValue = oldValue | src;
  12174. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12175. (void)order;
  12176. return oldValue;
  12177. #endif
  12178. }
  12179. #endif
  12180. #if defined(C89ATOMIC_HAS_64)
  12181. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12182. {
  12183. #if defined(C89ATOMIC_ARM)
  12184. C89ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr64, c89atomic_uint64, long long);
  12185. #else
  12186. c89atomic_uint64 oldValue;
  12187. c89atomic_uint64 newValue;
  12188. do {
  12189. oldValue = *dst;
  12190. newValue = oldValue | src;
  12191. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12192. (void)order;
  12193. return oldValue;
  12194. #endif
  12195. }
  12196. #endif
  12197. #if defined(C89ATOMIC_HAS_8)
  12198. #define c89atomic_test_and_set_explicit_8( dst, order) c89atomic_exchange_explicit_8 (dst, 1, order)
  12199. #endif
  12200. #if defined(C89ATOMIC_HAS_16)
  12201. #define c89atomic_test_and_set_explicit_16(dst, order) c89atomic_exchange_explicit_16(dst, 1, order)
  12202. #endif
  12203. #if defined(C89ATOMIC_HAS_32)
  12204. #define c89atomic_test_and_set_explicit_32(dst, order) c89atomic_exchange_explicit_32(dst, 1, order)
  12205. #endif
  12206. #if defined(C89ATOMIC_HAS_64)
  12207. #define c89atomic_test_and_set_explicit_64(dst, order) c89atomic_exchange_explicit_64(dst, 1, order)
  12208. #endif
  12209. #if defined(C89ATOMIC_HAS_8)
  12210. #define c89atomic_clear_explicit_8( dst, order) c89atomic_store_explicit_8 (dst, 0, order)
  12211. #endif
  12212. #if defined(C89ATOMIC_HAS_16)
  12213. #define c89atomic_clear_explicit_16(dst, order) c89atomic_store_explicit_16(dst, 0, order)
  12214. #endif
  12215. #if defined(C89ATOMIC_HAS_32)
  12216. #define c89atomic_clear_explicit_32(dst, order) c89atomic_store_explicit_32(dst, 0, order)
  12217. #endif
  12218. #if defined(C89ATOMIC_HAS_64)
  12219. #define c89atomic_clear_explicit_64(dst, order) c89atomic_store_explicit_64(dst, 0, order)
  12220. #endif
  12221. #if defined(C89ATOMIC_HAS_8)
  12222. typedef c89atomic_uint8 c89atomic_flag;
  12223. #define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_bool)c89atomic_test_and_set_explicit_8(ptr, order)
  12224. #define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_8(ptr, order)
  12225. #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_8(ptr, order)
  12226. #else
  12227. typedef c89atomic_uint32 c89atomic_flag;
  12228. #define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_bool)c89atomic_test_and_set_explicit_32(ptr, order)
  12229. #define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_32(ptr, order)
  12230. #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_32(ptr, order)
  12231. #endif
  12232. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
  12233. #define C89ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE
  12234. #define C89ATOMIC_HAS_NATIVE_IS_LOCK_FREE
  12235. #define c89atomic_memory_order_relaxed __ATOMIC_RELAXED
  12236. #define c89atomic_memory_order_consume __ATOMIC_CONSUME
  12237. #define c89atomic_memory_order_acquire __ATOMIC_ACQUIRE
  12238. #define c89atomic_memory_order_release __ATOMIC_RELEASE
  12239. #define c89atomic_memory_order_acq_rel __ATOMIC_ACQ_REL
  12240. #define c89atomic_memory_order_seq_cst __ATOMIC_SEQ_CST
  12241. #define c89atomic_compiler_fence() __asm__ __volatile__("":::"memory")
  12242. #define c89atomic_thread_fence(order) __atomic_thread_fence(order)
  12243. #define c89atomic_signal_fence(order) __atomic_signal_fence(order)
  12244. #define c89atomic_is_lock_free_8(ptr) __atomic_is_lock_free(1, ptr)
  12245. #define c89atomic_is_lock_free_16(ptr) __atomic_is_lock_free(2, ptr)
  12246. #define c89atomic_is_lock_free_32(ptr) __atomic_is_lock_free(4, ptr)
  12247. #define c89atomic_is_lock_free_64(ptr) __atomic_is_lock_free(8, ptr)
  12248. #define c89atomic_test_and_set_explicit_8( dst, order) __atomic_exchange_n(dst, 1, order)
  12249. #define c89atomic_test_and_set_explicit_16(dst, order) __atomic_exchange_n(dst, 1, order)
  12250. #define c89atomic_test_and_set_explicit_32(dst, order) __atomic_exchange_n(dst, 1, order)
  12251. #define c89atomic_test_and_set_explicit_64(dst, order) __atomic_exchange_n(dst, 1, order)
  12252. #define c89atomic_clear_explicit_8( dst, order) __atomic_store_n(dst, 0, order)
  12253. #define c89atomic_clear_explicit_16(dst, order) __atomic_store_n(dst, 0, order)
  12254. #define c89atomic_clear_explicit_32(dst, order) __atomic_store_n(dst, 0, order)
  12255. #define c89atomic_clear_explicit_64(dst, order) __atomic_store_n(dst, 0, order)
  12256. #define c89atomic_store_explicit_8( dst, src, order) __atomic_store_n(dst, src, order)
  12257. #define c89atomic_store_explicit_16(dst, src, order) __atomic_store_n(dst, src, order)
  12258. #define c89atomic_store_explicit_32(dst, src, order) __atomic_store_n(dst, src, order)
  12259. #define c89atomic_store_explicit_64(dst, src, order) __atomic_store_n(dst, src, order)
  12260. #define c89atomic_load_explicit_8( dst, order) __atomic_load_n(dst, order)
  12261. #define c89atomic_load_explicit_16(dst, order) __atomic_load_n(dst, order)
  12262. #define c89atomic_load_explicit_32(dst, order) __atomic_load_n(dst, order)
  12263. #define c89atomic_load_explicit_64(dst, order) __atomic_load_n(dst, order)
  12264. #define c89atomic_exchange_explicit_8( dst, src, order) __atomic_exchange_n(dst, src, order)
  12265. #define c89atomic_exchange_explicit_16(dst, src, order) __atomic_exchange_n(dst, src, order)
  12266. #define c89atomic_exchange_explicit_32(dst, src, order) __atomic_exchange_n(dst, src, order)
  12267. #define c89atomic_exchange_explicit_64(dst, src, order) __atomic_exchange_n(dst, src, order)
  12268. #define c89atomic_compare_exchange_strong_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  12269. #define c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  12270. #define c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  12271. #define c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  12272. #define c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  12273. #define c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  12274. #define c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  12275. #define c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  12276. #define c89atomic_fetch_add_explicit_8( dst, src, order) __atomic_fetch_add(dst, src, order)
  12277. #define c89atomic_fetch_add_explicit_16(dst, src, order) __atomic_fetch_add(dst, src, order)
  12278. #define c89atomic_fetch_add_explicit_32(dst, src, order) __atomic_fetch_add(dst, src, order)
  12279. #define c89atomic_fetch_add_explicit_64(dst, src, order) __atomic_fetch_add(dst, src, order)
  12280. #define c89atomic_fetch_sub_explicit_8( dst, src, order) __atomic_fetch_sub(dst, src, order)
  12281. #define c89atomic_fetch_sub_explicit_16(dst, src, order) __atomic_fetch_sub(dst, src, order)
  12282. #define c89atomic_fetch_sub_explicit_32(dst, src, order) __atomic_fetch_sub(dst, src, order)
  12283. #define c89atomic_fetch_sub_explicit_64(dst, src, order) __atomic_fetch_sub(dst, src, order)
  12284. #define c89atomic_fetch_or_explicit_8( dst, src, order) __atomic_fetch_or(dst, src, order)
  12285. #define c89atomic_fetch_or_explicit_16(dst, src, order) __atomic_fetch_or(dst, src, order)
  12286. #define c89atomic_fetch_or_explicit_32(dst, src, order) __atomic_fetch_or(dst, src, order)
  12287. #define c89atomic_fetch_or_explicit_64(dst, src, order) __atomic_fetch_or(dst, src, order)
  12288. #define c89atomic_fetch_xor_explicit_8( dst, src, order) __atomic_fetch_xor(dst, src, order)
  12289. #define c89atomic_fetch_xor_explicit_16(dst, src, order) __atomic_fetch_xor(dst, src, order)
  12290. #define c89atomic_fetch_xor_explicit_32(dst, src, order) __atomic_fetch_xor(dst, src, order)
  12291. #define c89atomic_fetch_xor_explicit_64(dst, src, order) __atomic_fetch_xor(dst, src, order)
  12292. #define c89atomic_fetch_and_explicit_8( dst, src, order) __atomic_fetch_and(dst, src, order)
  12293. #define c89atomic_fetch_and_explicit_16(dst, src, order) __atomic_fetch_and(dst, src, order)
  12294. #define c89atomic_fetch_and_explicit_32(dst, src, order) __atomic_fetch_and(dst, src, order)
  12295. #define c89atomic_fetch_and_explicit_64(dst, src, order) __atomic_fetch_and(dst, src, order)
  12296. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_compare_and_swap_8(volatile c89atomic_uint8* dst, c89atomic_uint8 expected, c89atomic_uint8 desired)
  12297. {
  12298. __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
  12299. return expected;
  12300. }
  12301. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_compare_and_swap_16(volatile c89atomic_uint16* dst, c89atomic_uint16 expected, c89atomic_uint16 desired)
  12302. {
  12303. __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
  12304. return expected;
  12305. }
  12306. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_compare_and_swap_32(volatile c89atomic_uint32* dst, c89atomic_uint32 expected, c89atomic_uint32 desired)
  12307. {
  12308. __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
  12309. return expected;
  12310. }
  12311. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_compare_and_swap_64(volatile c89atomic_uint64* dst, c89atomic_uint64 expected, c89atomic_uint64 desired)
  12312. {
  12313. __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
  12314. return expected;
  12315. }
  12316. typedef c89atomic_uint8 c89atomic_flag;
  12317. #define c89atomic_flag_test_and_set_explicit(dst, order) (c89atomic_bool)__atomic_test_and_set(dst, order)
  12318. #define c89atomic_flag_clear_explicit(dst, order) __atomic_clear(dst, order)
  12319. #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_8(ptr, order)
  12320. #else
  12321. #define c89atomic_memory_order_relaxed 1
  12322. #define c89atomic_memory_order_consume 2
  12323. #define c89atomic_memory_order_acquire 3
  12324. #define c89atomic_memory_order_release 4
  12325. #define c89atomic_memory_order_acq_rel 5
  12326. #define c89atomic_memory_order_seq_cst 6
  12327. #define c89atomic_compiler_fence() __asm__ __volatile__("":::"memory")
  12328. #if defined(__GNUC__)
  12329. #define c89atomic_thread_fence(order) __sync_synchronize(), (void)order
  12330. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12331. {
  12332. if (order > c89atomic_memory_order_acquire) {
  12333. __sync_synchronize();
  12334. }
  12335. return __sync_lock_test_and_set(dst, src);
  12336. }
  12337. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12338. {
  12339. c89atomic_uint16 oldValue;
  12340. do {
  12341. oldValue = *dst;
  12342. } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
  12343. (void)order;
  12344. return oldValue;
  12345. }
  12346. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12347. {
  12348. c89atomic_uint32 oldValue;
  12349. do {
  12350. oldValue = *dst;
  12351. } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
  12352. (void)order;
  12353. return oldValue;
  12354. }
  12355. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12356. {
  12357. c89atomic_uint64 oldValue;
  12358. do {
  12359. oldValue = *dst;
  12360. } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
  12361. (void)order;
  12362. return oldValue;
  12363. }
  12364. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12365. {
  12366. (void)order;
  12367. return __sync_fetch_and_add(dst, src);
  12368. }
  12369. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12370. {
  12371. (void)order;
  12372. return __sync_fetch_and_add(dst, src);
  12373. }
  12374. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12375. {
  12376. (void)order;
  12377. return __sync_fetch_and_add(dst, src);
  12378. }
  12379. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12380. {
  12381. (void)order;
  12382. return __sync_fetch_and_add(dst, src);
  12383. }
  12384. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12385. {
  12386. (void)order;
  12387. return __sync_fetch_and_sub(dst, src);
  12388. }
  12389. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12390. {
  12391. (void)order;
  12392. return __sync_fetch_and_sub(dst, src);
  12393. }
  12394. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12395. {
  12396. (void)order;
  12397. return __sync_fetch_and_sub(dst, src);
  12398. }
  12399. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12400. {
  12401. (void)order;
  12402. return __sync_fetch_and_sub(dst, src);
  12403. }
  12404. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12405. {
  12406. (void)order;
  12407. return __sync_fetch_and_or(dst, src);
  12408. }
  12409. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12410. {
  12411. (void)order;
  12412. return __sync_fetch_and_or(dst, src);
  12413. }
  12414. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12415. {
  12416. (void)order;
  12417. return __sync_fetch_and_or(dst, src);
  12418. }
  12419. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12420. {
  12421. (void)order;
  12422. return __sync_fetch_and_or(dst, src);
  12423. }
  12424. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12425. {
  12426. (void)order;
  12427. return __sync_fetch_and_xor(dst, src);
  12428. }
  12429. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12430. {
  12431. (void)order;
  12432. return __sync_fetch_and_xor(dst, src);
  12433. }
  12434. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12435. {
  12436. (void)order;
  12437. return __sync_fetch_and_xor(dst, src);
  12438. }
  12439. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12440. {
  12441. (void)order;
  12442. return __sync_fetch_and_xor(dst, src);
  12443. }
  12444. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12445. {
  12446. (void)order;
  12447. return __sync_fetch_and_and(dst, src);
  12448. }
  12449. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12450. {
  12451. (void)order;
  12452. return __sync_fetch_and_and(dst, src);
  12453. }
  12454. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12455. {
  12456. (void)order;
  12457. return __sync_fetch_and_and(dst, src);
  12458. }
  12459. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12460. {
  12461. (void)order;
  12462. return __sync_fetch_and_and(dst, src);
  12463. }
  12464. #define c89atomic_compare_and_swap_8( dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12465. #define c89atomic_compare_and_swap_16(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12466. #define c89atomic_compare_and_swap_32(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12467. #define c89atomic_compare_and_swap_64(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12468. #else
  12469. #if defined(C89ATOMIC_X86)
  12470. #define c89atomic_thread_fence(order) __asm__ __volatile__("lock; addl $0, (%%esp)" ::: "memory", "cc")
  12471. #elif defined(C89ATOMIC_X64)
  12472. #define c89atomic_thread_fence(order) __asm__ __volatile__("lock; addq $0, (%%rsp)" ::: "memory", "cc")
  12473. #else
  12474. #error Unsupported architecture. Please submit a feature request.
  12475. #endif
  12476. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_compare_and_swap_8(volatile c89atomic_uint8* dst, c89atomic_uint8 expected, c89atomic_uint8 desired)
  12477. {
  12478. c89atomic_uint8 result;
  12479. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12480. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12481. #else
  12482. #error Unsupported architecture. Please submit a feature request.
  12483. #endif
  12484. return result;
  12485. }
  12486. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_compare_and_swap_16(volatile c89atomic_uint16* dst, c89atomic_uint16 expected, c89atomic_uint16 desired)
  12487. {
  12488. c89atomic_uint16 result;
  12489. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12490. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12491. #else
  12492. #error Unsupported architecture. Please submit a feature request.
  12493. #endif
  12494. return result;
  12495. }
  12496. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_compare_and_swap_32(volatile c89atomic_uint32* dst, c89atomic_uint32 expected, c89atomic_uint32 desired)
  12497. {
  12498. c89atomic_uint32 result;
  12499. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12500. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12501. #else
  12502. #error Unsupported architecture. Please submit a feature request.
  12503. #endif
  12504. return result;
  12505. }
  12506. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_compare_and_swap_64(volatile c89atomic_uint64* dst, c89atomic_uint64 expected, c89atomic_uint64 desired)
  12507. {
  12508. volatile c89atomic_uint64 result;
  12509. #if defined(C89ATOMIC_X86)
  12510. c89atomic_uint32 resultEAX;
  12511. c89atomic_uint32 resultEDX;
  12512. __asm__ __volatile__("push %%ebx; xchg %5, %%ebx; lock; cmpxchg8b %0; pop %%ebx" : "+m"(*dst), "=a"(resultEAX), "=d"(resultEDX) : "a"(expected & 0xFFFFFFFF), "d"(expected >> 32), "r"(desired & 0xFFFFFFFF), "c"(desired >> 32) : "cc");
  12513. result = ((c89atomic_uint64)resultEDX << 32) | resultEAX;
  12514. #elif defined(C89ATOMIC_X64)
  12515. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12516. #else
  12517. #error Unsupported architecture. Please submit a feature request.
  12518. #endif
  12519. return result;
  12520. }
  12521. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12522. {
  12523. c89atomic_uint8 result = 0;
  12524. (void)order;
  12525. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12526. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12527. #else
  12528. #error Unsupported architecture. Please submit a feature request.
  12529. #endif
  12530. return result;
  12531. }
  12532. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12533. {
  12534. c89atomic_uint16 result = 0;
  12535. (void)order;
  12536. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12537. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12538. #else
  12539. #error Unsupported architecture. Please submit a feature request.
  12540. #endif
  12541. return result;
  12542. }
  12543. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12544. {
  12545. c89atomic_uint32 result;
  12546. (void)order;
  12547. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12548. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12549. #else
  12550. #error Unsupported architecture. Please submit a feature request.
  12551. #endif
  12552. return result;
  12553. }
  12554. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12555. {
  12556. c89atomic_uint64 result;
  12557. (void)order;
  12558. #if defined(C89ATOMIC_X86)
  12559. do {
  12560. result = *dst;
  12561. } while (c89atomic_compare_and_swap_64(dst, result, src) != result);
  12562. #elif defined(C89ATOMIC_X64)
  12563. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12564. #else
  12565. #error Unsupported architecture. Please submit a feature request.
  12566. #endif
  12567. return result;
  12568. }
  12569. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12570. {
  12571. c89atomic_uint8 result;
  12572. (void)order;
  12573. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12574. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12575. #else
  12576. #error Unsupported architecture. Please submit a feature request.
  12577. #endif
  12578. return result;
  12579. }
  12580. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12581. {
  12582. c89atomic_uint16 result;
  12583. (void)order;
  12584. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12585. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12586. #else
  12587. #error Unsupported architecture. Please submit a feature request.
  12588. #endif
  12589. return result;
  12590. }
  12591. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12592. {
  12593. c89atomic_uint32 result;
  12594. (void)order;
  12595. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12596. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12597. #else
  12598. #error Unsupported architecture. Please submit a feature request.
  12599. #endif
  12600. return result;
  12601. }
  12602. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12603. {
  12604. #if defined(C89ATOMIC_X86)
  12605. c89atomic_uint64 oldValue;
  12606. c89atomic_uint64 newValue;
  12607. (void)order;
  12608. do {
  12609. oldValue = *dst;
  12610. newValue = oldValue + src;
  12611. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12612. return oldValue;
  12613. #elif defined(C89ATOMIC_X64)
  12614. c89atomic_uint64 result;
  12615. (void)order;
  12616. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12617. return result;
  12618. #endif
  12619. }
  12620. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12621. {
  12622. c89atomic_uint8 oldValue;
  12623. c89atomic_uint8 newValue;
  12624. do {
  12625. oldValue = *dst;
  12626. newValue = (c89atomic_uint8)(oldValue - src);
  12627. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12628. (void)order;
  12629. return oldValue;
  12630. }
  12631. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12632. {
  12633. c89atomic_uint16 oldValue;
  12634. c89atomic_uint16 newValue;
  12635. do {
  12636. oldValue = *dst;
  12637. newValue = (c89atomic_uint16)(oldValue - src);
  12638. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12639. (void)order;
  12640. return oldValue;
  12641. }
  12642. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12643. {
  12644. c89atomic_uint32 oldValue;
  12645. c89atomic_uint32 newValue;
  12646. do {
  12647. oldValue = *dst;
  12648. newValue = oldValue - src;
  12649. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12650. (void)order;
  12651. return oldValue;
  12652. }
  12653. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12654. {
  12655. c89atomic_uint64 oldValue;
  12656. c89atomic_uint64 newValue;
  12657. do {
  12658. oldValue = *dst;
  12659. newValue = oldValue - src;
  12660. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12661. (void)order;
  12662. return oldValue;
  12663. }
  12664. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12665. {
  12666. c89atomic_uint8 oldValue;
  12667. c89atomic_uint8 newValue;
  12668. do {
  12669. oldValue = *dst;
  12670. newValue = (c89atomic_uint8)(oldValue & src);
  12671. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12672. (void)order;
  12673. return oldValue;
  12674. }
  12675. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12676. {
  12677. c89atomic_uint16 oldValue;
  12678. c89atomic_uint16 newValue;
  12679. do {
  12680. oldValue = *dst;
  12681. newValue = (c89atomic_uint16)(oldValue & src);
  12682. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12683. (void)order;
  12684. return oldValue;
  12685. }
  12686. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12687. {
  12688. c89atomic_uint32 oldValue;
  12689. c89atomic_uint32 newValue;
  12690. do {
  12691. oldValue = *dst;
  12692. newValue = oldValue & src;
  12693. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12694. (void)order;
  12695. return oldValue;
  12696. }
  12697. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12698. {
  12699. c89atomic_uint64 oldValue;
  12700. c89atomic_uint64 newValue;
  12701. do {
  12702. oldValue = *dst;
  12703. newValue = oldValue & src;
  12704. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12705. (void)order;
  12706. return oldValue;
  12707. }
  12708. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12709. {
  12710. c89atomic_uint8 oldValue;
  12711. c89atomic_uint8 newValue;
  12712. do {
  12713. oldValue = *dst;
  12714. newValue = (c89atomic_uint8)(oldValue ^ src);
  12715. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12716. (void)order;
  12717. return oldValue;
  12718. }
  12719. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12720. {
  12721. c89atomic_uint16 oldValue;
  12722. c89atomic_uint16 newValue;
  12723. do {
  12724. oldValue = *dst;
  12725. newValue = (c89atomic_uint16)(oldValue ^ src);
  12726. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12727. (void)order;
  12728. return oldValue;
  12729. }
  12730. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12731. {
  12732. c89atomic_uint32 oldValue;
  12733. c89atomic_uint32 newValue;
  12734. do {
  12735. oldValue = *dst;
  12736. newValue = oldValue ^ src;
  12737. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12738. (void)order;
  12739. return oldValue;
  12740. }
  12741. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12742. {
  12743. c89atomic_uint64 oldValue;
  12744. c89atomic_uint64 newValue;
  12745. do {
  12746. oldValue = *dst;
  12747. newValue = oldValue ^ src;
  12748. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12749. (void)order;
  12750. return oldValue;
  12751. }
  12752. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12753. {
  12754. c89atomic_uint8 oldValue;
  12755. c89atomic_uint8 newValue;
  12756. do {
  12757. oldValue = *dst;
  12758. newValue = (c89atomic_uint8)(oldValue | src);
  12759. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12760. (void)order;
  12761. return oldValue;
  12762. }
  12763. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12764. {
  12765. c89atomic_uint16 oldValue;
  12766. c89atomic_uint16 newValue;
  12767. do {
  12768. oldValue = *dst;
  12769. newValue = (c89atomic_uint16)(oldValue | src);
  12770. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12771. (void)order;
  12772. return oldValue;
  12773. }
  12774. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12775. {
  12776. c89atomic_uint32 oldValue;
  12777. c89atomic_uint32 newValue;
  12778. do {
  12779. oldValue = *dst;
  12780. newValue = oldValue | src;
  12781. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12782. (void)order;
  12783. return oldValue;
  12784. }
  12785. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12786. {
  12787. c89atomic_uint64 oldValue;
  12788. c89atomic_uint64 newValue;
  12789. do {
  12790. oldValue = *dst;
  12791. newValue = oldValue | src;
  12792. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12793. (void)order;
  12794. return oldValue;
  12795. }
  12796. #endif
  12797. #define c89atomic_signal_fence(order) c89atomic_thread_fence(order)
  12798. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_load_explicit_8(volatile const c89atomic_uint8* ptr, c89atomic_memory_order order)
  12799. {
  12800. (void)order;
  12801. return c89atomic_compare_and_swap_8((c89atomic_uint8*)ptr, 0, 0);
  12802. }
  12803. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_load_explicit_16(volatile const c89atomic_uint16* ptr, c89atomic_memory_order order)
  12804. {
  12805. (void)order;
  12806. return c89atomic_compare_and_swap_16((c89atomic_uint16*)ptr, 0, 0);
  12807. }
  12808. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_load_explicit_32(volatile const c89atomic_uint32* ptr, c89atomic_memory_order order)
  12809. {
  12810. (void)order;
  12811. return c89atomic_compare_and_swap_32((c89atomic_uint32*)ptr, 0, 0);
  12812. }
  12813. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_load_explicit_64(volatile const c89atomic_uint64* ptr, c89atomic_memory_order order)
  12814. {
  12815. (void)order;
  12816. return c89atomic_compare_and_swap_64((c89atomic_uint64*)ptr, 0, 0);
  12817. }
  12818. #define c89atomic_store_explicit_8( dst, src, order) (void)c89atomic_exchange_explicit_8 (dst, src, order)
  12819. #define c89atomic_store_explicit_16(dst, src, order) (void)c89atomic_exchange_explicit_16(dst, src, order)
  12820. #define c89atomic_store_explicit_32(dst, src, order) (void)c89atomic_exchange_explicit_32(dst, src, order)
  12821. #define c89atomic_store_explicit_64(dst, src, order) (void)c89atomic_exchange_explicit_64(dst, src, order)
  12822. #define c89atomic_test_and_set_explicit_8( dst, order) c89atomic_exchange_explicit_8 (dst, 1, order)
  12823. #define c89atomic_test_and_set_explicit_16(dst, order) c89atomic_exchange_explicit_16(dst, 1, order)
  12824. #define c89atomic_test_and_set_explicit_32(dst, order) c89atomic_exchange_explicit_32(dst, 1, order)
  12825. #define c89atomic_test_and_set_explicit_64(dst, order) c89atomic_exchange_explicit_64(dst, 1, order)
  12826. #define c89atomic_clear_explicit_8( dst, order) c89atomic_store_explicit_8 (dst, 0, order)
  12827. #define c89atomic_clear_explicit_16(dst, order) c89atomic_store_explicit_16(dst, 0, order)
  12828. #define c89atomic_clear_explicit_32(dst, order) c89atomic_store_explicit_32(dst, 0, order)
  12829. #define c89atomic_clear_explicit_64(dst, order) c89atomic_store_explicit_64(dst, 0, order)
  12830. typedef c89atomic_uint8 c89atomic_flag;
  12831. #define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_bool)c89atomic_test_and_set_explicit_8(ptr, order)
  12832. #define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_8(ptr, order)
  12833. #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_8(ptr, order)
  12834. #endif
  12835. #if !defined(C89ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE)
  12836. #if defined(C89ATOMIC_HAS_8)
  12837. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8* expected, c89atomic_uint8 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12838. {
  12839. c89atomic_uint8 expectedValue;
  12840. c89atomic_uint8 result;
  12841. (void)successOrder;
  12842. (void)failureOrder;
  12843. expectedValue = c89atomic_load_explicit_8(expected, c89atomic_memory_order_seq_cst);
  12844. result = c89atomic_compare_and_swap_8(dst, expectedValue, desired);
  12845. if (result == expectedValue) {
  12846. return 1;
  12847. } else {
  12848. c89atomic_store_explicit_8(expected, result, failureOrder);
  12849. return 0;
  12850. }
  12851. }
  12852. #endif
  12853. #if defined(C89ATOMIC_HAS_16)
  12854. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16* expected, c89atomic_uint16 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12855. {
  12856. c89atomic_uint16 expectedValue;
  12857. c89atomic_uint16 result;
  12858. (void)successOrder;
  12859. (void)failureOrder;
  12860. expectedValue = c89atomic_load_explicit_16(expected, c89atomic_memory_order_seq_cst);
  12861. result = c89atomic_compare_and_swap_16(dst, expectedValue, desired);
  12862. if (result == expectedValue) {
  12863. return 1;
  12864. } else {
  12865. c89atomic_store_explicit_16(expected, result, failureOrder);
  12866. return 0;
  12867. }
  12868. }
  12869. #endif
  12870. #if defined(C89ATOMIC_HAS_32)
  12871. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32* expected, c89atomic_uint32 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12872. {
  12873. c89atomic_uint32 expectedValue;
  12874. c89atomic_uint32 result;
  12875. (void)successOrder;
  12876. (void)failureOrder;
  12877. expectedValue = c89atomic_load_explicit_32(expected, c89atomic_memory_order_seq_cst);
  12878. result = c89atomic_compare_and_swap_32(dst, expectedValue, desired);
  12879. if (result == expectedValue) {
  12880. return 1;
  12881. } else {
  12882. c89atomic_store_explicit_32(expected, result, failureOrder);
  12883. return 0;
  12884. }
  12885. }
  12886. #endif
  12887. #if defined(C89ATOMIC_HAS_64)
  12888. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_64(volatile c89atomic_uint64* dst, volatile c89atomic_uint64* expected, c89atomic_uint64 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12889. {
  12890. c89atomic_uint64 expectedValue;
  12891. c89atomic_uint64 result;
  12892. (void)successOrder;
  12893. (void)failureOrder;
  12894. expectedValue = c89atomic_load_explicit_64(expected, c89atomic_memory_order_seq_cst);
  12895. result = c89atomic_compare_and_swap_64(dst, expectedValue, desired);
  12896. if (result == expectedValue) {
  12897. return 1;
  12898. } else {
  12899. c89atomic_store_explicit_64(expected, result, failureOrder);
  12900. return 0;
  12901. }
  12902. }
  12903. #endif
  12904. #define c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_8 (dst, expected, desired, successOrder, failureOrder)
  12905. #define c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder)
  12906. #define c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder)
  12907. #define c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder)
  12908. #endif
  12909. #if !defined(C89ATOMIC_HAS_NATIVE_IS_LOCK_FREE)
  12910. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_8(volatile void* ptr)
  12911. {
  12912. (void)ptr;
  12913. return 1;
  12914. }
  12915. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_16(volatile void* ptr)
  12916. {
  12917. (void)ptr;
  12918. return 1;
  12919. }
  12920. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_32(volatile void* ptr)
  12921. {
  12922. (void)ptr;
  12923. return 1;
  12924. }
  12925. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_64(volatile void* ptr)
  12926. {
  12927. (void)ptr;
  12928. #if defined(C89ATOMIC_64BIT)
  12929. return 1;
  12930. #else
  12931. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12932. return 1;
  12933. #else
  12934. return 0;
  12935. #endif
  12936. #endif
  12937. }
  12938. #endif
  12939. #if defined(C89ATOMIC_64BIT)
  12940. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_ptr(volatile void** ptr)
  12941. {
  12942. return c89atomic_is_lock_free_64((volatile c89atomic_uint64*)ptr);
  12943. }
  12944. static C89ATOMIC_INLINE void* c89atomic_load_explicit_ptr(volatile void** ptr, c89atomic_memory_order order)
  12945. {
  12946. return (void*)c89atomic_load_explicit_64((volatile c89atomic_uint64*)ptr, order);
  12947. }
  12948. static C89ATOMIC_INLINE void c89atomic_store_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
  12949. {
  12950. c89atomic_store_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)src, order);
  12951. }
  12952. static C89ATOMIC_INLINE void* c89atomic_exchange_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
  12953. {
  12954. return (void*)c89atomic_exchange_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)src, order);
  12955. }
  12956. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12957. {
  12958. return c89atomic_compare_exchange_strong_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder);
  12959. }
  12960. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12961. {
  12962. return c89atomic_compare_exchange_weak_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder);
  12963. }
  12964. static C89ATOMIC_INLINE void* c89atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired)
  12965. {
  12966. return (void*)c89atomic_compare_and_swap_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)expected, (c89atomic_uint64)desired);
  12967. }
  12968. #elif defined(C89ATOMIC_32BIT)
  12969. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_ptr(volatile void** ptr)
  12970. {
  12971. return c89atomic_is_lock_free_32((volatile c89atomic_uint32*)ptr);
  12972. }
  12973. static C89ATOMIC_INLINE void* c89atomic_load_explicit_ptr(volatile void** ptr, c89atomic_memory_order order)
  12974. {
  12975. return (void*)c89atomic_load_explicit_32((volatile c89atomic_uint32*)ptr, order);
  12976. }
  12977. static C89ATOMIC_INLINE void c89atomic_store_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
  12978. {
  12979. c89atomic_store_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)src, order);
  12980. }
  12981. static C89ATOMIC_INLINE void* c89atomic_exchange_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
  12982. {
  12983. return (void*)c89atomic_exchange_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)src, order);
  12984. }
  12985. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12986. {
  12987. return c89atomic_compare_exchange_strong_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder);
  12988. }
  12989. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12990. {
  12991. return c89atomic_compare_exchange_weak_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder);
  12992. }
  12993. static C89ATOMIC_INLINE void* c89atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired)
  12994. {
  12995. return (void*)c89atomic_compare_and_swap_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)expected, (c89atomic_uint32)desired);
  12996. }
  12997. #else
  12998. #error Unsupported architecture.
  12999. #endif
  13000. #define c89atomic_flag_test_and_set(ptr) c89atomic_flag_test_and_set_explicit(ptr, c89atomic_memory_order_seq_cst)
  13001. #define c89atomic_flag_clear(ptr) c89atomic_flag_clear_explicit(ptr, c89atomic_memory_order_seq_cst)
  13002. #define c89atomic_store_ptr(dst, src) c89atomic_store_explicit_ptr((volatile void**)dst, (void*)src, c89atomic_memory_order_seq_cst)
  13003. #define c89atomic_load_ptr(ptr) c89atomic_load_explicit_ptr((volatile void**)ptr, c89atomic_memory_order_seq_cst)
  13004. #define c89atomic_exchange_ptr(dst, src) c89atomic_exchange_explicit_ptr((volatile void**)dst, (void*)src, c89atomic_memory_order_seq_cst)
  13005. #define c89atomic_compare_exchange_strong_ptr(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_ptr((volatile void**)dst, (void**)expected, (void*)desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13006. #define c89atomic_compare_exchange_weak_ptr(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_ptr((volatile void**)dst, (void**)expected, (void*)desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13007. #define c89atomic_test_and_set_8( ptr) c89atomic_test_and_set_explicit_8( ptr, c89atomic_memory_order_seq_cst)
  13008. #define c89atomic_test_and_set_16(ptr) c89atomic_test_and_set_explicit_16(ptr, c89atomic_memory_order_seq_cst)
  13009. #define c89atomic_test_and_set_32(ptr) c89atomic_test_and_set_explicit_32(ptr, c89atomic_memory_order_seq_cst)
  13010. #define c89atomic_test_and_set_64(ptr) c89atomic_test_and_set_explicit_64(ptr, c89atomic_memory_order_seq_cst)
  13011. #define c89atomic_clear_8( ptr) c89atomic_clear_explicit_8( ptr, c89atomic_memory_order_seq_cst)
  13012. #define c89atomic_clear_16(ptr) c89atomic_clear_explicit_16(ptr, c89atomic_memory_order_seq_cst)
  13013. #define c89atomic_clear_32(ptr) c89atomic_clear_explicit_32(ptr, c89atomic_memory_order_seq_cst)
  13014. #define c89atomic_clear_64(ptr) c89atomic_clear_explicit_64(ptr, c89atomic_memory_order_seq_cst)
  13015. #define c89atomic_store_8( dst, src) c89atomic_store_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  13016. #define c89atomic_store_16(dst, src) c89atomic_store_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  13017. #define c89atomic_store_32(dst, src) c89atomic_store_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  13018. #define c89atomic_store_64(dst, src) c89atomic_store_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  13019. #define c89atomic_load_8( ptr) c89atomic_load_explicit_8( ptr, c89atomic_memory_order_seq_cst)
  13020. #define c89atomic_load_16(ptr) c89atomic_load_explicit_16(ptr, c89atomic_memory_order_seq_cst)
  13021. #define c89atomic_load_32(ptr) c89atomic_load_explicit_32(ptr, c89atomic_memory_order_seq_cst)
  13022. #define c89atomic_load_64(ptr) c89atomic_load_explicit_64(ptr, c89atomic_memory_order_seq_cst)
  13023. #define c89atomic_exchange_8( dst, src) c89atomic_exchange_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  13024. #define c89atomic_exchange_16(dst, src) c89atomic_exchange_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  13025. #define c89atomic_exchange_32(dst, src) c89atomic_exchange_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  13026. #define c89atomic_exchange_64(dst, src) c89atomic_exchange_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  13027. #define c89atomic_compare_exchange_strong_8( dst, expected, desired) c89atomic_compare_exchange_strong_explicit_8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13028. #define c89atomic_compare_exchange_strong_16(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13029. #define c89atomic_compare_exchange_strong_32(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13030. #define c89atomic_compare_exchange_strong_64(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13031. #define c89atomic_compare_exchange_weak_8( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13032. #define c89atomic_compare_exchange_weak_16( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13033. #define c89atomic_compare_exchange_weak_32( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13034. #define c89atomic_compare_exchange_weak_64( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13035. #define c89atomic_fetch_add_8( dst, src) c89atomic_fetch_add_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  13036. #define c89atomic_fetch_add_16(dst, src) c89atomic_fetch_add_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  13037. #define c89atomic_fetch_add_32(dst, src) c89atomic_fetch_add_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  13038. #define c89atomic_fetch_add_64(dst, src) c89atomic_fetch_add_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  13039. #define c89atomic_fetch_sub_8( dst, src) c89atomic_fetch_sub_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  13040. #define c89atomic_fetch_sub_16(dst, src) c89atomic_fetch_sub_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  13041. #define c89atomic_fetch_sub_32(dst, src) c89atomic_fetch_sub_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  13042. #define c89atomic_fetch_sub_64(dst, src) c89atomic_fetch_sub_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  13043. #define c89atomic_fetch_or_8( dst, src) c89atomic_fetch_or_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  13044. #define c89atomic_fetch_or_16(dst, src) c89atomic_fetch_or_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  13045. #define c89atomic_fetch_or_32(dst, src) c89atomic_fetch_or_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  13046. #define c89atomic_fetch_or_64(dst, src) c89atomic_fetch_or_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  13047. #define c89atomic_fetch_xor_8( dst, src) c89atomic_fetch_xor_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  13048. #define c89atomic_fetch_xor_16(dst, src) c89atomic_fetch_xor_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  13049. #define c89atomic_fetch_xor_32(dst, src) c89atomic_fetch_xor_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  13050. #define c89atomic_fetch_xor_64(dst, src) c89atomic_fetch_xor_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  13051. #define c89atomic_fetch_and_8( dst, src) c89atomic_fetch_and_explicit_8 (dst, src, c89atomic_memory_order_seq_cst)
  13052. #define c89atomic_fetch_and_16(dst, src) c89atomic_fetch_and_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  13053. #define c89atomic_fetch_and_32(dst, src) c89atomic_fetch_and_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  13054. #define c89atomic_fetch_and_64(dst, src) c89atomic_fetch_and_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  13055. #define c89atomic_test_and_set_explicit_i8( ptr, order) (c89atomic_int8 )c89atomic_test_and_set_explicit_8( (c89atomic_uint8* )ptr, order)
  13056. #define c89atomic_test_and_set_explicit_i16(ptr, order) (c89atomic_int16)c89atomic_test_and_set_explicit_16((c89atomic_uint16*)ptr, order)
  13057. #define c89atomic_test_and_set_explicit_i32(ptr, order) (c89atomic_int32)c89atomic_test_and_set_explicit_32((c89atomic_uint32*)ptr, order)
  13058. #define c89atomic_test_and_set_explicit_i64(ptr, order) (c89atomic_int64)c89atomic_test_and_set_explicit_64((c89atomic_uint64*)ptr, order)
  13059. #define c89atomic_clear_explicit_i8( ptr, order) c89atomic_clear_explicit_8( (c89atomic_uint8* )ptr, order)
  13060. #define c89atomic_clear_explicit_i16(ptr, order) c89atomic_clear_explicit_16((c89atomic_uint16*)ptr, order)
  13061. #define c89atomic_clear_explicit_i32(ptr, order) c89atomic_clear_explicit_32((c89atomic_uint32*)ptr, order)
  13062. #define c89atomic_clear_explicit_i64(ptr, order) c89atomic_clear_explicit_64((c89atomic_uint64*)ptr, order)
  13063. #define c89atomic_store_explicit_i8( dst, src, order) c89atomic_store_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  13064. #define c89atomic_store_explicit_i16(dst, src, order) c89atomic_store_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  13065. #define c89atomic_store_explicit_i32(dst, src, order) c89atomic_store_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  13066. #define c89atomic_store_explicit_i64(dst, src, order) c89atomic_store_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  13067. #define c89atomic_load_explicit_i8( ptr, order) (c89atomic_int8 )c89atomic_load_explicit_8( (c89atomic_uint8* )ptr, order)
  13068. #define c89atomic_load_explicit_i16(ptr, order) (c89atomic_int16)c89atomic_load_explicit_16((c89atomic_uint16*)ptr, order)
  13069. #define c89atomic_load_explicit_i32(ptr, order) (c89atomic_int32)c89atomic_load_explicit_32((c89atomic_uint32*)ptr, order)
  13070. #define c89atomic_load_explicit_i64(ptr, order) (c89atomic_int64)c89atomic_load_explicit_64((c89atomic_uint64*)ptr, order)
  13071. #define c89atomic_exchange_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_exchange_explicit_8 ((c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  13072. #define c89atomic_exchange_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_exchange_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  13073. #define c89atomic_exchange_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_exchange_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  13074. #define c89atomic_exchange_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_exchange_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  13075. #define c89atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8* )expected, (c89atomic_uint8 )desired, successOrder, failureOrder)
  13076. #define c89atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16*)expected, (c89atomic_uint16)desired, successOrder, failureOrder)
  13077. #define c89atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder)
  13078. #define c89atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder)
  13079. #define c89atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8* )expected, (c89atomic_uint8 )desired, successOrder, failureOrder)
  13080. #define c89atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16*)expected, (c89atomic_uint16)desired, successOrder, failureOrder)
  13081. #define c89atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder)
  13082. #define c89atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder)
  13083. #define c89atomic_fetch_add_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_add_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  13084. #define c89atomic_fetch_add_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_add_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  13085. #define c89atomic_fetch_add_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_add_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  13086. #define c89atomic_fetch_add_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_add_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  13087. #define c89atomic_fetch_sub_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_sub_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  13088. #define c89atomic_fetch_sub_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_sub_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  13089. #define c89atomic_fetch_sub_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_sub_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  13090. #define c89atomic_fetch_sub_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_sub_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  13091. #define c89atomic_fetch_or_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_or_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  13092. #define c89atomic_fetch_or_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_or_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  13093. #define c89atomic_fetch_or_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_or_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  13094. #define c89atomic_fetch_or_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_or_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  13095. #define c89atomic_fetch_xor_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_xor_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  13096. #define c89atomic_fetch_xor_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_xor_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  13097. #define c89atomic_fetch_xor_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_xor_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  13098. #define c89atomic_fetch_xor_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_xor_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  13099. #define c89atomic_fetch_and_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_and_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  13100. #define c89atomic_fetch_and_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_and_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  13101. #define c89atomic_fetch_and_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_and_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  13102. #define c89atomic_fetch_and_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_and_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  13103. #define c89atomic_test_and_set_i8( ptr) c89atomic_test_and_set_explicit_i8( ptr, c89atomic_memory_order_seq_cst)
  13104. #define c89atomic_test_and_set_i16(ptr) c89atomic_test_and_set_explicit_i16(ptr, c89atomic_memory_order_seq_cst)
  13105. #define c89atomic_test_and_set_i32(ptr) c89atomic_test_and_set_explicit_i32(ptr, c89atomic_memory_order_seq_cst)
  13106. #define c89atomic_test_and_set_i64(ptr) c89atomic_test_and_set_explicit_i64(ptr, c89atomic_memory_order_seq_cst)
  13107. #define c89atomic_clear_i8( ptr) c89atomic_clear_explicit_i8( ptr, c89atomic_memory_order_seq_cst)
  13108. #define c89atomic_clear_i16(ptr) c89atomic_clear_explicit_i16(ptr, c89atomic_memory_order_seq_cst)
  13109. #define c89atomic_clear_i32(ptr) c89atomic_clear_explicit_i32(ptr, c89atomic_memory_order_seq_cst)
  13110. #define c89atomic_clear_i64(ptr) c89atomic_clear_explicit_i64(ptr, c89atomic_memory_order_seq_cst)
  13111. #define c89atomic_store_i8( dst, src) c89atomic_store_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  13112. #define c89atomic_store_i16(dst, src) c89atomic_store_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  13113. #define c89atomic_store_i32(dst, src) c89atomic_store_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  13114. #define c89atomic_store_i64(dst, src) c89atomic_store_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  13115. #define c89atomic_load_i8( ptr) c89atomic_load_explicit_i8( ptr, c89atomic_memory_order_seq_cst)
  13116. #define c89atomic_load_i16(ptr) c89atomic_load_explicit_i16(ptr, c89atomic_memory_order_seq_cst)
  13117. #define c89atomic_load_i32(ptr) c89atomic_load_explicit_i32(ptr, c89atomic_memory_order_seq_cst)
  13118. #define c89atomic_load_i64(ptr) c89atomic_load_explicit_i64(ptr, c89atomic_memory_order_seq_cst)
  13119. #define c89atomic_exchange_i8( dst, src) c89atomic_exchange_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  13120. #define c89atomic_exchange_i16(dst, src) c89atomic_exchange_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  13121. #define c89atomic_exchange_i32(dst, src) c89atomic_exchange_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  13122. #define c89atomic_exchange_i64(dst, src) c89atomic_exchange_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  13123. #define c89atomic_compare_exchange_strong_i8( dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13124. #define c89atomic_compare_exchange_strong_i16(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13125. #define c89atomic_compare_exchange_strong_i32(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13126. #define c89atomic_compare_exchange_strong_i64(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13127. #define c89atomic_compare_exchange_weak_i8( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13128. #define c89atomic_compare_exchange_weak_i16(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13129. #define c89atomic_compare_exchange_weak_i32(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13130. #define c89atomic_compare_exchange_weak_i64(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13131. #define c89atomic_fetch_add_i8( dst, src) c89atomic_fetch_add_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  13132. #define c89atomic_fetch_add_i16(dst, src) c89atomic_fetch_add_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  13133. #define c89atomic_fetch_add_i32(dst, src) c89atomic_fetch_add_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  13134. #define c89atomic_fetch_add_i64(dst, src) c89atomic_fetch_add_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  13135. #define c89atomic_fetch_sub_i8( dst, src) c89atomic_fetch_sub_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  13136. #define c89atomic_fetch_sub_i16(dst, src) c89atomic_fetch_sub_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  13137. #define c89atomic_fetch_sub_i32(dst, src) c89atomic_fetch_sub_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  13138. #define c89atomic_fetch_sub_i64(dst, src) c89atomic_fetch_sub_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  13139. #define c89atomic_fetch_or_i8( dst, src) c89atomic_fetch_or_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  13140. #define c89atomic_fetch_or_i16(dst, src) c89atomic_fetch_or_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  13141. #define c89atomic_fetch_or_i32(dst, src) c89atomic_fetch_or_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  13142. #define c89atomic_fetch_or_i64(dst, src) c89atomic_fetch_or_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  13143. #define c89atomic_fetch_xor_i8( dst, src) c89atomic_fetch_xor_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  13144. #define c89atomic_fetch_xor_i16(dst, src) c89atomic_fetch_xor_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  13145. #define c89atomic_fetch_xor_i32(dst, src) c89atomic_fetch_xor_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  13146. #define c89atomic_fetch_xor_i64(dst, src) c89atomic_fetch_xor_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  13147. #define c89atomic_fetch_and_i8( dst, src) c89atomic_fetch_and_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  13148. #define c89atomic_fetch_and_i16(dst, src) c89atomic_fetch_and_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  13149. #define c89atomic_fetch_and_i32(dst, src) c89atomic_fetch_and_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  13150. #define c89atomic_fetch_and_i64(dst, src) c89atomic_fetch_and_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  13151. #define c89atomic_compare_and_swap_i8( dst, expected, dedsired) (c89atomic_int8 )c89atomic_compare_and_swap_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )expected, (c89atomic_uint8 )dedsired)
  13152. #define c89atomic_compare_and_swap_i16(dst, expected, dedsired) (c89atomic_int16)c89atomic_compare_and_swap_16((c89atomic_uint16*)dst, (c89atomic_uint16)expected, (c89atomic_uint16)dedsired)
  13153. #define c89atomic_compare_and_swap_i32(dst, expected, dedsired) (c89atomic_int32)c89atomic_compare_and_swap_32((c89atomic_uint32*)dst, (c89atomic_uint32)expected, (c89atomic_uint32)dedsired)
  13154. #define c89atomic_compare_and_swap_i64(dst, expected, dedsired) (c89atomic_int64)c89atomic_compare_and_swap_64((c89atomic_uint64*)dst, (c89atomic_uint64)expected, (c89atomic_uint64)dedsired)
  13155. typedef union
  13156. {
  13157. c89atomic_uint32 i;
  13158. float f;
  13159. } c89atomic_if32;
  13160. typedef union
  13161. {
  13162. c89atomic_uint64 i;
  13163. double f;
  13164. } c89atomic_if64;
  13165. #define c89atomic_clear_explicit_f32(ptr, order) c89atomic_clear_explicit_32((c89atomic_uint32*)ptr, order)
  13166. #define c89atomic_clear_explicit_f64(ptr, order) c89atomic_clear_explicit_64((c89atomic_uint64*)ptr, order)
  13167. static C89ATOMIC_INLINE void c89atomic_store_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
  13168. {
  13169. c89atomic_if32 x;
  13170. x.f = src;
  13171. c89atomic_store_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
  13172. }
  13173. static C89ATOMIC_INLINE void c89atomic_store_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
  13174. {
  13175. c89atomic_if64 x;
  13176. x.f = src;
  13177. c89atomic_store_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
  13178. }
  13179. static C89ATOMIC_INLINE float c89atomic_load_explicit_f32(volatile const float* ptr, c89atomic_memory_order order)
  13180. {
  13181. c89atomic_if32 r;
  13182. r.i = c89atomic_load_explicit_32((volatile const c89atomic_uint32*)ptr, order);
  13183. return r.f;
  13184. }
  13185. static C89ATOMIC_INLINE double c89atomic_load_explicit_f64(volatile const double* ptr, c89atomic_memory_order order)
  13186. {
  13187. c89atomic_if64 r;
  13188. r.i = c89atomic_load_explicit_64((volatile const c89atomic_uint64*)ptr, order);
  13189. return r.f;
  13190. }
  13191. static C89ATOMIC_INLINE float c89atomic_exchange_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
  13192. {
  13193. c89atomic_if32 r;
  13194. c89atomic_if32 x;
  13195. x.f = src;
  13196. r.i = c89atomic_exchange_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
  13197. return r.f;
  13198. }
  13199. static C89ATOMIC_INLINE double c89atomic_exchange_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
  13200. {
  13201. c89atomic_if64 r;
  13202. c89atomic_if64 x;
  13203. x.f = src;
  13204. r.i = c89atomic_exchange_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
  13205. return r.f;
  13206. }
  13207. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_f32(volatile float* dst, float* expected, float desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  13208. {
  13209. c89atomic_if32 d;
  13210. d.f = desired;
  13211. return c89atomic_compare_exchange_strong_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, d.i, successOrder, failureOrder);
  13212. }
  13213. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_f64(volatile double* dst, double* expected, double desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  13214. {
  13215. c89atomic_if64 d;
  13216. d.f = desired;
  13217. return c89atomic_compare_exchange_strong_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, d.i, successOrder, failureOrder);
  13218. }
  13219. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_f32(volatile float* dst, float* expected, float desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  13220. {
  13221. c89atomic_if32 d;
  13222. d.f = desired;
  13223. return c89atomic_compare_exchange_weak_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, d.i, successOrder, failureOrder);
  13224. }
  13225. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_f64(volatile double* dst, double* expected, double desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  13226. {
  13227. c89atomic_if64 d;
  13228. d.f = desired;
  13229. return c89atomic_compare_exchange_weak_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, d.i, successOrder, failureOrder);
  13230. }
  13231. static C89ATOMIC_INLINE float c89atomic_fetch_add_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
  13232. {
  13233. c89atomic_if32 r;
  13234. c89atomic_if32 x;
  13235. x.f = src;
  13236. r.i = c89atomic_fetch_add_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
  13237. return r.f;
  13238. }
  13239. static C89ATOMIC_INLINE double c89atomic_fetch_add_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
  13240. {
  13241. c89atomic_if64 r;
  13242. c89atomic_if64 x;
  13243. x.f = src;
  13244. r.i = c89atomic_fetch_add_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
  13245. return r.f;
  13246. }
  13247. static C89ATOMIC_INLINE float c89atomic_fetch_sub_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
  13248. {
  13249. c89atomic_if32 r;
  13250. c89atomic_if32 x;
  13251. x.f = src;
  13252. r.i = c89atomic_fetch_sub_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
  13253. return r.f;
  13254. }
  13255. static C89ATOMIC_INLINE double c89atomic_fetch_sub_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
  13256. {
  13257. c89atomic_if64 r;
  13258. c89atomic_if64 x;
  13259. x.f = src;
  13260. r.i = c89atomic_fetch_sub_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
  13261. return r.f;
  13262. }
  13263. static C89ATOMIC_INLINE float c89atomic_fetch_or_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
  13264. {
  13265. c89atomic_if32 r;
  13266. c89atomic_if32 x;
  13267. x.f = src;
  13268. r.i = c89atomic_fetch_or_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
  13269. return r.f;
  13270. }
  13271. static C89ATOMIC_INLINE double c89atomic_fetch_or_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
  13272. {
  13273. c89atomic_if64 r;
  13274. c89atomic_if64 x;
  13275. x.f = src;
  13276. r.i = c89atomic_fetch_or_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
  13277. return r.f;
  13278. }
  13279. static C89ATOMIC_INLINE float c89atomic_fetch_xor_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
  13280. {
  13281. c89atomic_if32 r;
  13282. c89atomic_if32 x;
  13283. x.f = src;
  13284. r.i = c89atomic_fetch_xor_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
  13285. return r.f;
  13286. }
  13287. static C89ATOMIC_INLINE double c89atomic_fetch_xor_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
  13288. {
  13289. c89atomic_if64 r;
  13290. c89atomic_if64 x;
  13291. x.f = src;
  13292. r.i = c89atomic_fetch_xor_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
  13293. return r.f;
  13294. }
  13295. static C89ATOMIC_INLINE float c89atomic_fetch_and_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
  13296. {
  13297. c89atomic_if32 r;
  13298. c89atomic_if32 x;
  13299. x.f = src;
  13300. r.i = c89atomic_fetch_and_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
  13301. return r.f;
  13302. }
  13303. static C89ATOMIC_INLINE double c89atomic_fetch_and_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
  13304. {
  13305. c89atomic_if64 r;
  13306. c89atomic_if64 x;
  13307. x.f = src;
  13308. r.i = c89atomic_fetch_and_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
  13309. return r.f;
  13310. }
  13311. #define c89atomic_clear_f32(ptr) (float )c89atomic_clear_explicit_f32(ptr, c89atomic_memory_order_seq_cst)
  13312. #define c89atomic_clear_f64(ptr) (double)c89atomic_clear_explicit_f64(ptr, c89atomic_memory_order_seq_cst)
  13313. #define c89atomic_store_f32(dst, src) c89atomic_store_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
  13314. #define c89atomic_store_f64(dst, src) c89atomic_store_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
  13315. #define c89atomic_load_f32(ptr) (float )c89atomic_load_explicit_f32(ptr, c89atomic_memory_order_seq_cst)
  13316. #define c89atomic_load_f64(ptr) (double)c89atomic_load_explicit_f64(ptr, c89atomic_memory_order_seq_cst)
  13317. #define c89atomic_exchange_f32(dst, src) (float )c89atomic_exchange_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
  13318. #define c89atomic_exchange_f64(dst, src) (double)c89atomic_exchange_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
  13319. #define c89atomic_compare_exchange_strong_f32(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_f32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13320. #define c89atomic_compare_exchange_strong_f64(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_f64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13321. #define c89atomic_compare_exchange_weak_f32(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_f32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13322. #define c89atomic_compare_exchange_weak_f64(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_f64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  13323. #define c89atomic_fetch_add_f32(dst, src) c89atomic_fetch_add_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
  13324. #define c89atomic_fetch_add_f64(dst, src) c89atomic_fetch_add_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
  13325. #define c89atomic_fetch_sub_f32(dst, src) c89atomic_fetch_sub_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
  13326. #define c89atomic_fetch_sub_f64(dst, src) c89atomic_fetch_sub_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
  13327. #define c89atomic_fetch_or_f32(dst, src) c89atomic_fetch_or_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
  13328. #define c89atomic_fetch_or_f64(dst, src) c89atomic_fetch_or_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
  13329. #define c89atomic_fetch_xor_f32(dst, src) c89atomic_fetch_xor_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
  13330. #define c89atomic_fetch_xor_f64(dst, src) c89atomic_fetch_xor_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
  13331. #define c89atomic_fetch_and_f32(dst, src) c89atomic_fetch_and_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
  13332. #define c89atomic_fetch_and_f64(dst, src) c89atomic_fetch_and_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
  13333. static C89ATOMIC_INLINE float c89atomic_compare_and_swap_f32(volatile float* dst, float expected, float desired)
  13334. {
  13335. c89atomic_if32 r;
  13336. c89atomic_if32 e, d;
  13337. e.f = expected;
  13338. d.f = desired;
  13339. r.i = c89atomic_compare_and_swap_32((volatile c89atomic_uint32*)dst, e.i, d.i);
  13340. return r.f;
  13341. }
  13342. static C89ATOMIC_INLINE double c89atomic_compare_and_swap_f64(volatile double* dst, double expected, double desired)
  13343. {
  13344. c89atomic_if64 r;
  13345. c89atomic_if64 e, d;
  13346. e.f = expected;
  13347. d.f = desired;
  13348. r.i = c89atomic_compare_and_swap_64((volatile c89atomic_uint64*)dst, e.i, d.i);
  13349. return r.f;
  13350. }
  13351. typedef c89atomic_flag c89atomic_spinlock;
  13352. static C89ATOMIC_INLINE void c89atomic_spinlock_lock(volatile c89atomic_spinlock* pSpinlock)
  13353. {
  13354. for (;;) {
  13355. if (c89atomic_flag_test_and_set_explicit(pSpinlock, c89atomic_memory_order_acquire) == 0) {
  13356. break;
  13357. }
  13358. while (c89atoimc_flag_load_explicit(pSpinlock, c89atomic_memory_order_relaxed) == 1) {
  13359. }
  13360. }
  13361. }
  13362. static C89ATOMIC_INLINE void c89atomic_spinlock_unlock(volatile c89atomic_spinlock* pSpinlock)
  13363. {
  13364. c89atomic_flag_clear_explicit(pSpinlock, c89atomic_memory_order_release);
  13365. }
  13366. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  13367. #pragma GCC diagnostic pop
  13368. #endif
  13369. #if defined(__cplusplus)
  13370. }
  13371. #endif
  13372. #endif
  13373. /* c89atomic.h end */
  13374. #define MA_ATOMIC_SAFE_TYPE_IMPL(c89TypeExtension, type) \
  13375. static MA_INLINE ma_##type ma_atomic_##type##_get(ma_atomic_##type* x) \
  13376. { \
  13377. return (ma_##type)c89atomic_load_##c89TypeExtension(&x->value); \
  13378. } \
  13379. static MA_INLINE void ma_atomic_##type##_set(ma_atomic_##type* x, ma_##type value) \
  13380. { \
  13381. c89atomic_store_##c89TypeExtension(&x->value, value); \
  13382. } \
  13383. static MA_INLINE ma_##type ma_atomic_##type##_exchange(ma_atomic_##type* x, ma_##type value) \
  13384. { \
  13385. return (ma_##type)c89atomic_exchange_##c89TypeExtension(&x->value, value); \
  13386. } \
  13387. static MA_INLINE ma_bool32 ma_atomic_##type##_compare_exchange(ma_atomic_##type* x, ma_##type* expected, ma_##type desired) \
  13388. { \
  13389. return c89atomic_compare_exchange_weak_##c89TypeExtension(&x->value, expected, desired); \
  13390. } \
  13391. static MA_INLINE ma_##type ma_atomic_##type##_fetch_add(ma_atomic_##type* x, ma_##type y) \
  13392. { \
  13393. return (ma_##type)c89atomic_fetch_add_##c89TypeExtension(&x->value, y); \
  13394. } \
  13395. static MA_INLINE ma_##type ma_atomic_##type##_fetch_sub(ma_atomic_##type* x, ma_##type y) \
  13396. { \
  13397. return (ma_##type)c89atomic_fetch_sub_##c89TypeExtension(&x->value, y); \
  13398. } \
  13399. static MA_INLINE ma_##type ma_atomic_##type##_fetch_or(ma_atomic_##type* x, ma_##type y) \
  13400. { \
  13401. return (ma_##type)c89atomic_fetch_or_##c89TypeExtension(&x->value, y); \
  13402. } \
  13403. static MA_INLINE ma_##type ma_atomic_##type##_fetch_xor(ma_atomic_##type* x, ma_##type y) \
  13404. { \
  13405. return (ma_##type)c89atomic_fetch_xor_##c89TypeExtension(&x->value, y); \
  13406. } \
  13407. static MA_INLINE ma_##type ma_atomic_##type##_fetch_and(ma_atomic_##type* x, ma_##type y) \
  13408. { \
  13409. return (ma_##type)c89atomic_fetch_and_##c89TypeExtension(&x->value, y); \
  13410. } \
  13411. static MA_INLINE ma_##type ma_atomic_##type##_compare_and_swap(ma_atomic_##type* x, ma_##type expected, ma_##type desired) \
  13412. { \
  13413. return (ma_##type)c89atomic_compare_and_swap_##c89TypeExtension(&x->value, expected, desired); \
  13414. } \
  13415. #define MA_ATOMIC_SAFE_TYPE_IMPL_PTR(type) \
  13416. static MA_INLINE ma_##type* ma_atomic_ptr_##type##_get(ma_atomic_ptr_##type* x) \
  13417. { \
  13418. return c89atomic_load_ptr((void**)&x->value); \
  13419. } \
  13420. static MA_INLINE void ma_atomic_ptr_##type##_set(ma_atomic_ptr_##type* x, ma_##type* value) \
  13421. { \
  13422. c89atomic_store_ptr((void**)&x->value, (void*)value); \
  13423. } \
  13424. static MA_INLINE ma_##type* ma_atomic_ptr_##type##_exchange(ma_atomic_ptr_##type* x, ma_##type* value) \
  13425. { \
  13426. return c89atomic_exchange_ptr((void**)&x->value, (void*)value); \
  13427. } \
  13428. static MA_INLINE ma_bool32 ma_atomic_ptr_##type##_compare_exchange(ma_atomic_ptr_##type* x, ma_##type** expected, ma_##type* desired) \
  13429. { \
  13430. return c89atomic_compare_exchange_weak_ptr((void**)&x->value, (void*)expected, (void*)desired); \
  13431. } \
  13432. static MA_INLINE ma_##type* ma_atomic_ptr_##type##_compare_and_swap(ma_atomic_ptr_##type* x, ma_##type* expected, ma_##type* desired) \
  13433. { \
  13434. return (ma_##type*)c89atomic_compare_and_swap_ptr((void**)&x->value, (void*)expected, (void*)desired); \
  13435. } \
  13436. MA_ATOMIC_SAFE_TYPE_IMPL(32, uint32)
  13437. MA_ATOMIC_SAFE_TYPE_IMPL(i32, int32)
  13438. MA_ATOMIC_SAFE_TYPE_IMPL(64, uint64)
  13439. MA_ATOMIC_SAFE_TYPE_IMPL(f32, float)
  13440. MA_ATOMIC_SAFE_TYPE_IMPL(32, bool32)
  13441. #if !defined(MA_NO_DEVICE_IO)
  13442. MA_ATOMIC_SAFE_TYPE_IMPL(i32, device_state)
  13443. #endif
  13444. MA_API ma_uint64 ma_calculate_frame_count_after_resampling(ma_uint32 sampleRateOut, ma_uint32 sampleRateIn, ma_uint64 frameCountIn)
  13445. {
  13446. /* This is based on the calculation in ma_linear_resampler_get_expected_output_frame_count(). */
  13447. ma_uint64 outputFrameCount;
  13448. ma_uint64 preliminaryInputFrameCountFromFrac;
  13449. ma_uint64 preliminaryInputFrameCount;
  13450. if (sampleRateIn == 0 || sampleRateOut == 0 || frameCountIn == 0) {
  13451. return 0;
  13452. }
  13453. if (sampleRateOut == sampleRateIn) {
  13454. return frameCountIn;
  13455. }
  13456. outputFrameCount = (frameCountIn * sampleRateOut) / sampleRateIn;
  13457. preliminaryInputFrameCountFromFrac = (outputFrameCount * (sampleRateIn / sampleRateOut)) / sampleRateOut;
  13458. preliminaryInputFrameCount = (outputFrameCount * (sampleRateIn % sampleRateOut)) + preliminaryInputFrameCountFromFrac;
  13459. if (preliminaryInputFrameCount <= frameCountIn) {
  13460. outputFrameCount += 1;
  13461. }
  13462. return outputFrameCount;
  13463. }
  13464. #ifndef MA_DATA_CONVERTER_STACK_BUFFER_SIZE
  13465. #define MA_DATA_CONVERTER_STACK_BUFFER_SIZE 4096
  13466. #endif
  13467. #if defined(MA_WIN32)
  13468. static ma_result ma_result_from_GetLastError(DWORD error)
  13469. {
  13470. switch (error)
  13471. {
  13472. case ERROR_SUCCESS: return MA_SUCCESS;
  13473. case ERROR_PATH_NOT_FOUND: return MA_DOES_NOT_EXIST;
  13474. case ERROR_TOO_MANY_OPEN_FILES: return MA_TOO_MANY_OPEN_FILES;
  13475. case ERROR_NOT_ENOUGH_MEMORY: return MA_OUT_OF_MEMORY;
  13476. case ERROR_DISK_FULL: return MA_NO_SPACE;
  13477. case ERROR_HANDLE_EOF: return MA_AT_END;
  13478. case ERROR_NEGATIVE_SEEK: return MA_BAD_SEEK;
  13479. case ERROR_INVALID_PARAMETER: return MA_INVALID_ARGS;
  13480. case ERROR_ACCESS_DENIED: return MA_ACCESS_DENIED;
  13481. case ERROR_SEM_TIMEOUT: return MA_TIMEOUT;
  13482. case ERROR_FILE_NOT_FOUND: return MA_DOES_NOT_EXIST;
  13483. default: break;
  13484. }
  13485. return MA_ERROR;
  13486. }
  13487. #endif /* MA_WIN32 */
  13488. /*******************************************************************************
  13489. Threading
  13490. *******************************************************************************/
  13491. static MA_INLINE ma_result ma_spinlock_lock_ex(volatile ma_spinlock* pSpinlock, ma_bool32 yield)
  13492. {
  13493. if (pSpinlock == NULL) {
  13494. return MA_INVALID_ARGS;
  13495. }
  13496. for (;;) {
  13497. if (c89atomic_exchange_explicit_32(pSpinlock, 1, c89atomic_memory_order_acquire) == 0) {
  13498. break;
  13499. }
  13500. while (c89atomic_load_explicit_32(pSpinlock, c89atomic_memory_order_relaxed) == 1) {
  13501. if (yield) {
  13502. ma_yield();
  13503. }
  13504. }
  13505. }
  13506. return MA_SUCCESS;
  13507. }
  13508. MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock)
  13509. {
  13510. return ma_spinlock_lock_ex(pSpinlock, MA_TRUE);
  13511. }
  13512. MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock)
  13513. {
  13514. return ma_spinlock_lock_ex(pSpinlock, MA_FALSE);
  13515. }
  13516. MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock)
  13517. {
  13518. if (pSpinlock == NULL) {
  13519. return MA_INVALID_ARGS;
  13520. }
  13521. c89atomic_store_explicit_32(pSpinlock, 0, c89atomic_memory_order_release);
  13522. return MA_SUCCESS;
  13523. }
  13524. #ifndef MA_NO_THREADING
  13525. #if defined(MA_POSIX)
  13526. #define MA_THREADCALL
  13527. typedef void* ma_thread_result;
  13528. #elif defined(MA_WIN32)
  13529. #define MA_THREADCALL WINAPI
  13530. typedef unsigned long ma_thread_result;
  13531. #endif
  13532. typedef ma_thread_result (MA_THREADCALL * ma_thread_entry_proc)(void* pData);
  13533. #ifdef MA_POSIX
  13534. static ma_result ma_thread_create__posix(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData)
  13535. {
  13536. int result;
  13537. pthread_attr_t* pAttr = NULL;
  13538. #if !defined(__EMSCRIPTEN__)
  13539. /* Try setting the thread priority. It's not critical if anything fails here. */
  13540. pthread_attr_t attr;
  13541. if (pthread_attr_init(&attr) == 0) {
  13542. int scheduler = -1;
  13543. /* We successfully initialized our attributes object so we can assign the pointer so it's passed into pthread_create(). */
  13544. pAttr = &attr;
  13545. /* We need to set the scheduler policy. Only do this if the OS supports pthread_attr_setschedpolicy() */
  13546. #if !defined(MA_BEOS)
  13547. {
  13548. if (priority == ma_thread_priority_idle) {
  13549. #ifdef SCHED_IDLE
  13550. if (pthread_attr_setschedpolicy(&attr, SCHED_IDLE) == 0) {
  13551. scheduler = SCHED_IDLE;
  13552. }
  13553. #endif
  13554. } else if (priority == ma_thread_priority_realtime) {
  13555. #ifdef SCHED_FIFO
  13556. if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) == 0) {
  13557. scheduler = SCHED_FIFO;
  13558. }
  13559. #endif
  13560. #ifdef MA_LINUX
  13561. } else {
  13562. scheduler = sched_getscheduler(0);
  13563. #endif
  13564. }
  13565. }
  13566. #endif
  13567. if (stackSize > 0) {
  13568. pthread_attr_setstacksize(&attr, stackSize);
  13569. }
  13570. if (scheduler != -1) {
  13571. int priorityMin = sched_get_priority_min(scheduler);
  13572. int priorityMax = sched_get_priority_max(scheduler);
  13573. int priorityStep = (priorityMax - priorityMin) / 7; /* 7 = number of priorities supported by miniaudio. */
  13574. struct sched_param sched;
  13575. if (pthread_attr_getschedparam(&attr, &sched) == 0) {
  13576. if (priority == ma_thread_priority_idle) {
  13577. sched.sched_priority = priorityMin;
  13578. } else if (priority == ma_thread_priority_realtime) {
  13579. sched.sched_priority = priorityMax;
  13580. } else {
  13581. sched.sched_priority += ((int)priority + 5) * priorityStep; /* +5 because the lowest priority is -5. */
  13582. if (sched.sched_priority < priorityMin) {
  13583. sched.sched_priority = priorityMin;
  13584. }
  13585. if (sched.sched_priority > priorityMax) {
  13586. sched.sched_priority = priorityMax;
  13587. }
  13588. }
  13589. /* I'm not treating a failure of setting the priority as a critical error so not checking the return value here. */
  13590. pthread_attr_setschedparam(&attr, &sched);
  13591. }
  13592. }
  13593. }
  13594. #else
  13595. /* It's the emscripten build. We'll have a few unused parameters. */
  13596. (void)priority;
  13597. (void)stackSize;
  13598. #endif
  13599. result = pthread_create((pthread_t*)pThread, pAttr, entryProc, pData);
  13600. /* The thread attributes object is no longer required. */
  13601. if (pAttr != NULL) {
  13602. pthread_attr_destroy(pAttr);
  13603. }
  13604. if (result != 0) {
  13605. return ma_result_from_errno(result);
  13606. }
  13607. return MA_SUCCESS;
  13608. }
  13609. static void ma_thread_wait__posix(ma_thread* pThread)
  13610. {
  13611. pthread_join((pthread_t)*pThread, NULL);
  13612. }
  13613. static ma_result ma_mutex_init__posix(ma_mutex* pMutex)
  13614. {
  13615. int result = pthread_mutex_init((pthread_mutex_t*)pMutex, NULL);
  13616. if (result != 0) {
  13617. return ma_result_from_errno(result);
  13618. }
  13619. return MA_SUCCESS;
  13620. }
  13621. static void ma_mutex_uninit__posix(ma_mutex* pMutex)
  13622. {
  13623. pthread_mutex_destroy((pthread_mutex_t*)pMutex);
  13624. }
  13625. static void ma_mutex_lock__posix(ma_mutex* pMutex)
  13626. {
  13627. pthread_mutex_lock((pthread_mutex_t*)pMutex);
  13628. }
  13629. static void ma_mutex_unlock__posix(ma_mutex* pMutex)
  13630. {
  13631. pthread_mutex_unlock((pthread_mutex_t*)pMutex);
  13632. }
  13633. static ma_result ma_event_init__posix(ma_event* pEvent)
  13634. {
  13635. int result;
  13636. result = pthread_mutex_init((pthread_mutex_t*)&pEvent->lock, NULL);
  13637. if (result != 0) {
  13638. return ma_result_from_errno(result);
  13639. }
  13640. result = pthread_cond_init((pthread_cond_t*)&pEvent->cond, NULL);
  13641. if (result != 0) {
  13642. pthread_mutex_destroy((pthread_mutex_t*)&pEvent->lock);
  13643. return ma_result_from_errno(result);
  13644. }
  13645. pEvent->value = 0;
  13646. return MA_SUCCESS;
  13647. }
  13648. static void ma_event_uninit__posix(ma_event* pEvent)
  13649. {
  13650. pthread_cond_destroy((pthread_cond_t*)&pEvent->cond);
  13651. pthread_mutex_destroy((pthread_mutex_t*)&pEvent->lock);
  13652. }
  13653. static ma_result ma_event_wait__posix(ma_event* pEvent)
  13654. {
  13655. pthread_mutex_lock((pthread_mutex_t*)&pEvent->lock);
  13656. {
  13657. while (pEvent->value == 0) {
  13658. pthread_cond_wait((pthread_cond_t*)&pEvent->cond, (pthread_mutex_t*)&pEvent->lock);
  13659. }
  13660. pEvent->value = 0; /* Auto-reset. */
  13661. }
  13662. pthread_mutex_unlock((pthread_mutex_t*)&pEvent->lock);
  13663. return MA_SUCCESS;
  13664. }
  13665. static ma_result ma_event_signal__posix(ma_event* pEvent)
  13666. {
  13667. pthread_mutex_lock((pthread_mutex_t*)&pEvent->lock);
  13668. {
  13669. pEvent->value = 1;
  13670. pthread_cond_signal((pthread_cond_t*)&pEvent->cond);
  13671. }
  13672. pthread_mutex_unlock((pthread_mutex_t*)&pEvent->lock);
  13673. return MA_SUCCESS;
  13674. }
  13675. static ma_result ma_semaphore_init__posix(int initialValue, ma_semaphore* pSemaphore)
  13676. {
  13677. int result;
  13678. if (pSemaphore == NULL) {
  13679. return MA_INVALID_ARGS;
  13680. }
  13681. pSemaphore->value = initialValue;
  13682. result = pthread_mutex_init((pthread_mutex_t*)&pSemaphore->lock, NULL);
  13683. if (result != 0) {
  13684. return ma_result_from_errno(result); /* Failed to create mutex. */
  13685. }
  13686. result = pthread_cond_init((pthread_cond_t*)&pSemaphore->cond, NULL);
  13687. if (result != 0) {
  13688. pthread_mutex_destroy((pthread_mutex_t*)&pSemaphore->lock);
  13689. return ma_result_from_errno(result); /* Failed to create condition variable. */
  13690. }
  13691. return MA_SUCCESS;
  13692. }
  13693. static void ma_semaphore_uninit__posix(ma_semaphore* pSemaphore)
  13694. {
  13695. if (pSemaphore == NULL) {
  13696. return;
  13697. }
  13698. pthread_cond_destroy((pthread_cond_t*)&pSemaphore->cond);
  13699. pthread_mutex_destroy((pthread_mutex_t*)&pSemaphore->lock);
  13700. }
  13701. static ma_result ma_semaphore_wait__posix(ma_semaphore* pSemaphore)
  13702. {
  13703. if (pSemaphore == NULL) {
  13704. return MA_INVALID_ARGS;
  13705. }
  13706. pthread_mutex_lock((pthread_mutex_t*)&pSemaphore->lock);
  13707. {
  13708. /* We need to wait on a condition variable before escaping. We can't return from this function until the semaphore has been signaled. */
  13709. while (pSemaphore->value == 0) {
  13710. pthread_cond_wait((pthread_cond_t*)&pSemaphore->cond, (pthread_mutex_t*)&pSemaphore->lock);
  13711. }
  13712. pSemaphore->value -= 1;
  13713. }
  13714. pthread_mutex_unlock((pthread_mutex_t*)&pSemaphore->lock);
  13715. return MA_SUCCESS;
  13716. }
  13717. static ma_result ma_semaphore_release__posix(ma_semaphore* pSemaphore)
  13718. {
  13719. if (pSemaphore == NULL) {
  13720. return MA_INVALID_ARGS;
  13721. }
  13722. pthread_mutex_lock((pthread_mutex_t*)&pSemaphore->lock);
  13723. {
  13724. pSemaphore->value += 1;
  13725. pthread_cond_signal((pthread_cond_t*)&pSemaphore->cond);
  13726. }
  13727. pthread_mutex_unlock((pthread_mutex_t*)&pSemaphore->lock);
  13728. return MA_SUCCESS;
  13729. }
  13730. #elif defined(MA_WIN32)
  13731. static int ma_thread_priority_to_win32(ma_thread_priority priority)
  13732. {
  13733. switch (priority) {
  13734. case ma_thread_priority_idle: return THREAD_PRIORITY_IDLE;
  13735. case ma_thread_priority_lowest: return THREAD_PRIORITY_LOWEST;
  13736. case ma_thread_priority_low: return THREAD_PRIORITY_BELOW_NORMAL;
  13737. case ma_thread_priority_normal: return THREAD_PRIORITY_NORMAL;
  13738. case ma_thread_priority_high: return THREAD_PRIORITY_ABOVE_NORMAL;
  13739. case ma_thread_priority_highest: return THREAD_PRIORITY_HIGHEST;
  13740. case ma_thread_priority_realtime: return THREAD_PRIORITY_TIME_CRITICAL;
  13741. default: return THREAD_PRIORITY_NORMAL;
  13742. }
  13743. }
  13744. static ma_result ma_thread_create__win32(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData)
  13745. {
  13746. DWORD threadID; /* Not used. Only used for passing into CreateThread() so it doesn't fail on Windows 98. */
  13747. *pThread = CreateThread(NULL, stackSize, entryProc, pData, 0, &threadID);
  13748. if (*pThread == NULL) {
  13749. return ma_result_from_GetLastError(GetLastError());
  13750. }
  13751. SetThreadPriority((HANDLE)*pThread, ma_thread_priority_to_win32(priority));
  13752. return MA_SUCCESS;
  13753. }
  13754. static void ma_thread_wait__win32(ma_thread* pThread)
  13755. {
  13756. WaitForSingleObject((HANDLE)*pThread, INFINITE);
  13757. CloseHandle((HANDLE)*pThread);
  13758. }
  13759. static ma_result ma_mutex_init__win32(ma_mutex* pMutex)
  13760. {
  13761. *pMutex = CreateEventA(NULL, FALSE, TRUE, NULL);
  13762. if (*pMutex == NULL) {
  13763. return ma_result_from_GetLastError(GetLastError());
  13764. }
  13765. return MA_SUCCESS;
  13766. }
  13767. static void ma_mutex_uninit__win32(ma_mutex* pMutex)
  13768. {
  13769. CloseHandle((HANDLE)*pMutex);
  13770. }
  13771. static void ma_mutex_lock__win32(ma_mutex* pMutex)
  13772. {
  13773. WaitForSingleObject((HANDLE)*pMutex, INFINITE);
  13774. }
  13775. static void ma_mutex_unlock__win32(ma_mutex* pMutex)
  13776. {
  13777. SetEvent((HANDLE)*pMutex);
  13778. }
  13779. static ma_result ma_event_init__win32(ma_event* pEvent)
  13780. {
  13781. *pEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
  13782. if (*pEvent == NULL) {
  13783. return ma_result_from_GetLastError(GetLastError());
  13784. }
  13785. return MA_SUCCESS;
  13786. }
  13787. static void ma_event_uninit__win32(ma_event* pEvent)
  13788. {
  13789. CloseHandle((HANDLE)*pEvent);
  13790. }
  13791. static ma_result ma_event_wait__win32(ma_event* pEvent)
  13792. {
  13793. DWORD result = WaitForSingleObject((HANDLE)*pEvent, INFINITE);
  13794. if (result == WAIT_OBJECT_0) {
  13795. return MA_SUCCESS;
  13796. }
  13797. if (result == WAIT_TIMEOUT) {
  13798. return MA_TIMEOUT;
  13799. }
  13800. return ma_result_from_GetLastError(GetLastError());
  13801. }
  13802. static ma_result ma_event_signal__win32(ma_event* pEvent)
  13803. {
  13804. BOOL result = SetEvent((HANDLE)*pEvent);
  13805. if (result == 0) {
  13806. return ma_result_from_GetLastError(GetLastError());
  13807. }
  13808. return MA_SUCCESS;
  13809. }
  13810. static ma_result ma_semaphore_init__win32(int initialValue, ma_semaphore* pSemaphore)
  13811. {
  13812. *pSemaphore = CreateSemaphoreW(NULL, (LONG)initialValue, LONG_MAX, NULL);
  13813. if (*pSemaphore == NULL) {
  13814. return ma_result_from_GetLastError(GetLastError());
  13815. }
  13816. return MA_SUCCESS;
  13817. }
  13818. static void ma_semaphore_uninit__win32(ma_semaphore* pSemaphore)
  13819. {
  13820. CloseHandle((HANDLE)*pSemaphore);
  13821. }
  13822. static ma_result ma_semaphore_wait__win32(ma_semaphore* pSemaphore)
  13823. {
  13824. DWORD result = WaitForSingleObject((HANDLE)*pSemaphore, INFINITE);
  13825. if (result == WAIT_OBJECT_0) {
  13826. return MA_SUCCESS;
  13827. }
  13828. if (result == WAIT_TIMEOUT) {
  13829. return MA_TIMEOUT;
  13830. }
  13831. return ma_result_from_GetLastError(GetLastError());
  13832. }
  13833. static ma_result ma_semaphore_release__win32(ma_semaphore* pSemaphore)
  13834. {
  13835. BOOL result = ReleaseSemaphore((HANDLE)*pSemaphore, 1, NULL);
  13836. if (result == 0) {
  13837. return ma_result_from_GetLastError(GetLastError());
  13838. }
  13839. return MA_SUCCESS;
  13840. }
  13841. #endif
  13842. typedef struct
  13843. {
  13844. ma_thread_entry_proc entryProc;
  13845. void* pData;
  13846. ma_allocation_callbacks allocationCallbacks;
  13847. } ma_thread_proxy_data;
  13848. static ma_thread_result MA_THREADCALL ma_thread_entry_proxy(void* pData)
  13849. {
  13850. ma_thread_proxy_data* pProxyData = (ma_thread_proxy_data*)pData;
  13851. ma_thread_entry_proc entryProc;
  13852. void* pEntryProcData;
  13853. ma_thread_result result;
  13854. #if defined(MA_ON_THREAD_ENTRY)
  13855. MA_ON_THREAD_ENTRY
  13856. #endif
  13857. entryProc = pProxyData->entryProc;
  13858. pEntryProcData = pProxyData->pData;
  13859. /* Free the proxy data before getting into the real thread entry proc. */
  13860. ma_free(pProxyData, &pProxyData->allocationCallbacks);
  13861. result = entryProc(pEntryProcData);
  13862. #if defined(MA_ON_THREAD_EXIT)
  13863. MA_ON_THREAD_EXIT
  13864. #endif
  13865. return result;
  13866. }
  13867. static ma_result ma_thread_create(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData, const ma_allocation_callbacks* pAllocationCallbacks)
  13868. {
  13869. ma_result result;
  13870. ma_thread_proxy_data* pProxyData;
  13871. if (pThread == NULL || entryProc == NULL) {
  13872. return MA_INVALID_ARGS;
  13873. }
  13874. pProxyData = (ma_thread_proxy_data*)ma_malloc(sizeof(*pProxyData), pAllocationCallbacks); /* Will be freed by the proxy entry proc. */
  13875. if (pProxyData == NULL) {
  13876. return MA_OUT_OF_MEMORY;
  13877. }
  13878. #if defined(MA_THREAD_DEFAULT_STACK_SIZE)
  13879. if (stackSize == 0) {
  13880. stackSize = MA_THREAD_DEFAULT_STACK_SIZE;
  13881. }
  13882. #endif
  13883. pProxyData->entryProc = entryProc;
  13884. pProxyData->pData = pData;
  13885. ma_allocation_callbacks_init_copy(&pProxyData->allocationCallbacks, pAllocationCallbacks);
  13886. #if defined(MA_POSIX)
  13887. result = ma_thread_create__posix(pThread, priority, stackSize, ma_thread_entry_proxy, pProxyData);
  13888. #elif defined(MA_WIN32)
  13889. result = ma_thread_create__win32(pThread, priority, stackSize, ma_thread_entry_proxy, pProxyData);
  13890. #endif
  13891. if (result != MA_SUCCESS) {
  13892. ma_free(pProxyData, pAllocationCallbacks);
  13893. return result;
  13894. }
  13895. return MA_SUCCESS;
  13896. }
  13897. static void ma_thread_wait(ma_thread* pThread)
  13898. {
  13899. if (pThread == NULL) {
  13900. return;
  13901. }
  13902. #if defined(MA_POSIX)
  13903. ma_thread_wait__posix(pThread);
  13904. #elif defined(MA_WIN32)
  13905. ma_thread_wait__win32(pThread);
  13906. #endif
  13907. }
  13908. MA_API ma_result ma_mutex_init(ma_mutex* pMutex)
  13909. {
  13910. if (pMutex == NULL) {
  13911. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13912. return MA_INVALID_ARGS;
  13913. }
  13914. #if defined(MA_POSIX)
  13915. return ma_mutex_init__posix(pMutex);
  13916. #elif defined(MA_WIN32)
  13917. return ma_mutex_init__win32(pMutex);
  13918. #endif
  13919. }
  13920. MA_API void ma_mutex_uninit(ma_mutex* pMutex)
  13921. {
  13922. if (pMutex == NULL) {
  13923. return;
  13924. }
  13925. #if defined(MA_POSIX)
  13926. ma_mutex_uninit__posix(pMutex);
  13927. #elif defined(MA_WIN32)
  13928. ma_mutex_uninit__win32(pMutex);
  13929. #endif
  13930. }
  13931. MA_API void ma_mutex_lock(ma_mutex* pMutex)
  13932. {
  13933. if (pMutex == NULL) {
  13934. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13935. return;
  13936. }
  13937. #if defined(MA_POSIX)
  13938. ma_mutex_lock__posix(pMutex);
  13939. #elif defined(MA_WIN32)
  13940. ma_mutex_lock__win32(pMutex);
  13941. #endif
  13942. }
  13943. MA_API void ma_mutex_unlock(ma_mutex* pMutex)
  13944. {
  13945. if (pMutex == NULL) {
  13946. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13947. return;
  13948. }
  13949. #if defined(MA_POSIX)
  13950. ma_mutex_unlock__posix(pMutex);
  13951. #elif defined(MA_WIN32)
  13952. ma_mutex_unlock__win32(pMutex);
  13953. #endif
  13954. }
  13955. MA_API ma_result ma_event_init(ma_event* pEvent)
  13956. {
  13957. if (pEvent == NULL) {
  13958. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13959. return MA_INVALID_ARGS;
  13960. }
  13961. #if defined(MA_POSIX)
  13962. return ma_event_init__posix(pEvent);
  13963. #elif defined(MA_WIN32)
  13964. return ma_event_init__win32(pEvent);
  13965. #endif
  13966. }
  13967. #if 0
  13968. static ma_result ma_event_alloc_and_init(ma_event** ppEvent, ma_allocation_callbacks* pAllocationCallbacks)
  13969. {
  13970. ma_result result;
  13971. ma_event* pEvent;
  13972. if (ppEvent == NULL) {
  13973. return MA_INVALID_ARGS;
  13974. }
  13975. *ppEvent = NULL;
  13976. pEvent = ma_malloc(sizeof(*pEvent), pAllocationCallbacks);
  13977. if (pEvent == NULL) {
  13978. return MA_OUT_OF_MEMORY;
  13979. }
  13980. result = ma_event_init(pEvent);
  13981. if (result != MA_SUCCESS) {
  13982. ma_free(pEvent, pAllocationCallbacks);
  13983. return result;
  13984. }
  13985. *ppEvent = pEvent;
  13986. return result;
  13987. }
  13988. #endif
  13989. MA_API void ma_event_uninit(ma_event* pEvent)
  13990. {
  13991. if (pEvent == NULL) {
  13992. return;
  13993. }
  13994. #if defined(MA_POSIX)
  13995. ma_event_uninit__posix(pEvent);
  13996. #elif defined(MA_WIN32)
  13997. ma_event_uninit__win32(pEvent);
  13998. #endif
  13999. }
  14000. #if 0
  14001. static void ma_event_uninit_and_free(ma_event* pEvent, ma_allocation_callbacks* pAllocationCallbacks)
  14002. {
  14003. if (pEvent == NULL) {
  14004. return;
  14005. }
  14006. ma_event_uninit(pEvent);
  14007. ma_free(pEvent, pAllocationCallbacks);
  14008. }
  14009. #endif
  14010. MA_API ma_result ma_event_wait(ma_event* pEvent)
  14011. {
  14012. if (pEvent == NULL) {
  14013. MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
  14014. return MA_INVALID_ARGS;
  14015. }
  14016. #if defined(MA_POSIX)
  14017. return ma_event_wait__posix(pEvent);
  14018. #elif defined(MA_WIN32)
  14019. return ma_event_wait__win32(pEvent);
  14020. #endif
  14021. }
  14022. MA_API ma_result ma_event_signal(ma_event* pEvent)
  14023. {
  14024. if (pEvent == NULL) {
  14025. MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
  14026. return MA_INVALID_ARGS;
  14027. }
  14028. #if defined(MA_POSIX)
  14029. return ma_event_signal__posix(pEvent);
  14030. #elif defined(MA_WIN32)
  14031. return ma_event_signal__win32(pEvent);
  14032. #endif
  14033. }
  14034. MA_API ma_result ma_semaphore_init(int initialValue, ma_semaphore* pSemaphore)
  14035. {
  14036. if (pSemaphore == NULL) {
  14037. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  14038. return MA_INVALID_ARGS;
  14039. }
  14040. #if defined(MA_POSIX)
  14041. return ma_semaphore_init__posix(initialValue, pSemaphore);
  14042. #elif defined(MA_WIN32)
  14043. return ma_semaphore_init__win32(initialValue, pSemaphore);
  14044. #endif
  14045. }
  14046. MA_API void ma_semaphore_uninit(ma_semaphore* pSemaphore)
  14047. {
  14048. if (pSemaphore == NULL) {
  14049. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  14050. return;
  14051. }
  14052. #if defined(MA_POSIX)
  14053. ma_semaphore_uninit__posix(pSemaphore);
  14054. #elif defined(MA_WIN32)
  14055. ma_semaphore_uninit__win32(pSemaphore);
  14056. #endif
  14057. }
  14058. MA_API ma_result ma_semaphore_wait(ma_semaphore* pSemaphore)
  14059. {
  14060. if (pSemaphore == NULL) {
  14061. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  14062. return MA_INVALID_ARGS;
  14063. }
  14064. #if defined(MA_POSIX)
  14065. return ma_semaphore_wait__posix(pSemaphore);
  14066. #elif defined(MA_WIN32)
  14067. return ma_semaphore_wait__win32(pSemaphore);
  14068. #endif
  14069. }
  14070. MA_API ma_result ma_semaphore_release(ma_semaphore* pSemaphore)
  14071. {
  14072. if (pSemaphore == NULL) {
  14073. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  14074. return MA_INVALID_ARGS;
  14075. }
  14076. #if defined(MA_POSIX)
  14077. return ma_semaphore_release__posix(pSemaphore);
  14078. #elif defined(MA_WIN32)
  14079. return ma_semaphore_release__win32(pSemaphore);
  14080. #endif
  14081. }
  14082. #else
  14083. /* MA_NO_THREADING is set which means threading is disabled. Threading is required by some API families. If any of these are enabled we need to throw an error. */
  14084. #ifndef MA_NO_DEVICE_IO
  14085. #error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO";
  14086. #endif
  14087. #endif /* MA_NO_THREADING */
  14088. #define MA_FENCE_COUNTER_MAX 0x7FFFFFFF
  14089. MA_API ma_result ma_fence_init(ma_fence* pFence)
  14090. {
  14091. if (pFence == NULL) {
  14092. return MA_INVALID_ARGS;
  14093. }
  14094. MA_ZERO_OBJECT(pFence);
  14095. pFence->counter = 0;
  14096. #ifndef MA_NO_THREADING
  14097. {
  14098. ma_result result;
  14099. result = ma_event_init(&pFence->e);
  14100. if (result != MA_SUCCESS) {
  14101. return result;
  14102. }
  14103. }
  14104. #endif
  14105. return MA_SUCCESS;
  14106. }
  14107. MA_API void ma_fence_uninit(ma_fence* pFence)
  14108. {
  14109. if (pFence == NULL) {
  14110. return;
  14111. }
  14112. #ifndef MA_NO_THREADING
  14113. {
  14114. ma_event_uninit(&pFence->e);
  14115. }
  14116. #endif
  14117. MA_ZERO_OBJECT(pFence);
  14118. }
  14119. MA_API ma_result ma_fence_acquire(ma_fence* pFence)
  14120. {
  14121. if (pFence == NULL) {
  14122. return MA_INVALID_ARGS;
  14123. }
  14124. for (;;) {
  14125. ma_uint32 oldCounter = c89atomic_load_32(&pFence->counter);
  14126. ma_uint32 newCounter = oldCounter + 1;
  14127. /* Make sure we're not about to exceed our maximum value. */
  14128. if (newCounter > MA_FENCE_COUNTER_MAX) {
  14129. MA_ASSERT(MA_FALSE);
  14130. return MA_OUT_OF_RANGE;
  14131. }
  14132. if (c89atomic_compare_exchange_weak_32(&pFence->counter, &oldCounter, newCounter)) {
  14133. return MA_SUCCESS;
  14134. } else {
  14135. if (oldCounter == MA_FENCE_COUNTER_MAX) {
  14136. MA_ASSERT(MA_FALSE);
  14137. return MA_OUT_OF_RANGE; /* The other thread took the last available slot. Abort. */
  14138. }
  14139. }
  14140. }
  14141. /* Should never get here. */
  14142. /*return MA_SUCCESS;*/
  14143. }
  14144. MA_API ma_result ma_fence_release(ma_fence* pFence)
  14145. {
  14146. if (pFence == NULL) {
  14147. return MA_INVALID_ARGS;
  14148. }
  14149. for (;;) {
  14150. ma_uint32 oldCounter = c89atomic_load_32(&pFence->counter);
  14151. ma_uint32 newCounter = oldCounter - 1;
  14152. if (oldCounter == 0) {
  14153. MA_ASSERT(MA_FALSE);
  14154. return MA_INVALID_OPERATION; /* Acquire/release mismatch. */
  14155. }
  14156. if (c89atomic_compare_exchange_weak_32(&pFence->counter, &oldCounter, newCounter)) {
  14157. #ifndef MA_NO_THREADING
  14158. {
  14159. if (newCounter == 0) {
  14160. ma_event_signal(&pFence->e); /* <-- ma_fence_wait() will be waiting on this. */
  14161. }
  14162. }
  14163. #endif
  14164. return MA_SUCCESS;
  14165. } else {
  14166. if (oldCounter == 0) {
  14167. MA_ASSERT(MA_FALSE);
  14168. return MA_INVALID_OPERATION; /* Another thread has taken the 0 slot. Acquire/release mismatch. */
  14169. }
  14170. }
  14171. }
  14172. /* Should never get here. */
  14173. /*return MA_SUCCESS;*/
  14174. }
  14175. MA_API ma_result ma_fence_wait(ma_fence* pFence)
  14176. {
  14177. if (pFence == NULL) {
  14178. return MA_INVALID_ARGS;
  14179. }
  14180. for (;;) {
  14181. ma_uint32 counter;
  14182. counter = c89atomic_load_32(&pFence->counter);
  14183. if (counter == 0) {
  14184. /*
  14185. Counter has hit zero. By the time we get here some other thread may have acquired the
  14186. fence again, but that is where the caller needs to take care with how they se the fence.
  14187. */
  14188. return MA_SUCCESS;
  14189. }
  14190. /* Getting here means the counter is > 0. We'll need to wait for something to happen. */
  14191. #ifndef MA_NO_THREADING
  14192. {
  14193. ma_result result;
  14194. result = ma_event_wait(&pFence->e);
  14195. if (result != MA_SUCCESS) {
  14196. return result;
  14197. }
  14198. }
  14199. #endif
  14200. }
  14201. /* Should never get here. */
  14202. /*return MA_INVALID_OPERATION;*/
  14203. }
  14204. MA_API ma_result ma_async_notification_signal(ma_async_notification* pNotification)
  14205. {
  14206. ma_async_notification_callbacks* pNotificationCallbacks = (ma_async_notification_callbacks*)pNotification;
  14207. if (pNotification == NULL) {
  14208. return MA_INVALID_ARGS;
  14209. }
  14210. if (pNotificationCallbacks->onSignal == NULL) {
  14211. return MA_NOT_IMPLEMENTED;
  14212. }
  14213. pNotificationCallbacks->onSignal(pNotification);
  14214. return MA_INVALID_ARGS;
  14215. }
  14216. static void ma_async_notification_poll__on_signal(ma_async_notification* pNotification)
  14217. {
  14218. ((ma_async_notification_poll*)pNotification)->signalled = MA_TRUE;
  14219. }
  14220. MA_API ma_result ma_async_notification_poll_init(ma_async_notification_poll* pNotificationPoll)
  14221. {
  14222. if (pNotificationPoll == NULL) {
  14223. return MA_INVALID_ARGS;
  14224. }
  14225. pNotificationPoll->cb.onSignal = ma_async_notification_poll__on_signal;
  14226. pNotificationPoll->signalled = MA_FALSE;
  14227. return MA_SUCCESS;
  14228. }
  14229. MA_API ma_bool32 ma_async_notification_poll_is_signalled(const ma_async_notification_poll* pNotificationPoll)
  14230. {
  14231. if (pNotificationPoll == NULL) {
  14232. return MA_FALSE;
  14233. }
  14234. return pNotificationPoll->signalled;
  14235. }
  14236. static void ma_async_notification_event__on_signal(ma_async_notification* pNotification)
  14237. {
  14238. ma_async_notification_event_signal((ma_async_notification_event*)pNotification);
  14239. }
  14240. MA_API ma_result ma_async_notification_event_init(ma_async_notification_event* pNotificationEvent)
  14241. {
  14242. if (pNotificationEvent == NULL) {
  14243. return MA_INVALID_ARGS;
  14244. }
  14245. pNotificationEvent->cb.onSignal = ma_async_notification_event__on_signal;
  14246. #ifndef MA_NO_THREADING
  14247. {
  14248. ma_result result;
  14249. result = ma_event_init(&pNotificationEvent->e);
  14250. if (result != MA_SUCCESS) {
  14251. return result;
  14252. }
  14253. return MA_SUCCESS;
  14254. }
  14255. #else
  14256. {
  14257. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  14258. }
  14259. #endif
  14260. }
  14261. MA_API ma_result ma_async_notification_event_uninit(ma_async_notification_event* pNotificationEvent)
  14262. {
  14263. if (pNotificationEvent == NULL) {
  14264. return MA_INVALID_ARGS;
  14265. }
  14266. #ifndef MA_NO_THREADING
  14267. {
  14268. ma_event_uninit(&pNotificationEvent->e);
  14269. return MA_SUCCESS;
  14270. }
  14271. #else
  14272. {
  14273. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  14274. }
  14275. #endif
  14276. }
  14277. MA_API ma_result ma_async_notification_event_wait(ma_async_notification_event* pNotificationEvent)
  14278. {
  14279. if (pNotificationEvent == NULL) {
  14280. return MA_INVALID_ARGS;
  14281. }
  14282. #ifndef MA_NO_THREADING
  14283. {
  14284. return ma_event_wait(&pNotificationEvent->e);
  14285. }
  14286. #else
  14287. {
  14288. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  14289. }
  14290. #endif
  14291. }
  14292. MA_API ma_result ma_async_notification_event_signal(ma_async_notification_event* pNotificationEvent)
  14293. {
  14294. if (pNotificationEvent == NULL) {
  14295. return MA_INVALID_ARGS;
  14296. }
  14297. #ifndef MA_NO_THREADING
  14298. {
  14299. return ma_event_signal(&pNotificationEvent->e);
  14300. }
  14301. #else
  14302. {
  14303. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  14304. }
  14305. #endif
  14306. }
  14307. /************************************************************************************************************************************************************
  14308. Job Queue
  14309. ************************************************************************************************************************************************************/
  14310. MA_API ma_slot_allocator_config ma_slot_allocator_config_init(ma_uint32 capacity)
  14311. {
  14312. ma_slot_allocator_config config;
  14313. MA_ZERO_OBJECT(&config);
  14314. config.capacity = capacity;
  14315. return config;
  14316. }
  14317. static MA_INLINE ma_uint32 ma_slot_allocator_calculate_group_capacity(ma_uint32 slotCapacity)
  14318. {
  14319. ma_uint32 cap = slotCapacity / 32;
  14320. if ((slotCapacity % 32) != 0) {
  14321. cap += 1;
  14322. }
  14323. return cap;
  14324. }
  14325. static MA_INLINE ma_uint32 ma_slot_allocator_group_capacity(const ma_slot_allocator* pAllocator)
  14326. {
  14327. return ma_slot_allocator_calculate_group_capacity(pAllocator->capacity);
  14328. }
  14329. typedef struct
  14330. {
  14331. size_t sizeInBytes;
  14332. size_t groupsOffset;
  14333. size_t slotsOffset;
  14334. } ma_slot_allocator_heap_layout;
  14335. static ma_result ma_slot_allocator_get_heap_layout(const ma_slot_allocator_config* pConfig, ma_slot_allocator_heap_layout* pHeapLayout)
  14336. {
  14337. MA_ASSERT(pHeapLayout != NULL);
  14338. MA_ZERO_OBJECT(pHeapLayout);
  14339. if (pConfig == NULL) {
  14340. return MA_INVALID_ARGS;
  14341. }
  14342. if (pConfig->capacity == 0) {
  14343. return MA_INVALID_ARGS;
  14344. }
  14345. pHeapLayout->sizeInBytes = 0;
  14346. /* Groups. */
  14347. pHeapLayout->groupsOffset = pHeapLayout->sizeInBytes;
  14348. pHeapLayout->sizeInBytes += ma_align_64(ma_slot_allocator_calculate_group_capacity(pConfig->capacity) * sizeof(ma_slot_allocator_group));
  14349. /* Slots. */
  14350. pHeapLayout->slotsOffset = pHeapLayout->sizeInBytes;
  14351. pHeapLayout->sizeInBytes += ma_align_64(pConfig->capacity * sizeof(ma_uint32));
  14352. return MA_SUCCESS;
  14353. }
  14354. MA_API ma_result ma_slot_allocator_get_heap_size(const ma_slot_allocator_config* pConfig, size_t* pHeapSizeInBytes)
  14355. {
  14356. ma_result result;
  14357. ma_slot_allocator_heap_layout layout;
  14358. if (pHeapSizeInBytes == NULL) {
  14359. return MA_INVALID_ARGS;
  14360. }
  14361. *pHeapSizeInBytes = 0;
  14362. result = ma_slot_allocator_get_heap_layout(pConfig, &layout);
  14363. if (result != MA_SUCCESS) {
  14364. return result;
  14365. }
  14366. *pHeapSizeInBytes = layout.sizeInBytes;
  14367. return result;
  14368. }
  14369. MA_API ma_result ma_slot_allocator_init_preallocated(const ma_slot_allocator_config* pConfig, void* pHeap, ma_slot_allocator* pAllocator)
  14370. {
  14371. ma_result result;
  14372. ma_slot_allocator_heap_layout heapLayout;
  14373. if (pAllocator == NULL) {
  14374. return MA_INVALID_ARGS;
  14375. }
  14376. MA_ZERO_OBJECT(pAllocator);
  14377. if (pHeap == NULL) {
  14378. return MA_INVALID_ARGS;
  14379. }
  14380. result = ma_slot_allocator_get_heap_layout(pConfig, &heapLayout);
  14381. if (result != MA_SUCCESS) {
  14382. return result;
  14383. }
  14384. pAllocator->_pHeap = pHeap;
  14385. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  14386. pAllocator->pGroups = (ma_slot_allocator_group*)ma_offset_ptr(pHeap, heapLayout.groupsOffset);
  14387. pAllocator->pSlots = (ma_uint32*)ma_offset_ptr(pHeap, heapLayout.slotsOffset);
  14388. pAllocator->capacity = pConfig->capacity;
  14389. return MA_SUCCESS;
  14390. }
  14391. MA_API ma_result ma_slot_allocator_init(const ma_slot_allocator_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_slot_allocator* pAllocator)
  14392. {
  14393. ma_result result;
  14394. size_t heapSizeInBytes;
  14395. void* pHeap;
  14396. result = ma_slot_allocator_get_heap_size(pConfig, &heapSizeInBytes);
  14397. if (result != MA_SUCCESS) {
  14398. return result; /* Failed to retrieve the size of the heap allocation. */
  14399. }
  14400. if (heapSizeInBytes > 0) {
  14401. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  14402. if (pHeap == NULL) {
  14403. return MA_OUT_OF_MEMORY;
  14404. }
  14405. } else {
  14406. pHeap = NULL;
  14407. }
  14408. result = ma_slot_allocator_init_preallocated(pConfig, pHeap, pAllocator);
  14409. if (result != MA_SUCCESS) {
  14410. ma_free(pHeap, pAllocationCallbacks);
  14411. return result;
  14412. }
  14413. pAllocator->_ownsHeap = MA_TRUE;
  14414. return MA_SUCCESS;
  14415. }
  14416. MA_API void ma_slot_allocator_uninit(ma_slot_allocator* pAllocator, const ma_allocation_callbacks* pAllocationCallbacks)
  14417. {
  14418. if (pAllocator == NULL) {
  14419. return;
  14420. }
  14421. if (pAllocator->_ownsHeap) {
  14422. ma_free(pAllocator->_pHeap, pAllocationCallbacks);
  14423. }
  14424. }
  14425. MA_API ma_result ma_slot_allocator_alloc(ma_slot_allocator* pAllocator, ma_uint64* pSlot)
  14426. {
  14427. ma_uint32 iAttempt;
  14428. const ma_uint32 maxAttempts = 2; /* The number of iterations to perform until returning MA_OUT_OF_MEMORY if no slots can be found. */
  14429. if (pAllocator == NULL || pSlot == NULL) {
  14430. return MA_INVALID_ARGS;
  14431. }
  14432. for (iAttempt = 0; iAttempt < maxAttempts; iAttempt += 1) {
  14433. /* We need to acquire a suitable bitfield first. This is a bitfield that's got an available slot within it. */
  14434. ma_uint32 iGroup;
  14435. for (iGroup = 0; iGroup < ma_slot_allocator_group_capacity(pAllocator); iGroup += 1) {
  14436. /* CAS */
  14437. for (;;) {
  14438. ma_uint32 oldBitfield;
  14439. ma_uint32 newBitfield;
  14440. ma_uint32 bitOffset;
  14441. oldBitfield = c89atomic_load_32(&pAllocator->pGroups[iGroup].bitfield); /* <-- This copy must happen. The compiler must not optimize this away. */
  14442. /* Fast check to see if anything is available. */
  14443. if (oldBitfield == 0xFFFFFFFF) {
  14444. break; /* No available bits in this bitfield. */
  14445. }
  14446. bitOffset = ma_ffs_32(~oldBitfield);
  14447. MA_ASSERT(bitOffset < 32);
  14448. newBitfield = oldBitfield | (1 << bitOffset);
  14449. if (c89atomic_compare_and_swap_32(&pAllocator->pGroups[iGroup].bitfield, oldBitfield, newBitfield) == oldBitfield) {
  14450. ma_uint32 slotIndex;
  14451. /* Increment the counter as soon as possible to have other threads report out-of-memory sooner than later. */
  14452. c89atomic_fetch_add_32(&pAllocator->count, 1);
  14453. /* The slot index is required for constructing the output value. */
  14454. slotIndex = (iGroup << 5) + bitOffset; /* iGroup << 5 = iGroup * 32 */
  14455. if (slotIndex >= pAllocator->capacity) {
  14456. return MA_OUT_OF_MEMORY;
  14457. }
  14458. /* Increment the reference count before constructing the output value. */
  14459. pAllocator->pSlots[slotIndex] += 1;
  14460. /* Construct the output value. */
  14461. *pSlot = (((ma_uint64)pAllocator->pSlots[slotIndex] << 32) | slotIndex);
  14462. return MA_SUCCESS;
  14463. }
  14464. }
  14465. }
  14466. /* We weren't able to find a slot. If it's because we've reached our capacity we need to return MA_OUT_OF_MEMORY. Otherwise we need to do another iteration and try again. */
  14467. if (pAllocator->count < pAllocator->capacity) {
  14468. ma_yield();
  14469. } else {
  14470. return MA_OUT_OF_MEMORY;
  14471. }
  14472. }
  14473. /* We couldn't find a slot within the maximum number of attempts. */
  14474. return MA_OUT_OF_MEMORY;
  14475. }
  14476. MA_API ma_result ma_slot_allocator_free(ma_slot_allocator* pAllocator, ma_uint64 slot)
  14477. {
  14478. ma_uint32 iGroup;
  14479. ma_uint32 iBit;
  14480. if (pAllocator == NULL) {
  14481. return MA_INVALID_ARGS;
  14482. }
  14483. iGroup = (ma_uint32)((slot & 0xFFFFFFFF) >> 5); /* slot / 32 */
  14484. iBit = (ma_uint32)((slot & 0xFFFFFFFF) & 31); /* slot % 32 */
  14485. if (iGroup >= ma_slot_allocator_group_capacity(pAllocator)) {
  14486. return MA_INVALID_ARGS;
  14487. }
  14488. MA_ASSERT(iBit < 32); /* This must be true due to the logic we used to actually calculate it. */
  14489. while (c89atomic_load_32(&pAllocator->count) > 0) {
  14490. /* CAS */
  14491. ma_uint32 oldBitfield;
  14492. ma_uint32 newBitfield;
  14493. oldBitfield = c89atomic_load_32(&pAllocator->pGroups[iGroup].bitfield); /* <-- This copy must happen. The compiler must not optimize this away. */
  14494. newBitfield = oldBitfield & ~(1 << iBit);
  14495. /* Debugging for checking for double-frees. */
  14496. #if defined(MA_DEBUG_OUTPUT)
  14497. {
  14498. if ((oldBitfield & (1 << iBit)) == 0) {
  14499. MA_ASSERT(MA_FALSE); /* Double free detected.*/
  14500. }
  14501. }
  14502. #endif
  14503. if (c89atomic_compare_and_swap_32(&pAllocator->pGroups[iGroup].bitfield, oldBitfield, newBitfield) == oldBitfield) {
  14504. c89atomic_fetch_sub_32(&pAllocator->count, 1);
  14505. return MA_SUCCESS;
  14506. }
  14507. }
  14508. /* Getting here means there are no allocations available for freeing. */
  14509. return MA_INVALID_OPERATION;
  14510. }
  14511. #define MA_JOB_ID_NONE ~((ma_uint64)0)
  14512. #define MA_JOB_SLOT_NONE (ma_uint16)(~0)
  14513. static MA_INLINE ma_uint32 ma_job_extract_refcount(ma_uint64 toc)
  14514. {
  14515. return (ma_uint32)(toc >> 32);
  14516. }
  14517. static MA_INLINE ma_uint16 ma_job_extract_slot(ma_uint64 toc)
  14518. {
  14519. return (ma_uint16)(toc & 0x0000FFFF);
  14520. }
  14521. static MA_INLINE ma_uint16 ma_job_extract_code(ma_uint64 toc)
  14522. {
  14523. return (ma_uint16)((toc & 0xFFFF0000) >> 16);
  14524. }
  14525. static MA_INLINE ma_uint64 ma_job_toc_to_allocation(ma_uint64 toc)
  14526. {
  14527. return ((ma_uint64)ma_job_extract_refcount(toc) << 32) | (ma_uint64)ma_job_extract_slot(toc);
  14528. }
  14529. static MA_INLINE ma_uint64 ma_job_set_refcount(ma_uint64 toc, ma_uint32 refcount)
  14530. {
  14531. /* Clear the reference count first. */
  14532. toc = toc & ~((ma_uint64)0xFFFFFFFF << 32);
  14533. toc = toc | ((ma_uint64)refcount << 32);
  14534. return toc;
  14535. }
  14536. MA_API ma_job ma_job_init(ma_uint16 code)
  14537. {
  14538. ma_job job;
  14539. MA_ZERO_OBJECT(&job);
  14540. job.toc.breakup.code = code;
  14541. job.toc.breakup.slot = MA_JOB_SLOT_NONE; /* Temp value. Will be allocated when posted to a queue. */
  14542. job.next = MA_JOB_ID_NONE;
  14543. return job;
  14544. }
  14545. static ma_result ma_job_process__noop(ma_job* pJob);
  14546. static ma_result ma_job_process__quit(ma_job* pJob);
  14547. static ma_result ma_job_process__custom(ma_job* pJob);
  14548. static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob);
  14549. static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob);
  14550. static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob);
  14551. static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob);
  14552. static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob);
  14553. static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob);
  14554. static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob);
  14555. static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob);
  14556. static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob);
  14557. #if !defined(MA_NO_DEVICE_IO)
  14558. static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob);
  14559. #endif
  14560. static ma_job_proc g_jobVTable[MA_JOB_TYPE_COUNT] =
  14561. {
  14562. /* Miscellaneous. */
  14563. ma_job_process__quit, /* MA_JOB_TYPE_QUIT */
  14564. ma_job_process__custom, /* MA_JOB_TYPE_CUSTOM */
  14565. /* Resource Manager. */
  14566. ma_job_process__resource_manager__load_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE */
  14567. ma_job_process__resource_manager__free_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE */
  14568. ma_job_process__resource_manager__page_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE */
  14569. ma_job_process__resource_manager__load_data_buffer, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER */
  14570. ma_job_process__resource_manager__free_data_buffer, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER */
  14571. ma_job_process__resource_manager__load_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM */
  14572. ma_job_process__resource_manager__free_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM */
  14573. ma_job_process__resource_manager__page_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM */
  14574. ma_job_process__resource_manager__seek_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM */
  14575. /* Device. */
  14576. #if !defined(MA_NO_DEVICE_IO)
  14577. ma_job_process__device__aaudio_reroute /*MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE*/
  14578. #endif
  14579. };
  14580. MA_API ma_result ma_job_process(ma_job* pJob)
  14581. {
  14582. if (pJob == NULL) {
  14583. return MA_INVALID_ARGS;
  14584. }
  14585. if (pJob->toc.breakup.code >= MA_JOB_TYPE_COUNT) {
  14586. return MA_INVALID_OPERATION;
  14587. }
  14588. return g_jobVTable[pJob->toc.breakup.code](pJob);
  14589. }
  14590. static ma_result ma_job_process__noop(ma_job* pJob)
  14591. {
  14592. MA_ASSERT(pJob != NULL);
  14593. /* No-op. */
  14594. (void)pJob;
  14595. return MA_SUCCESS;
  14596. }
  14597. static ma_result ma_job_process__quit(ma_job* pJob)
  14598. {
  14599. return ma_job_process__noop(pJob);
  14600. }
  14601. static ma_result ma_job_process__custom(ma_job* pJob)
  14602. {
  14603. MA_ASSERT(pJob != NULL);
  14604. /* No-op if there's no callback. */
  14605. if (pJob->data.custom.proc == NULL) {
  14606. return MA_SUCCESS;
  14607. }
  14608. return pJob->data.custom.proc(pJob);
  14609. }
  14610. MA_API ma_job_queue_config ma_job_queue_config_init(ma_uint32 flags, ma_uint32 capacity)
  14611. {
  14612. ma_job_queue_config config;
  14613. config.flags = flags;
  14614. config.capacity = capacity;
  14615. return config;
  14616. }
  14617. typedef struct
  14618. {
  14619. size_t sizeInBytes;
  14620. size_t allocatorOffset;
  14621. size_t jobsOffset;
  14622. } ma_job_queue_heap_layout;
  14623. static ma_result ma_job_queue_get_heap_layout(const ma_job_queue_config* pConfig, ma_job_queue_heap_layout* pHeapLayout)
  14624. {
  14625. ma_result result;
  14626. MA_ASSERT(pHeapLayout != NULL);
  14627. MA_ZERO_OBJECT(pHeapLayout);
  14628. if (pConfig == NULL) {
  14629. return MA_INVALID_ARGS;
  14630. }
  14631. if (pConfig->capacity == 0) {
  14632. return MA_INVALID_ARGS;
  14633. }
  14634. pHeapLayout->sizeInBytes = 0;
  14635. /* Allocator. */
  14636. {
  14637. ma_slot_allocator_config allocatorConfig;
  14638. size_t allocatorHeapSizeInBytes;
  14639. allocatorConfig = ma_slot_allocator_config_init(pConfig->capacity);
  14640. result = ma_slot_allocator_get_heap_size(&allocatorConfig, &allocatorHeapSizeInBytes);
  14641. if (result != MA_SUCCESS) {
  14642. return result;
  14643. }
  14644. pHeapLayout->allocatorOffset = pHeapLayout->sizeInBytes;
  14645. pHeapLayout->sizeInBytes += allocatorHeapSizeInBytes;
  14646. }
  14647. /* Jobs. */
  14648. pHeapLayout->jobsOffset = pHeapLayout->sizeInBytes;
  14649. pHeapLayout->sizeInBytes += ma_align_64(pConfig->capacity * sizeof(ma_job));
  14650. return MA_SUCCESS;
  14651. }
  14652. MA_API ma_result ma_job_queue_get_heap_size(const ma_job_queue_config* pConfig, size_t* pHeapSizeInBytes)
  14653. {
  14654. ma_result result;
  14655. ma_job_queue_heap_layout layout;
  14656. if (pHeapSizeInBytes == NULL) {
  14657. return MA_INVALID_ARGS;
  14658. }
  14659. *pHeapSizeInBytes = 0;
  14660. result = ma_job_queue_get_heap_layout(pConfig, &layout);
  14661. if (result != MA_SUCCESS) {
  14662. return result;
  14663. }
  14664. *pHeapSizeInBytes = layout.sizeInBytes;
  14665. return MA_SUCCESS;
  14666. }
  14667. MA_API ma_result ma_job_queue_init_preallocated(const ma_job_queue_config* pConfig, void* pHeap, ma_job_queue* pQueue)
  14668. {
  14669. ma_result result;
  14670. ma_job_queue_heap_layout heapLayout;
  14671. ma_slot_allocator_config allocatorConfig;
  14672. if (pQueue == NULL) {
  14673. return MA_INVALID_ARGS;
  14674. }
  14675. MA_ZERO_OBJECT(pQueue);
  14676. result = ma_job_queue_get_heap_layout(pConfig, &heapLayout);
  14677. if (result != MA_SUCCESS) {
  14678. return result;
  14679. }
  14680. pQueue->_pHeap = pHeap;
  14681. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  14682. pQueue->flags = pConfig->flags;
  14683. pQueue->capacity = pConfig->capacity;
  14684. pQueue->pJobs = (ma_job*)ma_offset_ptr(pHeap, heapLayout.jobsOffset);
  14685. allocatorConfig = ma_slot_allocator_config_init(pConfig->capacity);
  14686. result = ma_slot_allocator_init_preallocated(&allocatorConfig, ma_offset_ptr(pHeap, heapLayout.allocatorOffset), &pQueue->allocator);
  14687. if (result != MA_SUCCESS) {
  14688. return result;
  14689. }
  14690. /* We need a semaphore if we're running in non-blocking mode. If threading is disabled we need to return an error. */
  14691. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14692. #ifndef MA_NO_THREADING
  14693. {
  14694. ma_semaphore_init(0, &pQueue->sem);
  14695. }
  14696. #else
  14697. {
  14698. /* Threading is disabled and we've requested non-blocking mode. */
  14699. return MA_INVALID_OPERATION;
  14700. }
  14701. #endif
  14702. }
  14703. /*
  14704. Our queue needs to be initialized with a free standing node. This should always be slot 0. Required for the lock free algorithm. The first job in the queue is
  14705. just a dummy item for giving us the first item in the list which is stored in the "next" member.
  14706. */
  14707. ma_slot_allocator_alloc(&pQueue->allocator, &pQueue->head); /* Will never fail. */
  14708. pQueue->pJobs[ma_job_extract_slot(pQueue->head)].next = MA_JOB_ID_NONE;
  14709. pQueue->tail = pQueue->head;
  14710. return MA_SUCCESS;
  14711. }
  14712. MA_API ma_result ma_job_queue_init(const ma_job_queue_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_job_queue* pQueue)
  14713. {
  14714. ma_result result;
  14715. size_t heapSizeInBytes;
  14716. void* pHeap;
  14717. result = ma_job_queue_get_heap_size(pConfig, &heapSizeInBytes);
  14718. if (result != MA_SUCCESS) {
  14719. return result;
  14720. }
  14721. if (heapSizeInBytes > 0) {
  14722. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  14723. if (pHeap == NULL) {
  14724. return MA_OUT_OF_MEMORY;
  14725. }
  14726. } else {
  14727. pHeap = NULL;
  14728. }
  14729. result = ma_job_queue_init_preallocated(pConfig, pHeap, pQueue);
  14730. if (result != MA_SUCCESS) {
  14731. ma_free(pHeap, pAllocationCallbacks);
  14732. return result;
  14733. }
  14734. pQueue->_ownsHeap = MA_TRUE;
  14735. return MA_SUCCESS;
  14736. }
  14737. MA_API void ma_job_queue_uninit(ma_job_queue* pQueue, const ma_allocation_callbacks* pAllocationCallbacks)
  14738. {
  14739. if (pQueue == NULL) {
  14740. return;
  14741. }
  14742. /* All we need to do is uninitialize the semaphore. */
  14743. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14744. #ifndef MA_NO_THREADING
  14745. {
  14746. ma_semaphore_uninit(&pQueue->sem);
  14747. }
  14748. #else
  14749. {
  14750. MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */
  14751. }
  14752. #endif
  14753. }
  14754. ma_slot_allocator_uninit(&pQueue->allocator, pAllocationCallbacks);
  14755. if (pQueue->_ownsHeap) {
  14756. ma_free(pQueue->_pHeap, pAllocationCallbacks);
  14757. }
  14758. }
  14759. static ma_bool32 ma_job_queue_cas(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired)
  14760. {
  14761. /* The new counter is taken from the expected value. */
  14762. return c89atomic_compare_and_swap_64(dst, expected, ma_job_set_refcount(desired, ma_job_extract_refcount(expected) + 1)) == expected;
  14763. }
  14764. MA_API ma_result ma_job_queue_post(ma_job_queue* pQueue, const ma_job* pJob)
  14765. {
  14766. /*
  14767. Lock free queue implementation based on the paper by Michael and Scott: Nonblocking Algorithms and Preemption-Safe Locking on Multiprogrammed Shared Memory Multiprocessors
  14768. */
  14769. ma_result result;
  14770. ma_uint64 slot;
  14771. ma_uint64 tail;
  14772. ma_uint64 next;
  14773. if (pQueue == NULL || pJob == NULL) {
  14774. return MA_INVALID_ARGS;
  14775. }
  14776. /* We need a new slot. */
  14777. result = ma_slot_allocator_alloc(&pQueue->allocator, &slot);
  14778. if (result != MA_SUCCESS) {
  14779. return result; /* Probably ran out of slots. If so, MA_OUT_OF_MEMORY will be returned. */
  14780. }
  14781. /* At this point we should have a slot to place the job. */
  14782. MA_ASSERT(ma_job_extract_slot(slot) < pQueue->capacity);
  14783. /* We need to put the job into memory before we do anything. */
  14784. pQueue->pJobs[ma_job_extract_slot(slot)] = *pJob;
  14785. pQueue->pJobs[ma_job_extract_slot(slot)].toc.allocation = slot; /* This will overwrite the job code. */
  14786. pQueue->pJobs[ma_job_extract_slot(slot)].toc.breakup.code = pJob->toc.breakup.code; /* The job code needs to be applied again because the line above overwrote it. */
  14787. pQueue->pJobs[ma_job_extract_slot(slot)].next = MA_JOB_ID_NONE; /* Reset for safety. */
  14788. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14789. ma_spinlock_lock(&pQueue->lock);
  14790. #endif
  14791. {
  14792. /* The job is stored in memory so now we need to add it to our linked list. We only ever add items to the end of the list. */
  14793. for (;;) {
  14794. tail = c89atomic_load_64(&pQueue->tail);
  14795. next = c89atomic_load_64(&pQueue->pJobs[ma_job_extract_slot(tail)].next);
  14796. if (ma_job_toc_to_allocation(tail) == ma_job_toc_to_allocation(c89atomic_load_64(&pQueue->tail))) {
  14797. if (ma_job_extract_slot(next) == 0xFFFF) {
  14798. if (ma_job_queue_cas(&pQueue->pJobs[ma_job_extract_slot(tail)].next, next, slot)) {
  14799. break;
  14800. }
  14801. } else {
  14802. ma_job_queue_cas(&pQueue->tail, tail, ma_job_extract_slot(next));
  14803. }
  14804. }
  14805. }
  14806. ma_job_queue_cas(&pQueue->tail, tail, slot);
  14807. }
  14808. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14809. ma_spinlock_unlock(&pQueue->lock);
  14810. #endif
  14811. /* Signal the semaphore as the last step if we're using synchronous mode. */
  14812. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14813. #ifndef MA_NO_THREADING
  14814. {
  14815. ma_semaphore_release(&pQueue->sem);
  14816. }
  14817. #else
  14818. {
  14819. MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */
  14820. }
  14821. #endif
  14822. }
  14823. return MA_SUCCESS;
  14824. }
  14825. MA_API ma_result ma_job_queue_next(ma_job_queue* pQueue, ma_job* pJob)
  14826. {
  14827. ma_uint64 head;
  14828. ma_uint64 tail;
  14829. ma_uint64 next;
  14830. if (pQueue == NULL || pJob == NULL) {
  14831. return MA_INVALID_ARGS;
  14832. }
  14833. /* If we're running in synchronous mode we'll need to wait on a semaphore. */
  14834. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14835. #ifndef MA_NO_THREADING
  14836. {
  14837. ma_semaphore_wait(&pQueue->sem);
  14838. }
  14839. #else
  14840. {
  14841. MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */
  14842. }
  14843. #endif
  14844. }
  14845. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14846. ma_spinlock_lock(&pQueue->lock);
  14847. #endif
  14848. {
  14849. /*
  14850. BUG: In lock-free mode, multiple threads can be in this section of code. The "head" variable in the loop below
  14851. is stored. One thread can fall through to the freeing of this item while another is still using "head" for the
  14852. retrieval of the "next" variable.
  14853. The slot allocator might need to make use of some reference counting to ensure it's only truely freed when
  14854. there are no more references to the item. This must be fixed before removing these locks.
  14855. */
  14856. /* Now we need to remove the root item from the list. */
  14857. for (;;) {
  14858. head = c89atomic_load_64(&pQueue->head);
  14859. tail = c89atomic_load_64(&pQueue->tail);
  14860. next = c89atomic_load_64(&pQueue->pJobs[ma_job_extract_slot(head)].next);
  14861. if (ma_job_toc_to_allocation(head) == ma_job_toc_to_allocation(c89atomic_load_64(&pQueue->head))) {
  14862. if (ma_job_extract_slot(head) == ma_job_extract_slot(tail)) {
  14863. if (ma_job_extract_slot(next) == 0xFFFF) {
  14864. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14865. ma_spinlock_unlock(&pQueue->lock);
  14866. #endif
  14867. return MA_NO_DATA_AVAILABLE;
  14868. }
  14869. ma_job_queue_cas(&pQueue->tail, tail, ma_job_extract_slot(next));
  14870. } else {
  14871. *pJob = pQueue->pJobs[ma_job_extract_slot(next)];
  14872. if (ma_job_queue_cas(&pQueue->head, head, ma_job_extract_slot(next))) {
  14873. break;
  14874. }
  14875. }
  14876. }
  14877. }
  14878. }
  14879. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14880. ma_spinlock_unlock(&pQueue->lock);
  14881. #endif
  14882. ma_slot_allocator_free(&pQueue->allocator, head);
  14883. /*
  14884. If it's a quit job make sure it's put back on the queue to ensure other threads have an opportunity to detect it and terminate naturally. We
  14885. could instead just leave it on the queue, but that would involve fiddling with the lock-free code above and I want to keep that as simple as
  14886. possible.
  14887. */
  14888. if (pJob->toc.breakup.code == MA_JOB_TYPE_QUIT) {
  14889. ma_job_queue_post(pQueue, pJob);
  14890. return MA_CANCELLED; /* Return a cancelled status just in case the thread is checking return codes and not properly checking for a quit job. */
  14891. }
  14892. return MA_SUCCESS;
  14893. }
  14894. /************************************************************************************************************************************************************
  14895. *************************************************************************************************************************************************************
  14896. DEVICE I/O
  14897. ==========
  14898. *************************************************************************************************************************************************************
  14899. ************************************************************************************************************************************************************/
  14900. /* Disable run-time linking on certain backends and platforms. */
  14901. #ifndef MA_NO_RUNTIME_LINKING
  14902. #if defined(MA_EMSCRIPTEN) || defined(MA_ORBIS) || defined(MA_PROSPERO)
  14903. #define MA_NO_RUNTIME_LINKING
  14904. #endif
  14905. #endif
  14906. #ifndef MA_NO_DEVICE_IO
  14907. #if defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
  14908. #include <mach/mach_time.h> /* For mach_absolute_time() */
  14909. #endif
  14910. #ifdef MA_POSIX
  14911. #include <sys/types.h>
  14912. #include <unistd.h>
  14913. /* No need for dlfcn.h if we're not using runtime linking. */
  14914. #ifndef MA_NO_RUNTIME_LINKING
  14915. #include <dlfcn.h>
  14916. #endif
  14917. #endif
  14918. MA_API void ma_device_info_add_native_data_format(ma_device_info* pDeviceInfo, ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 flags)
  14919. {
  14920. if (pDeviceInfo == NULL) {
  14921. return;
  14922. }
  14923. if (pDeviceInfo->nativeDataFormatCount < ma_countof(pDeviceInfo->nativeDataFormats)) {
  14924. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  14925. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  14926. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  14927. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags;
  14928. pDeviceInfo->nativeDataFormatCount += 1;
  14929. }
  14930. }
  14931. typedef struct
  14932. {
  14933. ma_backend backend;
  14934. const char* pName;
  14935. } ma_backend_info;
  14936. static ma_backend_info gBackendInfo[] = /* Indexed by the backend enum. Must be in the order backends are declared in the ma_backend enum. */
  14937. {
  14938. {ma_backend_wasapi, "WASAPI"},
  14939. {ma_backend_dsound, "DirectSound"},
  14940. {ma_backend_winmm, "WinMM"},
  14941. {ma_backend_coreaudio, "Core Audio"},
  14942. {ma_backend_sndio, "sndio"},
  14943. {ma_backend_audio4, "audio(4)"},
  14944. {ma_backend_oss, "OSS"},
  14945. {ma_backend_pulseaudio, "PulseAudio"},
  14946. {ma_backend_alsa, "ALSA"},
  14947. {ma_backend_jack, "JACK"},
  14948. {ma_backend_aaudio, "AAudio"},
  14949. {ma_backend_opensl, "OpenSL|ES"},
  14950. {ma_backend_webaudio, "Web Audio"},
  14951. {ma_backend_custom, "Custom"},
  14952. {ma_backend_null, "Null"}
  14953. };
  14954. MA_API const char* ma_get_backend_name(ma_backend backend)
  14955. {
  14956. if (backend < 0 || backend >= (int)ma_countof(gBackendInfo)) {
  14957. return "Unknown";
  14958. }
  14959. return gBackendInfo[backend].pName;
  14960. }
  14961. MA_API ma_result ma_get_backend_from_name(const char* pBackendName, ma_backend* pBackend)
  14962. {
  14963. size_t iBackend;
  14964. if (pBackendName == NULL) {
  14965. return MA_INVALID_ARGS;
  14966. }
  14967. for (iBackend = 0; iBackend < ma_countof(gBackendInfo); iBackend += 1) {
  14968. if (ma_strcmp(pBackendName, gBackendInfo[iBackend].pName) == 0) {
  14969. if (pBackend != NULL) {
  14970. *pBackend = gBackendInfo[iBackend].backend;
  14971. }
  14972. return MA_SUCCESS;
  14973. }
  14974. }
  14975. /* Getting here means the backend name is unknown. */
  14976. return MA_INVALID_ARGS;
  14977. }
  14978. MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend)
  14979. {
  14980. /*
  14981. This looks a little bit gross, but we want all backends to be included in the switch to avoid warnings on some compilers
  14982. about some enums not being handled by the switch statement.
  14983. */
  14984. switch (backend)
  14985. {
  14986. case ma_backend_wasapi:
  14987. #if defined(MA_HAS_WASAPI)
  14988. return MA_TRUE;
  14989. #else
  14990. return MA_FALSE;
  14991. #endif
  14992. case ma_backend_dsound:
  14993. #if defined(MA_HAS_DSOUND)
  14994. return MA_TRUE;
  14995. #else
  14996. return MA_FALSE;
  14997. #endif
  14998. case ma_backend_winmm:
  14999. #if defined(MA_HAS_WINMM)
  15000. return MA_TRUE;
  15001. #else
  15002. return MA_FALSE;
  15003. #endif
  15004. case ma_backend_coreaudio:
  15005. #if defined(MA_HAS_COREAUDIO)
  15006. return MA_TRUE;
  15007. #else
  15008. return MA_FALSE;
  15009. #endif
  15010. case ma_backend_sndio:
  15011. #if defined(MA_HAS_SNDIO)
  15012. return MA_TRUE;
  15013. #else
  15014. return MA_FALSE;
  15015. #endif
  15016. case ma_backend_audio4:
  15017. #if defined(MA_HAS_AUDIO4)
  15018. return MA_TRUE;
  15019. #else
  15020. return MA_FALSE;
  15021. #endif
  15022. case ma_backend_oss:
  15023. #if defined(MA_HAS_OSS)
  15024. return MA_TRUE;
  15025. #else
  15026. return MA_FALSE;
  15027. #endif
  15028. case ma_backend_pulseaudio:
  15029. #if defined(MA_HAS_PULSEAUDIO)
  15030. return MA_TRUE;
  15031. #else
  15032. return MA_FALSE;
  15033. #endif
  15034. case ma_backend_alsa:
  15035. #if defined(MA_HAS_ALSA)
  15036. return MA_TRUE;
  15037. #else
  15038. return MA_FALSE;
  15039. #endif
  15040. case ma_backend_jack:
  15041. #if defined(MA_HAS_JACK)
  15042. return MA_TRUE;
  15043. #else
  15044. return MA_FALSE;
  15045. #endif
  15046. case ma_backend_aaudio:
  15047. #if defined(MA_HAS_AAUDIO)
  15048. #if defined(MA_ANDROID)
  15049. {
  15050. return ma_android_sdk_version() >= 26;
  15051. }
  15052. #else
  15053. return MA_FALSE;
  15054. #endif
  15055. #else
  15056. return MA_FALSE;
  15057. #endif
  15058. case ma_backend_opensl:
  15059. #if defined(MA_HAS_OPENSL)
  15060. #if defined(MA_ANDROID)
  15061. {
  15062. return ma_android_sdk_version() >= 9;
  15063. }
  15064. #else
  15065. return MA_TRUE;
  15066. #endif
  15067. #else
  15068. return MA_FALSE;
  15069. #endif
  15070. case ma_backend_webaudio:
  15071. #if defined(MA_HAS_WEBAUDIO)
  15072. return MA_TRUE;
  15073. #else
  15074. return MA_FALSE;
  15075. #endif
  15076. case ma_backend_custom:
  15077. #if defined(MA_HAS_CUSTOM)
  15078. return MA_TRUE;
  15079. #else
  15080. return MA_FALSE;
  15081. #endif
  15082. case ma_backend_null:
  15083. #if defined(MA_HAS_NULL)
  15084. return MA_TRUE;
  15085. #else
  15086. return MA_FALSE;
  15087. #endif
  15088. default: return MA_FALSE;
  15089. }
  15090. }
  15091. MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount)
  15092. {
  15093. size_t backendCount;
  15094. size_t iBackend;
  15095. ma_result result = MA_SUCCESS;
  15096. if (pBackendCount == NULL) {
  15097. return MA_INVALID_ARGS;
  15098. }
  15099. backendCount = 0;
  15100. for (iBackend = 0; iBackend <= ma_backend_null; iBackend += 1) {
  15101. ma_backend backend = (ma_backend)iBackend;
  15102. if (ma_is_backend_enabled(backend)) {
  15103. /* The backend is enabled. Try adding it to the list. If there's no room, MA_NO_SPACE needs to be returned. */
  15104. if (backendCount == backendCap) {
  15105. result = MA_NO_SPACE;
  15106. break;
  15107. } else {
  15108. pBackends[backendCount] = backend;
  15109. backendCount += 1;
  15110. }
  15111. }
  15112. }
  15113. if (pBackendCount != NULL) {
  15114. *pBackendCount = backendCount;
  15115. }
  15116. return result;
  15117. }
  15118. MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend)
  15119. {
  15120. switch (backend)
  15121. {
  15122. case ma_backend_wasapi: return MA_TRUE;
  15123. case ma_backend_dsound: return MA_FALSE;
  15124. case ma_backend_winmm: return MA_FALSE;
  15125. case ma_backend_coreaudio: return MA_FALSE;
  15126. case ma_backend_sndio: return MA_FALSE;
  15127. case ma_backend_audio4: return MA_FALSE;
  15128. case ma_backend_oss: return MA_FALSE;
  15129. case ma_backend_pulseaudio: return MA_FALSE;
  15130. case ma_backend_alsa: return MA_FALSE;
  15131. case ma_backend_jack: return MA_FALSE;
  15132. case ma_backend_aaudio: return MA_FALSE;
  15133. case ma_backend_opensl: return MA_FALSE;
  15134. case ma_backend_webaudio: return MA_FALSE;
  15135. case ma_backend_custom: return MA_FALSE; /* <-- Will depend on the implementation of the backend. */
  15136. case ma_backend_null: return MA_FALSE;
  15137. default: return MA_FALSE;
  15138. }
  15139. }
  15140. #if defined(MA_WIN32)
  15141. /* WASAPI error codes. */
  15142. #define MA_AUDCLNT_E_NOT_INITIALIZED ((HRESULT)0x88890001)
  15143. #define MA_AUDCLNT_E_ALREADY_INITIALIZED ((HRESULT)0x88890002)
  15144. #define MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE ((HRESULT)0x88890003)
  15145. #define MA_AUDCLNT_E_DEVICE_INVALIDATED ((HRESULT)0x88890004)
  15146. #define MA_AUDCLNT_E_NOT_STOPPED ((HRESULT)0x88890005)
  15147. #define MA_AUDCLNT_E_BUFFER_TOO_LARGE ((HRESULT)0x88890006)
  15148. #define MA_AUDCLNT_E_OUT_OF_ORDER ((HRESULT)0x88890007)
  15149. #define MA_AUDCLNT_E_UNSUPPORTED_FORMAT ((HRESULT)0x88890008)
  15150. #define MA_AUDCLNT_E_INVALID_SIZE ((HRESULT)0x88890009)
  15151. #define MA_AUDCLNT_E_DEVICE_IN_USE ((HRESULT)0x8889000A)
  15152. #define MA_AUDCLNT_E_BUFFER_OPERATION_PENDING ((HRESULT)0x8889000B)
  15153. #define MA_AUDCLNT_E_THREAD_NOT_REGISTERED ((HRESULT)0x8889000C)
  15154. #define MA_AUDCLNT_E_NO_SINGLE_PROCESS ((HRESULT)0x8889000D)
  15155. #define MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED ((HRESULT)0x8889000E)
  15156. #define MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED ((HRESULT)0x8889000F)
  15157. #define MA_AUDCLNT_E_SERVICE_NOT_RUNNING ((HRESULT)0x88890010)
  15158. #define MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED ((HRESULT)0x88890011)
  15159. #define MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY ((HRESULT)0x88890012)
  15160. #define MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL ((HRESULT)0x88890013)
  15161. #define MA_AUDCLNT_E_EVENTHANDLE_NOT_SET ((HRESULT)0x88890014)
  15162. #define MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE ((HRESULT)0x88890015)
  15163. #define MA_AUDCLNT_E_BUFFER_SIZE_ERROR ((HRESULT)0x88890016)
  15164. #define MA_AUDCLNT_E_CPUUSAGE_EXCEEDED ((HRESULT)0x88890017)
  15165. #define MA_AUDCLNT_E_BUFFER_ERROR ((HRESULT)0x88890018)
  15166. #define MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED ((HRESULT)0x88890019)
  15167. #define MA_AUDCLNT_E_INVALID_DEVICE_PERIOD ((HRESULT)0x88890020)
  15168. #define MA_AUDCLNT_E_INVALID_STREAM_FLAG ((HRESULT)0x88890021)
  15169. #define MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE ((HRESULT)0x88890022)
  15170. #define MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES ((HRESULT)0x88890023)
  15171. #define MA_AUDCLNT_E_OFFLOAD_MODE_ONLY ((HRESULT)0x88890024)
  15172. #define MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY ((HRESULT)0x88890025)
  15173. #define MA_AUDCLNT_E_RESOURCES_INVALIDATED ((HRESULT)0x88890026)
  15174. #define MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED ((HRESULT)0x88890027)
  15175. #define MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED ((HRESULT)0x88890028)
  15176. #define MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED ((HRESULT)0x88890029)
  15177. #define MA_AUDCLNT_E_HEADTRACKING_ENABLED ((HRESULT)0x88890030)
  15178. #define MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED ((HRESULT)0x88890040)
  15179. #define MA_AUDCLNT_S_BUFFER_EMPTY ((HRESULT)0x08890001)
  15180. #define MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED ((HRESULT)0x08890002)
  15181. #define MA_AUDCLNT_S_POSITION_STALLED ((HRESULT)0x08890003)
  15182. #define MA_DS_OK ((HRESULT)0)
  15183. #define MA_DS_NO_VIRTUALIZATION ((HRESULT)0x0878000A)
  15184. #define MA_DSERR_ALLOCATED ((HRESULT)0x8878000A)
  15185. #define MA_DSERR_CONTROLUNAVAIL ((HRESULT)0x8878001E)
  15186. #define MA_DSERR_INVALIDPARAM ((HRESULT)0x80070057) /*E_INVALIDARG*/
  15187. #define MA_DSERR_INVALIDCALL ((HRESULT)0x88780032)
  15188. #define MA_DSERR_GENERIC ((HRESULT)0x80004005) /*E_FAIL*/
  15189. #define MA_DSERR_PRIOLEVELNEEDED ((HRESULT)0x88780046)
  15190. #define MA_DSERR_OUTOFMEMORY ((HRESULT)0x8007000E) /*E_OUTOFMEMORY*/
  15191. #define MA_DSERR_BADFORMAT ((HRESULT)0x88780064)
  15192. #define MA_DSERR_UNSUPPORTED ((HRESULT)0x80004001) /*E_NOTIMPL*/
  15193. #define MA_DSERR_NODRIVER ((HRESULT)0x88780078)
  15194. #define MA_DSERR_ALREADYINITIALIZED ((HRESULT)0x88780082)
  15195. #define MA_DSERR_NOAGGREGATION ((HRESULT)0x80040110) /*CLASS_E_NOAGGREGATION*/
  15196. #define MA_DSERR_BUFFERLOST ((HRESULT)0x88780096)
  15197. #define MA_DSERR_OTHERAPPHASPRIO ((HRESULT)0x887800A0)
  15198. #define MA_DSERR_UNINITIALIZED ((HRESULT)0x887800AA)
  15199. #define MA_DSERR_NOINTERFACE ((HRESULT)0x80004002) /*E_NOINTERFACE*/
  15200. #define MA_DSERR_ACCESSDENIED ((HRESULT)0x80070005) /*E_ACCESSDENIED*/
  15201. #define MA_DSERR_BUFFERTOOSMALL ((HRESULT)0x887800B4)
  15202. #define MA_DSERR_DS8_REQUIRED ((HRESULT)0x887800BE)
  15203. #define MA_DSERR_SENDLOOP ((HRESULT)0x887800C8)
  15204. #define MA_DSERR_BADSENDBUFFERGUID ((HRESULT)0x887800D2)
  15205. #define MA_DSERR_OBJECTNOTFOUND ((HRESULT)0x88781161)
  15206. #define MA_DSERR_FXUNAVAILABLE ((HRESULT)0x887800DC)
  15207. static ma_result ma_result_from_HRESULT(HRESULT hr)
  15208. {
  15209. switch (hr)
  15210. {
  15211. case NOERROR: return MA_SUCCESS;
  15212. /*case S_OK: return MA_SUCCESS;*/
  15213. case E_POINTER: return MA_INVALID_ARGS;
  15214. case E_UNEXPECTED: return MA_ERROR;
  15215. case E_NOTIMPL: return MA_NOT_IMPLEMENTED;
  15216. case E_OUTOFMEMORY: return MA_OUT_OF_MEMORY;
  15217. case E_INVALIDARG: return MA_INVALID_ARGS;
  15218. case E_NOINTERFACE: return MA_API_NOT_FOUND;
  15219. case E_HANDLE: return MA_INVALID_ARGS;
  15220. case E_ABORT: return MA_ERROR;
  15221. case E_FAIL: return MA_ERROR;
  15222. case E_ACCESSDENIED: return MA_ACCESS_DENIED;
  15223. /* WASAPI */
  15224. case MA_AUDCLNT_E_NOT_INITIALIZED: return MA_DEVICE_NOT_INITIALIZED;
  15225. case MA_AUDCLNT_E_ALREADY_INITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED;
  15226. case MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE: return MA_INVALID_ARGS;
  15227. case MA_AUDCLNT_E_DEVICE_INVALIDATED: return MA_UNAVAILABLE;
  15228. case MA_AUDCLNT_E_NOT_STOPPED: return MA_DEVICE_NOT_STOPPED;
  15229. case MA_AUDCLNT_E_BUFFER_TOO_LARGE: return MA_TOO_BIG;
  15230. case MA_AUDCLNT_E_OUT_OF_ORDER: return MA_INVALID_OPERATION;
  15231. case MA_AUDCLNT_E_UNSUPPORTED_FORMAT: return MA_FORMAT_NOT_SUPPORTED;
  15232. case MA_AUDCLNT_E_INVALID_SIZE: return MA_INVALID_ARGS;
  15233. case MA_AUDCLNT_E_DEVICE_IN_USE: return MA_BUSY;
  15234. case MA_AUDCLNT_E_BUFFER_OPERATION_PENDING: return MA_INVALID_OPERATION;
  15235. case MA_AUDCLNT_E_THREAD_NOT_REGISTERED: return MA_DOES_NOT_EXIST;
  15236. case MA_AUDCLNT_E_NO_SINGLE_PROCESS: return MA_INVALID_OPERATION;
  15237. case MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: return MA_SHARE_MODE_NOT_SUPPORTED;
  15238. case MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED: return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  15239. case MA_AUDCLNT_E_SERVICE_NOT_RUNNING: return MA_NOT_CONNECTED;
  15240. case MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: return MA_INVALID_ARGS;
  15241. case MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY: return MA_SHARE_MODE_NOT_SUPPORTED;
  15242. case MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: return MA_INVALID_ARGS;
  15243. case MA_AUDCLNT_E_EVENTHANDLE_NOT_SET: return MA_INVALID_ARGS;
  15244. case MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE: return MA_INVALID_ARGS;
  15245. case MA_AUDCLNT_E_BUFFER_SIZE_ERROR: return MA_INVALID_ARGS;
  15246. case MA_AUDCLNT_E_CPUUSAGE_EXCEEDED: return MA_ERROR;
  15247. case MA_AUDCLNT_E_BUFFER_ERROR: return MA_ERROR;
  15248. case MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: return MA_INVALID_ARGS;
  15249. case MA_AUDCLNT_E_INVALID_DEVICE_PERIOD: return MA_INVALID_ARGS;
  15250. case MA_AUDCLNT_E_INVALID_STREAM_FLAG: return MA_INVALID_ARGS;
  15251. case MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: return MA_INVALID_OPERATION;
  15252. case MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: return MA_OUT_OF_MEMORY;
  15253. case MA_AUDCLNT_E_OFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION;
  15254. case MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION;
  15255. case MA_AUDCLNT_E_RESOURCES_INVALIDATED: return MA_INVALID_DATA;
  15256. case MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED: return MA_INVALID_OPERATION;
  15257. case MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED: return MA_INVALID_OPERATION;
  15258. case MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED: return MA_INVALID_OPERATION;
  15259. case MA_AUDCLNT_E_HEADTRACKING_ENABLED: return MA_INVALID_OPERATION;
  15260. case MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED: return MA_INVALID_OPERATION;
  15261. case MA_AUDCLNT_S_BUFFER_EMPTY: return MA_NO_SPACE;
  15262. case MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED: return MA_ALREADY_EXISTS;
  15263. case MA_AUDCLNT_S_POSITION_STALLED: return MA_ERROR;
  15264. /* DirectSound */
  15265. /*case MA_DS_OK: return MA_SUCCESS;*/ /* S_OK */
  15266. case MA_DS_NO_VIRTUALIZATION: return MA_SUCCESS;
  15267. case MA_DSERR_ALLOCATED: return MA_ALREADY_IN_USE;
  15268. case MA_DSERR_CONTROLUNAVAIL: return MA_INVALID_OPERATION;
  15269. /*case MA_DSERR_INVALIDPARAM: return MA_INVALID_ARGS;*/ /* E_INVALIDARG */
  15270. case MA_DSERR_INVALIDCALL: return MA_INVALID_OPERATION;
  15271. /*case MA_DSERR_GENERIC: return MA_ERROR;*/ /* E_FAIL */
  15272. case MA_DSERR_PRIOLEVELNEEDED: return MA_INVALID_OPERATION;
  15273. /*case MA_DSERR_OUTOFMEMORY: return MA_OUT_OF_MEMORY;*/ /* E_OUTOFMEMORY */
  15274. case MA_DSERR_BADFORMAT: return MA_FORMAT_NOT_SUPPORTED;
  15275. /*case MA_DSERR_UNSUPPORTED: return MA_NOT_IMPLEMENTED;*/ /* E_NOTIMPL */
  15276. case MA_DSERR_NODRIVER: return MA_FAILED_TO_INIT_BACKEND;
  15277. case MA_DSERR_ALREADYINITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED;
  15278. case MA_DSERR_NOAGGREGATION: return MA_ERROR;
  15279. case MA_DSERR_BUFFERLOST: return MA_UNAVAILABLE;
  15280. case MA_DSERR_OTHERAPPHASPRIO: return MA_ACCESS_DENIED;
  15281. case MA_DSERR_UNINITIALIZED: return MA_DEVICE_NOT_INITIALIZED;
  15282. /*case MA_DSERR_NOINTERFACE: return MA_API_NOT_FOUND;*/ /* E_NOINTERFACE */
  15283. /*case MA_DSERR_ACCESSDENIED: return MA_ACCESS_DENIED;*/ /* E_ACCESSDENIED */
  15284. case MA_DSERR_BUFFERTOOSMALL: return MA_NO_SPACE;
  15285. case MA_DSERR_DS8_REQUIRED: return MA_INVALID_OPERATION;
  15286. case MA_DSERR_SENDLOOP: return MA_DEADLOCK;
  15287. case MA_DSERR_BADSENDBUFFERGUID: return MA_INVALID_ARGS;
  15288. case MA_DSERR_OBJECTNOTFOUND: return MA_NO_DEVICE;
  15289. case MA_DSERR_FXUNAVAILABLE: return MA_UNAVAILABLE;
  15290. default: return MA_ERROR;
  15291. }
  15292. }
  15293. /* PROPVARIANT */
  15294. #define MA_VT_LPWSTR 31
  15295. #define MA_VT_BLOB 65
  15296. #if defined(_MSC_VER) && !defined(__clang__)
  15297. #pragma warning(push)
  15298. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  15299. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  15300. #pragma GCC diagnostic push
  15301. #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  15302. #if defined(__clang__)
  15303. #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
  15304. #endif
  15305. #endif
  15306. typedef struct
  15307. {
  15308. WORD vt;
  15309. WORD wReserved1;
  15310. WORD wReserved2;
  15311. WORD wReserved3;
  15312. union
  15313. {
  15314. struct
  15315. {
  15316. ULONG cbSize;
  15317. BYTE* pBlobData;
  15318. } blob;
  15319. WCHAR* pwszVal;
  15320. char pad[16]; /* Just to ensure the size of the struct matches the official version. */
  15321. };
  15322. } MA_PROPVARIANT;
  15323. #if defined(_MSC_VER) && !defined(__clang__)
  15324. #pragma warning(pop)
  15325. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  15326. #pragma GCC diagnostic pop
  15327. #endif
  15328. typedef HRESULT (WINAPI * MA_PFN_CoInitialize)(void* pvReserved);
  15329. typedef HRESULT (WINAPI * MA_PFN_CoInitializeEx)(void* pvReserved, DWORD dwCoInit);
  15330. typedef void (WINAPI * MA_PFN_CoUninitialize)(void);
  15331. typedef HRESULT (WINAPI * MA_PFN_CoCreateInstance)(const IID* rclsid, void* pUnkOuter, DWORD dwClsContext, const IID* riid, void* ppv);
  15332. typedef void (WINAPI * MA_PFN_CoTaskMemFree)(void* pv);
  15333. typedef HRESULT (WINAPI * MA_PFN_PropVariantClear)(MA_PROPVARIANT *pvar);
  15334. typedef int (WINAPI * MA_PFN_StringFromGUID2)(const GUID* const rguid, WCHAR* lpsz, int cchMax);
  15335. typedef HWND (WINAPI * MA_PFN_GetForegroundWindow)(void);
  15336. typedef HWND (WINAPI * MA_PFN_GetDesktopWindow)(void);
  15337. #if defined(MA_WIN32_DESKTOP)
  15338. /* Microsoft documents these APIs as returning LSTATUS, but the Win32 API shipping with some compilers do not define it. It's just a LONG. */
  15339. typedef LONG (WINAPI * MA_PFN_RegOpenKeyExA)(HKEY hKey, const char* lpSubKey, DWORD ulOptions, DWORD samDesired, HKEY* phkResult);
  15340. typedef LONG (WINAPI * MA_PFN_RegCloseKey)(HKEY hKey);
  15341. typedef LONG (WINAPI * MA_PFN_RegQueryValueExA)(HKEY hKey, const char* lpValueName, DWORD* lpReserved, DWORD* lpType, BYTE* lpData, DWORD* lpcbData);
  15342. #endif /* MA_WIN32_DESKTOP */
  15343. MA_API size_t ma_strlen_WCHAR(const WCHAR* str)
  15344. {
  15345. size_t len = 0;
  15346. while (str[len] != '\0') {
  15347. len += 1;
  15348. }
  15349. return len;
  15350. }
  15351. MA_API int ma_strcmp_WCHAR(const WCHAR *s1, const WCHAR *s2)
  15352. {
  15353. while (*s1 != '\0' && *s1 == *s2) {
  15354. s1 += 1;
  15355. s2 += 1;
  15356. }
  15357. return *s1 - *s2;
  15358. }
  15359. MA_API int ma_strcpy_s_WCHAR(WCHAR* dst, size_t dstCap, const WCHAR* src)
  15360. {
  15361. size_t i;
  15362. if (dst == 0) {
  15363. return 22;
  15364. }
  15365. if (dstCap == 0) {
  15366. return 34;
  15367. }
  15368. if (src == 0) {
  15369. dst[0] = '\0';
  15370. return 22;
  15371. }
  15372. for (i = 0; i < dstCap && src[i] != '\0'; ++i) {
  15373. dst[i] = src[i];
  15374. }
  15375. if (i < dstCap) {
  15376. dst[i] = '\0';
  15377. return 0;
  15378. }
  15379. dst[0] = '\0';
  15380. return 34;
  15381. }
  15382. #endif /* MA_WIN32 */
  15383. #define MA_DEFAULT_PLAYBACK_DEVICE_NAME "Default Playback Device"
  15384. #define MA_DEFAULT_CAPTURE_DEVICE_NAME "Default Capture Device"
  15385. /*******************************************************************************
  15386. Timing
  15387. *******************************************************************************/
  15388. #if defined(MA_WIN32) && !defined(MA_POSIX)
  15389. static LARGE_INTEGER g_ma_TimerFrequency; /* <-- Initialized to zero since it's static. */
  15390. void ma_timer_init(ma_timer* pTimer)
  15391. {
  15392. LARGE_INTEGER counter;
  15393. if (g_ma_TimerFrequency.QuadPart == 0) {
  15394. QueryPerformanceFrequency(&g_ma_TimerFrequency);
  15395. }
  15396. QueryPerformanceCounter(&counter);
  15397. pTimer->counter = counter.QuadPart;
  15398. }
  15399. double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15400. {
  15401. LARGE_INTEGER counter;
  15402. if (!QueryPerformanceCounter(&counter)) {
  15403. return 0;
  15404. }
  15405. return (double)(counter.QuadPart - pTimer->counter) / g_ma_TimerFrequency.QuadPart;
  15406. }
  15407. #elif defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
  15408. static ma_uint64 g_ma_TimerFrequency = 0;
  15409. static void ma_timer_init(ma_timer* pTimer)
  15410. {
  15411. mach_timebase_info_data_t baseTime;
  15412. mach_timebase_info(&baseTime);
  15413. g_ma_TimerFrequency = (baseTime.denom * 1e9) / baseTime.numer;
  15414. pTimer->counter = mach_absolute_time();
  15415. }
  15416. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15417. {
  15418. ma_uint64 newTimeCounter = mach_absolute_time();
  15419. ma_uint64 oldTimeCounter = pTimer->counter;
  15420. return (newTimeCounter - oldTimeCounter) / g_ma_TimerFrequency;
  15421. }
  15422. #elif defined(MA_EMSCRIPTEN)
  15423. static MA_INLINE void ma_timer_init(ma_timer* pTimer)
  15424. {
  15425. pTimer->counterD = emscripten_get_now();
  15426. }
  15427. static MA_INLINE double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15428. {
  15429. return (emscripten_get_now() - pTimer->counterD) / 1000; /* Emscripten is in milliseconds. */
  15430. }
  15431. #else
  15432. #if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L
  15433. #if defined(CLOCK_MONOTONIC)
  15434. #define MA_CLOCK_ID CLOCK_MONOTONIC
  15435. #else
  15436. #define MA_CLOCK_ID CLOCK_REALTIME
  15437. #endif
  15438. static void ma_timer_init(ma_timer* pTimer)
  15439. {
  15440. struct timespec newTime;
  15441. clock_gettime(MA_CLOCK_ID, &newTime);
  15442. pTimer->counter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec;
  15443. }
  15444. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15445. {
  15446. ma_uint64 newTimeCounter;
  15447. ma_uint64 oldTimeCounter;
  15448. struct timespec newTime;
  15449. clock_gettime(MA_CLOCK_ID, &newTime);
  15450. newTimeCounter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec;
  15451. oldTimeCounter = pTimer->counter;
  15452. return (newTimeCounter - oldTimeCounter) / 1000000000.0;
  15453. }
  15454. #else
  15455. static void ma_timer_init(ma_timer* pTimer)
  15456. {
  15457. struct timeval newTime;
  15458. gettimeofday(&newTime, NULL);
  15459. pTimer->counter = (newTime.tv_sec * 1000000) + newTime.tv_usec;
  15460. }
  15461. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15462. {
  15463. ma_uint64 newTimeCounter;
  15464. ma_uint64 oldTimeCounter;
  15465. struct timeval newTime;
  15466. gettimeofday(&newTime, NULL);
  15467. newTimeCounter = (newTime.tv_sec * 1000000) + newTime.tv_usec;
  15468. oldTimeCounter = pTimer->counter;
  15469. return (newTimeCounter - oldTimeCounter) / 1000000.0;
  15470. }
  15471. #endif
  15472. #endif
  15473. /*******************************************************************************
  15474. Dynamic Linking
  15475. *******************************************************************************/
  15476. MA_API ma_handle ma_dlopen(ma_context* pContext, const char* filename)
  15477. {
  15478. #ifndef MA_NO_RUNTIME_LINKING
  15479. ma_handle handle;
  15480. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Loading library: %s\n", filename);
  15481. #ifdef _WIN32
  15482. /* From MSDN: Desktop applications cannot use LoadPackagedLibrary; if a desktop application calls this function it fails with APPMODEL_ERROR_NO_PACKAGE.*/
  15483. #if !defined(WINAPI_FAMILY) || (defined(WINAPI_FAMILY) && (defined(WINAPI_FAMILY_DESKTOP_APP) && WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
  15484. handle = (ma_handle)LoadLibraryA(filename);
  15485. #else
  15486. /* *sigh* It appears there is no ANSI version of LoadPackagedLibrary()... */
  15487. WCHAR filenameW[4096];
  15488. if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, sizeof(filenameW)) == 0) {
  15489. handle = NULL;
  15490. } else {
  15491. handle = (ma_handle)LoadPackagedLibrary(filenameW, 0);
  15492. }
  15493. #endif
  15494. #else
  15495. handle = (ma_handle)dlopen(filename, RTLD_NOW);
  15496. #endif
  15497. /*
  15498. I'm not considering failure to load a library an error nor a warning because seamlessly falling through to a lower-priority
  15499. backend is a deliberate design choice. Instead I'm logging it as an informational message.
  15500. */
  15501. if (handle == NULL) {
  15502. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "Failed to load library: %s\n", filename);
  15503. }
  15504. (void)pContext; /* It's possible for pContext to be unused. */
  15505. return handle;
  15506. #else
  15507. /* Runtime linking is disabled. */
  15508. (void)pContext;
  15509. (void)filename;
  15510. return NULL;
  15511. #endif
  15512. }
  15513. MA_API void ma_dlclose(ma_context* pContext, ma_handle handle)
  15514. {
  15515. #ifndef MA_NO_RUNTIME_LINKING
  15516. #ifdef _WIN32
  15517. FreeLibrary((HMODULE)handle);
  15518. #else
  15519. dlclose((void*)handle);
  15520. #endif
  15521. (void)pContext;
  15522. #else
  15523. /* Runtime linking is disabled. */
  15524. (void)pContext;
  15525. (void)handle;
  15526. #endif
  15527. }
  15528. MA_API ma_proc ma_dlsym(ma_context* pContext, ma_handle handle, const char* symbol)
  15529. {
  15530. #ifndef MA_NO_RUNTIME_LINKING
  15531. ma_proc proc;
  15532. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Loading symbol: %s\n", symbol);
  15533. #ifdef _WIN32
  15534. proc = (ma_proc)GetProcAddress((HMODULE)handle, symbol);
  15535. #else
  15536. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  15537. #pragma GCC diagnostic push
  15538. #pragma GCC diagnostic ignored "-Wpedantic"
  15539. #endif
  15540. proc = (ma_proc)dlsym((void*)handle, symbol);
  15541. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  15542. #pragma GCC diagnostic pop
  15543. #endif
  15544. #endif
  15545. if (proc == NULL) {
  15546. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Failed to load symbol: %s\n", symbol);
  15547. }
  15548. (void)pContext; /* It's possible for pContext to be unused. */
  15549. return proc;
  15550. #else
  15551. /* Runtime linking is disabled. */
  15552. (void)pContext;
  15553. (void)handle;
  15554. (void)symbol;
  15555. return NULL;
  15556. #endif
  15557. }
  15558. #if 0
  15559. static ma_uint32 ma_get_closest_standard_sample_rate(ma_uint32 sampleRateIn)
  15560. {
  15561. ma_uint32 closestRate = 0;
  15562. ma_uint32 closestDiff = 0xFFFFFFFF;
  15563. size_t iStandardRate;
  15564. for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) {
  15565. ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate];
  15566. ma_uint32 diff;
  15567. if (sampleRateIn > standardRate) {
  15568. diff = sampleRateIn - standardRate;
  15569. } else {
  15570. diff = standardRate - sampleRateIn;
  15571. }
  15572. if (diff == 0) {
  15573. return standardRate; /* The input sample rate is a standard rate. */
  15574. }
  15575. if (closestDiff > diff) {
  15576. closestDiff = diff;
  15577. closestRate = standardRate;
  15578. }
  15579. }
  15580. return closestRate;
  15581. }
  15582. #endif
  15583. static MA_INLINE unsigned int ma_device_disable_denormals(ma_device* pDevice)
  15584. {
  15585. MA_ASSERT(pDevice != NULL);
  15586. if (!pDevice->noDisableDenormals) {
  15587. return ma_disable_denormals();
  15588. } else {
  15589. return 0;
  15590. }
  15591. }
  15592. static MA_INLINE void ma_device_restore_denormals(ma_device* pDevice, unsigned int prevState)
  15593. {
  15594. MA_ASSERT(pDevice != NULL);
  15595. if (!pDevice->noDisableDenormals) {
  15596. ma_restore_denormals(prevState);
  15597. } else {
  15598. /* Do nothing. */
  15599. (void)prevState;
  15600. }
  15601. }
  15602. static ma_device_notification ma_device_notification_init(ma_device* pDevice, ma_device_notification_type type)
  15603. {
  15604. ma_device_notification notification;
  15605. MA_ZERO_OBJECT(&notification);
  15606. notification.pDevice = pDevice;
  15607. notification.type = type;
  15608. return notification;
  15609. }
  15610. static void ma_device__on_notification(ma_device_notification notification)
  15611. {
  15612. MA_ASSERT(notification.pDevice != NULL);
  15613. if (notification.pDevice->onNotification != NULL) {
  15614. notification.pDevice->onNotification(&notification);
  15615. }
  15616. /* TEMP FOR COMPATIBILITY: If it's a stopped notification, fire the onStop callback as well. This is only for backwards compatibility and will be removed. */
  15617. if (notification.pDevice->onStop != NULL && notification.type == ma_device_notification_type_stopped) {
  15618. notification.pDevice->onStop(notification.pDevice);
  15619. }
  15620. }
  15621. void ma_device__on_notification_started(ma_device* pDevice)
  15622. {
  15623. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_started));
  15624. }
  15625. void ma_device__on_notification_stopped(ma_device* pDevice)
  15626. {
  15627. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_stopped));
  15628. }
  15629. void ma_device__on_notification_rerouted(ma_device* pDevice)
  15630. {
  15631. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_rerouted));
  15632. }
  15633. void ma_device__on_notification_interruption_began(ma_device* pDevice)
  15634. {
  15635. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_interruption_began));
  15636. }
  15637. void ma_device__on_notification_interruption_ended(ma_device* pDevice)
  15638. {
  15639. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_interruption_ended));
  15640. }
  15641. static void ma_device__on_data_inner(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  15642. {
  15643. MA_ASSERT(pDevice != NULL);
  15644. MA_ASSERT(pDevice->onData != NULL);
  15645. if (!pDevice->noPreSilencedOutputBuffer && pFramesOut != NULL) {
  15646. ma_silence_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels);
  15647. }
  15648. pDevice->onData(pDevice, pFramesOut, pFramesIn, frameCount);
  15649. }
  15650. static void ma_device__on_data(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  15651. {
  15652. MA_ASSERT(pDevice != NULL);
  15653. /* Don't read more data from the client if we're in the process of stopping. */
  15654. if (ma_device_get_state(pDevice) == ma_device_state_stopping) {
  15655. return;
  15656. }
  15657. if (pDevice->noFixedSizedCallback) {
  15658. /* Fast path. Not using a fixed sized callback. Process directly from the specified buffers. */
  15659. ma_device__on_data_inner(pDevice, pFramesOut, pFramesIn, frameCount);
  15660. } else {
  15661. /* Slow path. Using a fixed sized callback. Need to use the intermediary buffer. */
  15662. ma_uint32 totalFramesProcessed = 0;
  15663. while (totalFramesProcessed < frameCount) {
  15664. ma_uint32 totalFramesRemaining = frameCount - totalFramesProcessed;
  15665. ma_uint32 framesToProcessThisIteration = 0;
  15666. if (pFramesIn != NULL) {
  15667. /* Capturing. Write to the intermediary buffer. If there's no room, fire the callback to empty it. */
  15668. if (pDevice->capture.intermediaryBufferLen < pDevice->capture.intermediaryBufferCap) {
  15669. /* There's some room left in the intermediary buffer. Write to it without firing the callback. */
  15670. framesToProcessThisIteration = totalFramesRemaining;
  15671. if (framesToProcessThisIteration > pDevice->capture.intermediaryBufferCap - pDevice->capture.intermediaryBufferLen) {
  15672. framesToProcessThisIteration = pDevice->capture.intermediaryBufferCap - pDevice->capture.intermediaryBufferLen;
  15673. }
  15674. ma_copy_pcm_frames(
  15675. ma_offset_pcm_frames_ptr(pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferLen, pDevice->capture.format, pDevice->capture.channels),
  15676. ma_offset_pcm_frames_const_ptr(pFramesIn, totalFramesProcessed, pDevice->capture.format, pDevice->capture.channels),
  15677. framesToProcessThisIteration,
  15678. pDevice->capture.format, pDevice->capture.channels);
  15679. pDevice->capture.intermediaryBufferLen += framesToProcessThisIteration;
  15680. }
  15681. if (pDevice->capture.intermediaryBufferLen == pDevice->capture.intermediaryBufferCap) {
  15682. /* No room left in the intermediary buffer. Fire the data callback. */
  15683. if (pDevice->type == ma_device_type_duplex) {
  15684. /* We'll do the duplex data callback later after we've processed the playback data. */
  15685. } else {
  15686. ma_device__on_data_inner(pDevice, NULL, pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap);
  15687. /* The intermediary buffer has just been drained. */
  15688. pDevice->capture.intermediaryBufferLen = 0;
  15689. }
  15690. }
  15691. }
  15692. if (pFramesOut != NULL) {
  15693. /* Playing back. Read from the intermediary buffer. If there's nothing in it, fire the callback to fill it. */
  15694. if (pDevice->playback.intermediaryBufferLen > 0) {
  15695. /* There's some content in the intermediary buffer. Read from that without firing the callback. */
  15696. if (pDevice->type == ma_device_type_duplex) {
  15697. /* The frames processed this iteration for a duplex device will always be based on the capture side. Leave it unmodified. */
  15698. } else {
  15699. framesToProcessThisIteration = totalFramesRemaining;
  15700. if (framesToProcessThisIteration > pDevice->playback.intermediaryBufferLen) {
  15701. framesToProcessThisIteration = pDevice->playback.intermediaryBufferLen;
  15702. }
  15703. }
  15704. ma_copy_pcm_frames(
  15705. ma_offset_pcm_frames_ptr(pFramesOut, totalFramesProcessed, pDevice->playback.format, pDevice->playback.channels),
  15706. ma_offset_pcm_frames_ptr(pDevice->playback.pIntermediaryBuffer, pDevice->playback.intermediaryBufferCap - pDevice->playback.intermediaryBufferLen, pDevice->playback.format, pDevice->playback.channels),
  15707. framesToProcessThisIteration,
  15708. pDevice->playback.format, pDevice->playback.channels);
  15709. pDevice->playback.intermediaryBufferLen -= framesToProcessThisIteration;
  15710. }
  15711. if (pDevice->playback.intermediaryBufferLen == 0) {
  15712. /* There's nothing in the intermediary buffer. Fire the data callback to fill it. */
  15713. if (pDevice->type == ma_device_type_duplex) {
  15714. /* In duplex mode, the data callback will be fired later. Nothing to do here. */
  15715. } else {
  15716. ma_device__on_data_inner(pDevice, pDevice->playback.pIntermediaryBuffer, NULL, pDevice->playback.intermediaryBufferCap);
  15717. /* The intermediary buffer has just been filled. */
  15718. pDevice->playback.intermediaryBufferLen = pDevice->playback.intermediaryBufferCap;
  15719. }
  15720. }
  15721. }
  15722. /* If we're in duplex mode we might need to do a refill of the data. */
  15723. if (pDevice->type == ma_device_type_duplex) {
  15724. if (pDevice->capture.intermediaryBufferLen == pDevice->capture.intermediaryBufferCap) {
  15725. ma_device__on_data_inner(pDevice, pDevice->playback.pIntermediaryBuffer, pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap);
  15726. pDevice->playback.intermediaryBufferLen = pDevice->playback.intermediaryBufferCap; /* The playback buffer will have just been filled. */
  15727. pDevice->capture.intermediaryBufferLen = 0; /* The intermediary buffer has just been drained. */
  15728. }
  15729. }
  15730. /* Make sure this is only incremented once in the duplex case. */
  15731. totalFramesProcessed += framesToProcessThisIteration;
  15732. }
  15733. }
  15734. }
  15735. static void ma_device__handle_data_callback(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  15736. {
  15737. float masterVolumeFactor;
  15738. ma_device_get_master_volume(pDevice, &masterVolumeFactor); /* Use ma_device_get_master_volume() to ensure the volume is loaded atomically. */
  15739. if (pDevice->onData) {
  15740. unsigned int prevDenormalState = ma_device_disable_denormals(pDevice);
  15741. {
  15742. /* Volume control of input makes things a bit awkward because the input buffer is read-only. We'll need to use a temp buffer and loop in this case. */
  15743. if (pFramesIn != NULL && masterVolumeFactor < 1) {
  15744. ma_uint8 tempFramesIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15745. ma_uint32 bpfCapture = ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15746. ma_uint32 bpfPlayback = ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  15747. ma_uint32 totalFramesProcessed = 0;
  15748. while (totalFramesProcessed < frameCount) {
  15749. ma_uint32 framesToProcessThisIteration = frameCount - totalFramesProcessed;
  15750. if (framesToProcessThisIteration > sizeof(tempFramesIn)/bpfCapture) {
  15751. framesToProcessThisIteration = sizeof(tempFramesIn)/bpfCapture;
  15752. }
  15753. ma_copy_and_apply_volume_factor_pcm_frames(tempFramesIn, ma_offset_ptr(pFramesIn, totalFramesProcessed*bpfCapture), framesToProcessThisIteration, pDevice->capture.format, pDevice->capture.channels, masterVolumeFactor);
  15754. ma_device__on_data(pDevice, ma_offset_ptr(pFramesOut, totalFramesProcessed*bpfPlayback), tempFramesIn, framesToProcessThisIteration);
  15755. totalFramesProcessed += framesToProcessThisIteration;
  15756. }
  15757. } else {
  15758. ma_device__on_data(pDevice, pFramesOut, pFramesIn, frameCount);
  15759. }
  15760. /* Volume control and clipping for playback devices. */
  15761. if (pFramesOut != NULL) {
  15762. if (masterVolumeFactor < 1) {
  15763. if (pFramesIn == NULL) { /* <-- In full-duplex situations, the volume will have been applied to the input samples before the data callback. Applying it again post-callback will incorrectly compound it. */
  15764. ma_apply_volume_factor_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels, masterVolumeFactor);
  15765. }
  15766. }
  15767. if (!pDevice->noClip && pDevice->playback.format == ma_format_f32) {
  15768. ma_clip_samples_f32((float*)pFramesOut, (const float*)pFramesOut, frameCount * pDevice->playback.channels); /* Intentionally specifying the same pointer for both input and output for in-place processing. */
  15769. }
  15770. }
  15771. }
  15772. ma_device_restore_denormals(pDevice, prevDenormalState);
  15773. }
  15774. }
  15775. /* A helper function for reading sample data from the client. */
  15776. static void ma_device__read_frames_from_client(ma_device* pDevice, ma_uint32 frameCount, void* pFramesOut)
  15777. {
  15778. MA_ASSERT(pDevice != NULL);
  15779. MA_ASSERT(frameCount > 0);
  15780. MA_ASSERT(pFramesOut != NULL);
  15781. if (pDevice->playback.converter.isPassthrough) {
  15782. ma_device__handle_data_callback(pDevice, pFramesOut, NULL, frameCount);
  15783. } else {
  15784. ma_result result;
  15785. ma_uint64 totalFramesReadOut;
  15786. void* pRunningFramesOut;
  15787. totalFramesReadOut = 0;
  15788. pRunningFramesOut = pFramesOut;
  15789. /*
  15790. We run slightly different logic depending on whether or not we're using a heap-allocated
  15791. buffer for caching input data. This will be the case if the data converter does not have
  15792. the ability to retrieve the required input frame count for a given output frame count.
  15793. */
  15794. if (pDevice->playback.pInputCache != NULL) {
  15795. while (totalFramesReadOut < frameCount) {
  15796. ma_uint64 framesToReadThisIterationIn;
  15797. ma_uint64 framesToReadThisIterationOut;
  15798. /* If there's any data available in the cache, that needs to get processed first. */
  15799. if (pDevice->playback.inputCacheRemaining > 0) {
  15800. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  15801. framesToReadThisIterationIn = framesToReadThisIterationOut;
  15802. if (framesToReadThisIterationIn > pDevice->playback.inputCacheRemaining) {
  15803. framesToReadThisIterationIn = pDevice->playback.inputCacheRemaining;
  15804. }
  15805. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, ma_offset_pcm_frames_ptr(pDevice->playback.pInputCache, pDevice->playback.inputCacheConsumed, pDevice->playback.format, pDevice->playback.channels), &framesToReadThisIterationIn, pRunningFramesOut, &framesToReadThisIterationOut);
  15806. if (result != MA_SUCCESS) {
  15807. break;
  15808. }
  15809. pDevice->playback.inputCacheConsumed += framesToReadThisIterationIn;
  15810. pDevice->playback.inputCacheRemaining -= framesToReadThisIterationIn;
  15811. totalFramesReadOut += framesToReadThisIterationOut;
  15812. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesToReadThisIterationOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  15813. if (framesToReadThisIterationIn == 0 && framesToReadThisIterationOut == 0) {
  15814. break; /* We're done. */
  15815. }
  15816. }
  15817. /* Getting here means there's no data in the cache and we need to fill it up with data from the client. */
  15818. if (pDevice->playback.inputCacheRemaining == 0) {
  15819. ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, NULL, (ma_uint32)pDevice->playback.inputCacheCap);
  15820. pDevice->playback.inputCacheConsumed = 0;
  15821. pDevice->playback.inputCacheRemaining = pDevice->playback.inputCacheCap;
  15822. }
  15823. }
  15824. } else {
  15825. while (totalFramesReadOut < frameCount) {
  15826. ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In client format. */
  15827. ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  15828. ma_uint64 framesToReadThisIterationIn;
  15829. ma_uint64 framesReadThisIterationIn;
  15830. ma_uint64 framesToReadThisIterationOut;
  15831. ma_uint64 framesReadThisIterationOut;
  15832. ma_uint64 requiredInputFrameCount;
  15833. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  15834. framesToReadThisIterationIn = framesToReadThisIterationOut;
  15835. if (framesToReadThisIterationIn > intermediaryBufferCap) {
  15836. framesToReadThisIterationIn = intermediaryBufferCap;
  15837. }
  15838. ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, framesToReadThisIterationOut, &requiredInputFrameCount);
  15839. if (framesToReadThisIterationIn > requiredInputFrameCount) {
  15840. framesToReadThisIterationIn = requiredInputFrameCount;
  15841. }
  15842. if (framesToReadThisIterationIn > 0) {
  15843. ma_device__handle_data_callback(pDevice, pIntermediaryBuffer, NULL, (ma_uint32)framesToReadThisIterationIn);
  15844. }
  15845. /*
  15846. At this point we have our decoded data in input format and now we need to convert to output format. Note that even if we didn't read any
  15847. input frames, we still want to try processing frames because there may some output frames generated from cached input data.
  15848. */
  15849. framesReadThisIterationIn = framesToReadThisIterationIn;
  15850. framesReadThisIterationOut = framesToReadThisIterationOut;
  15851. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut);
  15852. if (result != MA_SUCCESS) {
  15853. break;
  15854. }
  15855. totalFramesReadOut += framesReadThisIterationOut;
  15856. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  15857. if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) {
  15858. break; /* We're done. */
  15859. }
  15860. }
  15861. }
  15862. }
  15863. }
  15864. /* A helper for sending sample data to the client. */
  15865. static void ma_device__send_frames_to_client(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat)
  15866. {
  15867. MA_ASSERT(pDevice != NULL);
  15868. MA_ASSERT(frameCountInDeviceFormat > 0);
  15869. MA_ASSERT(pFramesInDeviceFormat != NULL);
  15870. if (pDevice->capture.converter.isPassthrough) {
  15871. ma_device__handle_data_callback(pDevice, NULL, pFramesInDeviceFormat, frameCountInDeviceFormat);
  15872. } else {
  15873. ma_result result;
  15874. ma_uint8 pFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15875. ma_uint64 framesInClientFormatCap = sizeof(pFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15876. ma_uint64 totalDeviceFramesProcessed = 0;
  15877. ma_uint64 totalClientFramesProcessed = 0;
  15878. const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat;
  15879. /* We just keep going until we've exhaused all of our input frames and cannot generate any more output frames. */
  15880. for (;;) {
  15881. ma_uint64 deviceFramesProcessedThisIteration;
  15882. ma_uint64 clientFramesProcessedThisIteration;
  15883. deviceFramesProcessedThisIteration = (frameCountInDeviceFormat - totalDeviceFramesProcessed);
  15884. clientFramesProcessedThisIteration = framesInClientFormatCap;
  15885. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &deviceFramesProcessedThisIteration, pFramesInClientFormat, &clientFramesProcessedThisIteration);
  15886. if (result != MA_SUCCESS) {
  15887. break;
  15888. }
  15889. if (clientFramesProcessedThisIteration > 0) {
  15890. ma_device__handle_data_callback(pDevice, NULL, pFramesInClientFormat, (ma_uint32)clientFramesProcessedThisIteration); /* Safe cast. */
  15891. }
  15892. pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, deviceFramesProcessedThisIteration * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  15893. totalDeviceFramesProcessed += deviceFramesProcessedThisIteration;
  15894. totalClientFramesProcessed += clientFramesProcessedThisIteration;
  15895. /* This is just to silence a warning. I might want to use this variable later so leaving in place for now. */
  15896. (void)totalClientFramesProcessed;
  15897. if (deviceFramesProcessedThisIteration == 0 && clientFramesProcessedThisIteration == 0) {
  15898. break; /* We're done. */
  15899. }
  15900. }
  15901. }
  15902. }
  15903. static ma_result ma_device__handle_duplex_callback_capture(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat, ma_pcm_rb* pRB)
  15904. {
  15905. ma_result result;
  15906. ma_uint32 totalDeviceFramesProcessed = 0;
  15907. const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat;
  15908. MA_ASSERT(pDevice != NULL);
  15909. MA_ASSERT(frameCountInDeviceFormat > 0);
  15910. MA_ASSERT(pFramesInDeviceFormat != NULL);
  15911. MA_ASSERT(pRB != NULL);
  15912. /* Write to the ring buffer. The ring buffer is in the client format which means we need to convert. */
  15913. for (;;) {
  15914. ma_uint32 framesToProcessInDeviceFormat = (frameCountInDeviceFormat - totalDeviceFramesProcessed);
  15915. ma_uint32 framesToProcessInClientFormat = MA_DATA_CONVERTER_STACK_BUFFER_SIZE / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15916. ma_uint64 framesProcessedInDeviceFormat;
  15917. ma_uint64 framesProcessedInClientFormat;
  15918. void* pFramesInClientFormat;
  15919. result = ma_pcm_rb_acquire_write(pRB, &framesToProcessInClientFormat, &pFramesInClientFormat);
  15920. if (result != MA_SUCCESS) {
  15921. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "Failed to acquire capture PCM frames from ring buffer.");
  15922. break;
  15923. }
  15924. if (framesToProcessInClientFormat == 0) {
  15925. if (ma_pcm_rb_pointer_distance(pRB) == (ma_int32)ma_pcm_rb_get_subbuffer_size(pRB)) {
  15926. break; /* Overrun. Not enough room in the ring buffer for input frame. Excess frames are dropped. */
  15927. }
  15928. }
  15929. /* Convert. */
  15930. framesProcessedInDeviceFormat = framesToProcessInDeviceFormat;
  15931. framesProcessedInClientFormat = framesToProcessInClientFormat;
  15932. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &framesProcessedInDeviceFormat, pFramesInClientFormat, &framesProcessedInClientFormat);
  15933. if (result != MA_SUCCESS) {
  15934. break;
  15935. }
  15936. result = ma_pcm_rb_commit_write(pRB, (ma_uint32)framesProcessedInClientFormat); /* Safe cast. */
  15937. if (result != MA_SUCCESS) {
  15938. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "Failed to commit capture PCM frames to ring buffer.");
  15939. break;
  15940. }
  15941. pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, framesProcessedInDeviceFormat * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  15942. totalDeviceFramesProcessed += (ma_uint32)framesProcessedInDeviceFormat; /* Safe cast. */
  15943. /* We're done when we're unable to process any client nor device frames. */
  15944. if (framesProcessedInClientFormat == 0 && framesProcessedInDeviceFormat == 0) {
  15945. break; /* Done. */
  15946. }
  15947. }
  15948. return MA_SUCCESS;
  15949. }
  15950. static ma_result ma_device__handle_duplex_callback_playback(ma_device* pDevice, ma_uint32 frameCount, void* pFramesInInternalFormat, ma_pcm_rb* pRB)
  15951. {
  15952. ma_result result;
  15953. ma_uint8 silentInputFrames[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15954. ma_uint32 totalFramesReadOut = 0;
  15955. MA_ASSERT(pDevice != NULL);
  15956. MA_ASSERT(frameCount > 0);
  15957. MA_ASSERT(pFramesInInternalFormat != NULL);
  15958. MA_ASSERT(pRB != NULL);
  15959. MA_ASSERT(pDevice->playback.pInputCache != NULL);
  15960. /*
  15961. Sitting in the ring buffer should be captured data from the capture callback in external format. If there's not enough data in there for
  15962. the whole frameCount frames we just use silence instead for the input data.
  15963. */
  15964. MA_ZERO_MEMORY(silentInputFrames, sizeof(silentInputFrames));
  15965. while (totalFramesReadOut < frameCount && ma_device_is_started(pDevice)) {
  15966. /*
  15967. We should have a buffer allocated on the heap. Any playback frames still sitting in there
  15968. need to be sent to the internal device before we process any more data from the client.
  15969. */
  15970. if (pDevice->playback.inputCacheRemaining > 0) {
  15971. ma_uint64 framesConvertedIn = pDevice->playback.inputCacheRemaining;
  15972. ma_uint64 framesConvertedOut = (frameCount - totalFramesReadOut);
  15973. ma_data_converter_process_pcm_frames(&pDevice->playback.converter, ma_offset_pcm_frames_ptr(pDevice->playback.pInputCache, pDevice->playback.inputCacheConsumed, pDevice->playback.format, pDevice->playback.channels), &framesConvertedIn, pFramesInInternalFormat, &framesConvertedOut);
  15974. pDevice->playback.inputCacheConsumed += framesConvertedIn;
  15975. pDevice->playback.inputCacheRemaining -= framesConvertedIn;
  15976. totalFramesReadOut += (ma_uint32)framesConvertedOut; /* Safe cast. */
  15977. pFramesInInternalFormat = ma_offset_ptr(pFramesInInternalFormat, framesConvertedOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  15978. }
  15979. /* If there's no more data in the cache we'll need to fill it with some. */
  15980. if (totalFramesReadOut < frameCount && pDevice->playback.inputCacheRemaining == 0) {
  15981. ma_uint32 inputFrameCount;
  15982. void* pInputFrames;
  15983. inputFrameCount = (ma_uint32)pDevice->playback.inputCacheCap;
  15984. result = ma_pcm_rb_acquire_read(pRB, &inputFrameCount, &pInputFrames);
  15985. if (result == MA_SUCCESS) {
  15986. if (inputFrameCount > 0) {
  15987. ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, pInputFrames, inputFrameCount);
  15988. } else {
  15989. if (ma_pcm_rb_pointer_distance(pRB) == 0) {
  15990. break; /* Underrun. */
  15991. }
  15992. }
  15993. } else {
  15994. /* No capture data available. Feed in silence. */
  15995. inputFrameCount = (ma_uint32)ma_min(pDevice->playback.inputCacheCap, sizeof(silentInputFrames) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels));
  15996. ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, silentInputFrames, inputFrameCount);
  15997. }
  15998. pDevice->playback.inputCacheConsumed = 0;
  15999. pDevice->playback.inputCacheRemaining = inputFrameCount;
  16000. result = ma_pcm_rb_commit_read(pRB, inputFrameCount);
  16001. if (result != MA_SUCCESS) {
  16002. return result; /* Should never happen. */
  16003. }
  16004. }
  16005. }
  16006. return MA_SUCCESS;
  16007. }
  16008. /* A helper for changing the state of the device. */
  16009. static MA_INLINE void ma_device__set_state(ma_device* pDevice, ma_device_state newState)
  16010. {
  16011. ma_atomic_device_state_set(&pDevice->state, newState);
  16012. }
  16013. #if defined(MA_WIN32)
  16014. GUID MA_GUID_KSDATAFORMAT_SUBTYPE_PCM = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
  16015. GUID MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
  16016. /*GUID MA_GUID_KSDATAFORMAT_SUBTYPE_ALAW = {0x00000006, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/
  16017. /*GUID MA_GUID_KSDATAFORMAT_SUBTYPE_MULAW = {0x00000007, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/
  16018. #endif
  16019. MA_API ma_uint32 ma_get_format_priority_index(ma_format format) /* Lower = better. */
  16020. {
  16021. ma_uint32 i;
  16022. for (i = 0; i < ma_countof(g_maFormatPriorities); ++i) {
  16023. if (g_maFormatPriorities[i] == format) {
  16024. return i;
  16025. }
  16026. }
  16027. /* Getting here means the format could not be found or is equal to ma_format_unknown. */
  16028. return (ma_uint32)-1;
  16029. }
  16030. static ma_result ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType);
  16031. static ma_bool32 ma_device_descriptor_is_valid(const ma_device_descriptor* pDeviceDescriptor)
  16032. {
  16033. if (pDeviceDescriptor == NULL) {
  16034. return MA_FALSE;
  16035. }
  16036. if (pDeviceDescriptor->format == ma_format_unknown) {
  16037. return MA_FALSE;
  16038. }
  16039. if (pDeviceDescriptor->channels == 0 || pDeviceDescriptor->channels > MA_MAX_CHANNELS) {
  16040. return MA_FALSE;
  16041. }
  16042. if (pDeviceDescriptor->sampleRate == 0) {
  16043. return MA_FALSE;
  16044. }
  16045. return MA_TRUE;
  16046. }
  16047. static ma_result ma_device_audio_thread__default_read_write(ma_device* pDevice)
  16048. {
  16049. ma_result result = MA_SUCCESS;
  16050. ma_bool32 exitLoop = MA_FALSE;
  16051. ma_uint8 capturedDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  16052. ma_uint8 playbackDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  16053. ma_uint32 capturedDeviceDataCapInFrames = 0;
  16054. ma_uint32 playbackDeviceDataCapInFrames = 0;
  16055. MA_ASSERT(pDevice != NULL);
  16056. /* Just some quick validation on the device type and the available callbacks. */
  16057. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  16058. if (pDevice->pContext->callbacks.onDeviceRead == NULL) {
  16059. return MA_NOT_IMPLEMENTED;
  16060. }
  16061. capturedDeviceDataCapInFrames = sizeof(capturedDeviceData) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  16062. }
  16063. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  16064. if (pDevice->pContext->callbacks.onDeviceWrite == NULL) {
  16065. return MA_NOT_IMPLEMENTED;
  16066. }
  16067. playbackDeviceDataCapInFrames = sizeof(playbackDeviceData) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  16068. }
  16069. /* NOTE: The device was started outside of this function, in the worker thread. */
  16070. while (ma_device_get_state(pDevice) == ma_device_state_started && !exitLoop) {
  16071. switch (pDevice->type) {
  16072. case ma_device_type_duplex:
  16073. {
  16074. /* The process is: onDeviceRead() -> convert -> callback -> convert -> onDeviceWrite() */
  16075. ma_uint32 totalCapturedDeviceFramesProcessed = 0;
  16076. ma_uint32 capturedDevicePeriodSizeInFrames = ma_min(pDevice->capture.internalPeriodSizeInFrames, pDevice->playback.internalPeriodSizeInFrames);
  16077. while (totalCapturedDeviceFramesProcessed < capturedDevicePeriodSizeInFrames) {
  16078. ma_uint32 capturedDeviceFramesRemaining;
  16079. ma_uint32 capturedDeviceFramesProcessed;
  16080. ma_uint32 capturedDeviceFramesToProcess;
  16081. ma_uint32 capturedDeviceFramesToTryProcessing = capturedDevicePeriodSizeInFrames - totalCapturedDeviceFramesProcessed;
  16082. if (capturedDeviceFramesToTryProcessing > capturedDeviceDataCapInFrames) {
  16083. capturedDeviceFramesToTryProcessing = capturedDeviceDataCapInFrames;
  16084. }
  16085. result = pDevice->pContext->callbacks.onDeviceRead(pDevice, capturedDeviceData, capturedDeviceFramesToTryProcessing, &capturedDeviceFramesToProcess);
  16086. if (result != MA_SUCCESS) {
  16087. exitLoop = MA_TRUE;
  16088. break;
  16089. }
  16090. capturedDeviceFramesRemaining = capturedDeviceFramesToProcess;
  16091. capturedDeviceFramesProcessed = 0;
  16092. /* At this point we have our captured data in device format and we now need to convert it to client format. */
  16093. for (;;) {
  16094. ma_uint8 capturedClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  16095. ma_uint8 playbackClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  16096. ma_uint32 capturedClientDataCapInFrames = sizeof(capturedClientData) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  16097. ma_uint32 playbackClientDataCapInFrames = sizeof(playbackClientData) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  16098. ma_uint64 capturedClientFramesToProcessThisIteration = ma_min(capturedClientDataCapInFrames, playbackClientDataCapInFrames);
  16099. ma_uint64 capturedDeviceFramesToProcessThisIteration = capturedDeviceFramesRemaining;
  16100. ma_uint8* pRunningCapturedDeviceFrames = ma_offset_ptr(capturedDeviceData, capturedDeviceFramesProcessed * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  16101. /* Convert capture data from device format to client format. */
  16102. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningCapturedDeviceFrames, &capturedDeviceFramesToProcessThisIteration, capturedClientData, &capturedClientFramesToProcessThisIteration);
  16103. if (result != MA_SUCCESS) {
  16104. break;
  16105. }
  16106. /*
  16107. If we weren't able to generate any output frames it must mean we've exhaused all of our input. The only time this would not be the case is if capturedClientData was too small
  16108. which should never be the case when it's of the size MA_DATA_CONVERTER_STACK_BUFFER_SIZE.
  16109. */
  16110. if (capturedClientFramesToProcessThisIteration == 0) {
  16111. break;
  16112. }
  16113. ma_device__handle_data_callback(pDevice, playbackClientData, capturedClientData, (ma_uint32)capturedClientFramesToProcessThisIteration); /* Safe cast .*/
  16114. capturedDeviceFramesProcessed += (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
  16115. capturedDeviceFramesRemaining -= (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
  16116. /* At this point the playbackClientData buffer should be holding data that needs to be written to the device. */
  16117. for (;;) {
  16118. ma_uint64 convertedClientFrameCount = capturedClientFramesToProcessThisIteration;
  16119. ma_uint64 convertedDeviceFrameCount = playbackDeviceDataCapInFrames;
  16120. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, playbackClientData, &convertedClientFrameCount, playbackDeviceData, &convertedDeviceFrameCount);
  16121. if (result != MA_SUCCESS) {
  16122. break;
  16123. }
  16124. result = pDevice->pContext->callbacks.onDeviceWrite(pDevice, playbackDeviceData, (ma_uint32)convertedDeviceFrameCount, NULL); /* Safe cast. */
  16125. if (result != MA_SUCCESS) {
  16126. exitLoop = MA_TRUE;
  16127. break;
  16128. }
  16129. capturedClientFramesToProcessThisIteration -= (ma_uint32)convertedClientFrameCount; /* Safe cast. */
  16130. if (capturedClientFramesToProcessThisIteration == 0) {
  16131. break;
  16132. }
  16133. }
  16134. /* In case an error happened from ma_device_write__null()... */
  16135. if (result != MA_SUCCESS) {
  16136. exitLoop = MA_TRUE;
  16137. break;
  16138. }
  16139. }
  16140. /* Make sure we don't get stuck in the inner loop. */
  16141. if (capturedDeviceFramesProcessed == 0) {
  16142. break;
  16143. }
  16144. totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
  16145. }
  16146. } break;
  16147. case ma_device_type_capture:
  16148. case ma_device_type_loopback:
  16149. {
  16150. ma_uint32 periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames;
  16151. ma_uint32 framesReadThisPeriod = 0;
  16152. while (framesReadThisPeriod < periodSizeInFrames) {
  16153. ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesReadThisPeriod;
  16154. ma_uint32 framesProcessed;
  16155. ma_uint32 framesToReadThisIteration = framesRemainingInPeriod;
  16156. if (framesToReadThisIteration > capturedDeviceDataCapInFrames) {
  16157. framesToReadThisIteration = capturedDeviceDataCapInFrames;
  16158. }
  16159. result = pDevice->pContext->callbacks.onDeviceRead(pDevice, capturedDeviceData, framesToReadThisIteration, &framesProcessed);
  16160. if (result != MA_SUCCESS) {
  16161. exitLoop = MA_TRUE;
  16162. break;
  16163. }
  16164. /* Make sure we don't get stuck in the inner loop. */
  16165. if (framesProcessed == 0) {
  16166. break;
  16167. }
  16168. ma_device__send_frames_to_client(pDevice, framesProcessed, capturedDeviceData);
  16169. framesReadThisPeriod += framesProcessed;
  16170. }
  16171. } break;
  16172. case ma_device_type_playback:
  16173. {
  16174. /* We write in chunks of the period size, but use a stack allocated buffer for the intermediary. */
  16175. ma_uint32 periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames;
  16176. ma_uint32 framesWrittenThisPeriod = 0;
  16177. while (framesWrittenThisPeriod < periodSizeInFrames) {
  16178. ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesWrittenThisPeriod;
  16179. ma_uint32 framesProcessed;
  16180. ma_uint32 framesToWriteThisIteration = framesRemainingInPeriod;
  16181. if (framesToWriteThisIteration > playbackDeviceDataCapInFrames) {
  16182. framesToWriteThisIteration = playbackDeviceDataCapInFrames;
  16183. }
  16184. ma_device__read_frames_from_client(pDevice, framesToWriteThisIteration, playbackDeviceData);
  16185. result = pDevice->pContext->callbacks.onDeviceWrite(pDevice, playbackDeviceData, framesToWriteThisIteration, &framesProcessed);
  16186. if (result != MA_SUCCESS) {
  16187. exitLoop = MA_TRUE;
  16188. break;
  16189. }
  16190. /* Make sure we don't get stuck in the inner loop. */
  16191. if (framesProcessed == 0) {
  16192. break;
  16193. }
  16194. framesWrittenThisPeriod += framesProcessed;
  16195. }
  16196. } break;
  16197. /* Should never get here. */
  16198. default: break;
  16199. }
  16200. }
  16201. return result;
  16202. }
  16203. /*******************************************************************************
  16204. Null Backend
  16205. *******************************************************************************/
  16206. #ifdef MA_HAS_NULL
  16207. #define MA_DEVICE_OP_NONE__NULL 0
  16208. #define MA_DEVICE_OP_START__NULL 1
  16209. #define MA_DEVICE_OP_SUSPEND__NULL 2
  16210. #define MA_DEVICE_OP_KILL__NULL 3
  16211. static ma_thread_result MA_THREADCALL ma_device_thread__null(void* pData)
  16212. {
  16213. ma_device* pDevice = (ma_device*)pData;
  16214. MA_ASSERT(pDevice != NULL);
  16215. for (;;) { /* Keep the thread alive until the device is uninitialized. */
  16216. ma_uint32 operation;
  16217. /* Wait for an operation to be requested. */
  16218. ma_event_wait(&pDevice->null_device.operationEvent);
  16219. /* At this point an event should have been triggered. */
  16220. operation = pDevice->null_device.operation;
  16221. /* Starting the device needs to put the thread into a loop. */
  16222. if (operation == MA_DEVICE_OP_START__NULL) {
  16223. /* Reset the timer just in case. */
  16224. ma_timer_init(&pDevice->null_device.timer);
  16225. /* Getting here means a suspend or kill operation has been requested. */
  16226. pDevice->null_device.operationResult = MA_SUCCESS;
  16227. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  16228. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  16229. continue;
  16230. }
  16231. /* Suspending the device means we need to stop the timer and just continue the loop. */
  16232. if (operation == MA_DEVICE_OP_SUSPEND__NULL) {
  16233. /* We need to add the current run time to the prior run time, then reset the timer. */
  16234. pDevice->null_device.priorRunTime += ma_timer_get_time_in_seconds(&pDevice->null_device.timer);
  16235. ma_timer_init(&pDevice->null_device.timer);
  16236. /* We're done. */
  16237. pDevice->null_device.operationResult = MA_SUCCESS;
  16238. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  16239. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  16240. continue;
  16241. }
  16242. /* Killing the device means we need to get out of this loop so that this thread can terminate. */
  16243. if (operation == MA_DEVICE_OP_KILL__NULL) {
  16244. pDevice->null_device.operationResult = MA_SUCCESS;
  16245. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  16246. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  16247. break;
  16248. }
  16249. /* Getting a signal on a "none" operation probably means an error. Return invalid operation. */
  16250. if (operation == MA_DEVICE_OP_NONE__NULL) {
  16251. MA_ASSERT(MA_FALSE); /* <-- Trigger this in debug mode to ensure developers are aware they're doing something wrong (or there's a bug in a miniaudio). */
  16252. pDevice->null_device.operationResult = MA_INVALID_OPERATION;
  16253. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  16254. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  16255. continue; /* Continue the loop. Don't terminate. */
  16256. }
  16257. }
  16258. return (ma_thread_result)0;
  16259. }
  16260. static ma_result ma_device_do_operation__null(ma_device* pDevice, ma_uint32 operation)
  16261. {
  16262. ma_result result;
  16263. /*
  16264. TODO: Need to review this and consider just using mutual exclusion. I think the original motivation
  16265. for this was to just post the event to a queue and return immediately, but that has since changed
  16266. and now this function is synchronous. I think this can be simplified to just use a mutex.
  16267. */
  16268. /*
  16269. The first thing to do is wait for an operation slot to become available. We only have a single slot for this, but we could extend this later
  16270. to support queing of operations.
  16271. */
  16272. result = ma_semaphore_wait(&pDevice->null_device.operationSemaphore);
  16273. if (result != MA_SUCCESS) {
  16274. return result; /* Failed to wait for the event. */
  16275. }
  16276. /*
  16277. When we get here it means the background thread is not referencing the operation code and it can be changed. After changing this we need to
  16278. signal an event to the worker thread to let it know that it can start work.
  16279. */
  16280. pDevice->null_device.operation = operation;
  16281. /* Once the operation code has been set, the worker thread can start work. */
  16282. if (ma_event_signal(&pDevice->null_device.operationEvent) != MA_SUCCESS) {
  16283. return MA_ERROR;
  16284. }
  16285. /* We want everything to be synchronous so we're going to wait for the worker thread to complete it's operation. */
  16286. if (ma_event_wait(&pDevice->null_device.operationCompletionEvent) != MA_SUCCESS) {
  16287. return MA_ERROR;
  16288. }
  16289. return pDevice->null_device.operationResult;
  16290. }
  16291. static ma_uint64 ma_device_get_total_run_time_in_frames__null(ma_device* pDevice)
  16292. {
  16293. ma_uint32 internalSampleRate;
  16294. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  16295. internalSampleRate = pDevice->capture.internalSampleRate;
  16296. } else {
  16297. internalSampleRate = pDevice->playback.internalSampleRate;
  16298. }
  16299. return (ma_uint64)((pDevice->null_device.priorRunTime + ma_timer_get_time_in_seconds(&pDevice->null_device.timer)) * internalSampleRate);
  16300. }
  16301. static ma_result ma_context_enumerate_devices__null(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  16302. {
  16303. ma_bool32 cbResult = MA_TRUE;
  16304. MA_ASSERT(pContext != NULL);
  16305. MA_ASSERT(callback != NULL);
  16306. /* Playback. */
  16307. if (cbResult) {
  16308. ma_device_info deviceInfo;
  16309. MA_ZERO_OBJECT(&deviceInfo);
  16310. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Playback Device", (size_t)-1);
  16311. deviceInfo.isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */
  16312. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  16313. }
  16314. /* Capture. */
  16315. if (cbResult) {
  16316. ma_device_info deviceInfo;
  16317. MA_ZERO_OBJECT(&deviceInfo);
  16318. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Capture Device", (size_t)-1);
  16319. deviceInfo.isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */
  16320. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  16321. }
  16322. (void)cbResult; /* Silence a static analysis warning. */
  16323. return MA_SUCCESS;
  16324. }
  16325. static ma_result ma_context_get_device_info__null(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  16326. {
  16327. MA_ASSERT(pContext != NULL);
  16328. if (pDeviceID != NULL && pDeviceID->nullbackend != 0) {
  16329. return MA_NO_DEVICE; /* Don't know the device. */
  16330. }
  16331. /* Name / Description */
  16332. if (deviceType == ma_device_type_playback) {
  16333. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Playback Device", (size_t)-1);
  16334. } else {
  16335. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Capture Device", (size_t)-1);
  16336. }
  16337. pDeviceInfo->isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */
  16338. /* Support everything on the null backend. */
  16339. pDeviceInfo->nativeDataFormats[0].format = ma_format_unknown;
  16340. pDeviceInfo->nativeDataFormats[0].channels = 0;
  16341. pDeviceInfo->nativeDataFormats[0].sampleRate = 0;
  16342. pDeviceInfo->nativeDataFormats[0].flags = 0;
  16343. pDeviceInfo->nativeDataFormatCount = 1;
  16344. (void)pContext;
  16345. return MA_SUCCESS;
  16346. }
  16347. static ma_result ma_device_uninit__null(ma_device* pDevice)
  16348. {
  16349. MA_ASSERT(pDevice != NULL);
  16350. /* Keep it clean and wait for the device thread to finish before returning. */
  16351. ma_device_do_operation__null(pDevice, MA_DEVICE_OP_KILL__NULL);
  16352. /* Wait for the thread to finish before continuing. */
  16353. ma_thread_wait(&pDevice->null_device.deviceThread);
  16354. /* At this point the loop in the device thread is as good as terminated so we can uninitialize our events. */
  16355. ma_semaphore_uninit(&pDevice->null_device.operationSemaphore);
  16356. ma_event_uninit(&pDevice->null_device.operationCompletionEvent);
  16357. ma_event_uninit(&pDevice->null_device.operationEvent);
  16358. return MA_SUCCESS;
  16359. }
  16360. static ma_result ma_device_init__null(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  16361. {
  16362. ma_result result;
  16363. MA_ASSERT(pDevice != NULL);
  16364. MA_ZERO_OBJECT(&pDevice->null_device);
  16365. if (pConfig->deviceType == ma_device_type_loopback) {
  16366. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  16367. }
  16368. /* The null backend supports everything exactly as we specify it. */
  16369. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  16370. pDescriptorCapture->format = (pDescriptorCapture->format != ma_format_unknown) ? pDescriptorCapture->format : MA_DEFAULT_FORMAT;
  16371. pDescriptorCapture->channels = (pDescriptorCapture->channels != 0) ? pDescriptorCapture->channels : MA_DEFAULT_CHANNELS;
  16372. pDescriptorCapture->sampleRate = (pDescriptorCapture->sampleRate != 0) ? pDescriptorCapture->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  16373. if (pDescriptorCapture->channelMap[0] == MA_CHANNEL_NONE) {
  16374. ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  16375. }
  16376. pDescriptorCapture->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
  16377. }
  16378. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  16379. pDescriptorPlayback->format = (pDescriptorPlayback->format != ma_format_unknown) ? pDescriptorPlayback->format : MA_DEFAULT_FORMAT;
  16380. pDescriptorPlayback->channels = (pDescriptorPlayback->channels != 0) ? pDescriptorPlayback->channels : MA_DEFAULT_CHANNELS;
  16381. pDescriptorPlayback->sampleRate = (pDescriptorPlayback->sampleRate != 0) ? pDescriptorPlayback->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  16382. if (pDescriptorPlayback->channelMap[0] == MA_CHANNEL_NONE) {
  16383. ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptorPlayback->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorPlayback->channels);
  16384. }
  16385. pDescriptorPlayback->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  16386. }
  16387. /*
  16388. In order to get timing right, we need to create a thread that does nothing but keeps track of the timer. This timer is started when the
  16389. first period is "written" to it, and then stopped in ma_device_stop__null().
  16390. */
  16391. result = ma_event_init(&pDevice->null_device.operationEvent);
  16392. if (result != MA_SUCCESS) {
  16393. return result;
  16394. }
  16395. result = ma_event_init(&pDevice->null_device.operationCompletionEvent);
  16396. if (result != MA_SUCCESS) {
  16397. return result;
  16398. }
  16399. result = ma_semaphore_init(1, &pDevice->null_device.operationSemaphore); /* <-- It's important that the initial value is set to 1. */
  16400. if (result != MA_SUCCESS) {
  16401. return result;
  16402. }
  16403. result = ma_thread_create(&pDevice->null_device.deviceThread, pDevice->pContext->threadPriority, 0, ma_device_thread__null, pDevice, &pDevice->pContext->allocationCallbacks);
  16404. if (result != MA_SUCCESS) {
  16405. return result;
  16406. }
  16407. return MA_SUCCESS;
  16408. }
  16409. static ma_result ma_device_start__null(ma_device* pDevice)
  16410. {
  16411. MA_ASSERT(pDevice != NULL);
  16412. ma_device_do_operation__null(pDevice, MA_DEVICE_OP_START__NULL);
  16413. ma_atomic_bool32_set(&pDevice->null_device.isStarted, MA_TRUE);
  16414. return MA_SUCCESS;
  16415. }
  16416. static ma_result ma_device_stop__null(ma_device* pDevice)
  16417. {
  16418. MA_ASSERT(pDevice != NULL);
  16419. ma_device_do_operation__null(pDevice, MA_DEVICE_OP_SUSPEND__NULL);
  16420. ma_atomic_bool32_set(&pDevice->null_device.isStarted, MA_FALSE);
  16421. return MA_SUCCESS;
  16422. }
  16423. static ma_bool32 ma_device_is_started__null(ma_device* pDevice)
  16424. {
  16425. MA_ASSERT(pDevice != NULL);
  16426. return ma_atomic_bool32_get(&pDevice->null_device.isStarted);
  16427. }
  16428. static ma_result ma_device_write__null(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  16429. {
  16430. ma_result result = MA_SUCCESS;
  16431. ma_uint32 totalPCMFramesProcessed;
  16432. ma_bool32 wasStartedOnEntry;
  16433. if (pFramesWritten != NULL) {
  16434. *pFramesWritten = 0;
  16435. }
  16436. wasStartedOnEntry = ma_device_is_started__null(pDevice);
  16437. /* Keep going until everything has been read. */
  16438. totalPCMFramesProcessed = 0;
  16439. while (totalPCMFramesProcessed < frameCount) {
  16440. ma_uint64 targetFrame;
  16441. /* If there are any frames remaining in the current period, consume those first. */
  16442. if (pDevice->null_device.currentPeriodFramesRemainingPlayback > 0) {
  16443. ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed);
  16444. ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingPlayback;
  16445. if (framesToProcess > framesRemaining) {
  16446. framesToProcess = framesRemaining;
  16447. }
  16448. /* We don't actually do anything with pPCMFrames, so just mark it as unused to prevent a warning. */
  16449. (void)pPCMFrames;
  16450. pDevice->null_device.currentPeriodFramesRemainingPlayback -= framesToProcess;
  16451. totalPCMFramesProcessed += framesToProcess;
  16452. }
  16453. /* If we've consumed the current period we'll need to mark it as such an ensure the device is started if it's not already. */
  16454. if (pDevice->null_device.currentPeriodFramesRemainingPlayback == 0) {
  16455. pDevice->null_device.currentPeriodFramesRemainingPlayback = 0;
  16456. if (!ma_device_is_started__null(pDevice) && !wasStartedOnEntry) {
  16457. result = ma_device_start__null(pDevice);
  16458. if (result != MA_SUCCESS) {
  16459. break;
  16460. }
  16461. }
  16462. }
  16463. /* If we've consumed the whole buffer we can return now. */
  16464. MA_ASSERT(totalPCMFramesProcessed <= frameCount);
  16465. if (totalPCMFramesProcessed == frameCount) {
  16466. break;
  16467. }
  16468. /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */
  16469. targetFrame = pDevice->null_device.lastProcessedFramePlayback;
  16470. for (;;) {
  16471. ma_uint64 currentFrame;
  16472. /* Stop waiting if the device has been stopped. */
  16473. if (!ma_device_is_started__null(pDevice)) {
  16474. break;
  16475. }
  16476. currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice);
  16477. if (currentFrame >= targetFrame) {
  16478. break;
  16479. }
  16480. /* Getting here means we haven't yet reached the target sample, so continue waiting. */
  16481. ma_sleep(10);
  16482. }
  16483. pDevice->null_device.lastProcessedFramePlayback += pDevice->playback.internalPeriodSizeInFrames;
  16484. pDevice->null_device.currentPeriodFramesRemainingPlayback = pDevice->playback.internalPeriodSizeInFrames;
  16485. }
  16486. if (pFramesWritten != NULL) {
  16487. *pFramesWritten = totalPCMFramesProcessed;
  16488. }
  16489. return result;
  16490. }
  16491. static ma_result ma_device_read__null(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  16492. {
  16493. ma_result result = MA_SUCCESS;
  16494. ma_uint32 totalPCMFramesProcessed;
  16495. if (pFramesRead != NULL) {
  16496. *pFramesRead = 0;
  16497. }
  16498. /* Keep going until everything has been read. */
  16499. totalPCMFramesProcessed = 0;
  16500. while (totalPCMFramesProcessed < frameCount) {
  16501. ma_uint64 targetFrame;
  16502. /* If there are any frames remaining in the current period, consume those first. */
  16503. if (pDevice->null_device.currentPeriodFramesRemainingCapture > 0) {
  16504. ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  16505. ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed);
  16506. ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingCapture;
  16507. if (framesToProcess > framesRemaining) {
  16508. framesToProcess = framesRemaining;
  16509. }
  16510. /* We need to ensure the output buffer is zeroed. */
  16511. MA_ZERO_MEMORY(ma_offset_ptr(pPCMFrames, totalPCMFramesProcessed*bpf), framesToProcess*bpf);
  16512. pDevice->null_device.currentPeriodFramesRemainingCapture -= framesToProcess;
  16513. totalPCMFramesProcessed += framesToProcess;
  16514. }
  16515. /* If we've consumed the current period we'll need to mark it as such an ensure the device is started if it's not already. */
  16516. if (pDevice->null_device.currentPeriodFramesRemainingCapture == 0) {
  16517. pDevice->null_device.currentPeriodFramesRemainingCapture = 0;
  16518. }
  16519. /* If we've consumed the whole buffer we can return now. */
  16520. MA_ASSERT(totalPCMFramesProcessed <= frameCount);
  16521. if (totalPCMFramesProcessed == frameCount) {
  16522. break;
  16523. }
  16524. /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */
  16525. targetFrame = pDevice->null_device.lastProcessedFrameCapture + pDevice->capture.internalPeriodSizeInFrames;
  16526. for (;;) {
  16527. ma_uint64 currentFrame;
  16528. /* Stop waiting if the device has been stopped. */
  16529. if (!ma_device_is_started__null(pDevice)) {
  16530. break;
  16531. }
  16532. currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice);
  16533. if (currentFrame >= targetFrame) {
  16534. break;
  16535. }
  16536. /* Getting here means we haven't yet reached the target sample, so continue waiting. */
  16537. ma_sleep(10);
  16538. }
  16539. pDevice->null_device.lastProcessedFrameCapture += pDevice->capture.internalPeriodSizeInFrames;
  16540. pDevice->null_device.currentPeriodFramesRemainingCapture = pDevice->capture.internalPeriodSizeInFrames;
  16541. }
  16542. if (pFramesRead != NULL) {
  16543. *pFramesRead = totalPCMFramesProcessed;
  16544. }
  16545. return result;
  16546. }
  16547. static ma_result ma_context_uninit__null(ma_context* pContext)
  16548. {
  16549. MA_ASSERT(pContext != NULL);
  16550. MA_ASSERT(pContext->backend == ma_backend_null);
  16551. (void)pContext;
  16552. return MA_SUCCESS;
  16553. }
  16554. static ma_result ma_context_init__null(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  16555. {
  16556. MA_ASSERT(pContext != NULL);
  16557. (void)pConfig;
  16558. (void)pContext;
  16559. pCallbacks->onContextInit = ma_context_init__null;
  16560. pCallbacks->onContextUninit = ma_context_uninit__null;
  16561. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__null;
  16562. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__null;
  16563. pCallbacks->onDeviceInit = ma_device_init__null;
  16564. pCallbacks->onDeviceUninit = ma_device_uninit__null;
  16565. pCallbacks->onDeviceStart = ma_device_start__null;
  16566. pCallbacks->onDeviceStop = ma_device_stop__null;
  16567. pCallbacks->onDeviceRead = ma_device_read__null;
  16568. pCallbacks->onDeviceWrite = ma_device_write__null;
  16569. pCallbacks->onDeviceDataLoop = NULL; /* Our backend is asynchronous with a blocking read-write API which means we can get miniaudio to deal with the audio thread. */
  16570. /* The null backend always works. */
  16571. return MA_SUCCESS;
  16572. }
  16573. #endif
  16574. /*******************************************************************************
  16575. WIN32 COMMON
  16576. *******************************************************************************/
  16577. #if defined(MA_WIN32)
  16578. #if defined(MA_WIN32_DESKTOP)
  16579. #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) ((pContext->win32.CoInitializeEx) ? ((MA_PFN_CoInitializeEx)pContext->win32.CoInitializeEx)(pvReserved, dwCoInit) : ((MA_PFN_CoInitialize)pContext->win32.CoInitialize)(pvReserved))
  16580. #define ma_CoUninitialize(pContext) ((MA_PFN_CoUninitialize)pContext->win32.CoUninitialize)()
  16581. #define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) ((MA_PFN_CoCreateInstance)pContext->win32.CoCreateInstance)(rclsid, pUnkOuter, dwClsContext, riid, ppv)
  16582. #define ma_CoTaskMemFree(pContext, pv) ((MA_PFN_CoTaskMemFree)pContext->win32.CoTaskMemFree)(pv)
  16583. #define ma_PropVariantClear(pContext, pvar) ((MA_PFN_PropVariantClear)pContext->win32.PropVariantClear)(pvar)
  16584. #else
  16585. #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) CoInitializeEx(pvReserved, dwCoInit)
  16586. #define ma_CoUninitialize(pContext) CoUninitialize()
  16587. #define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv)
  16588. #define ma_CoTaskMemFree(pContext, pv) CoTaskMemFree(pv)
  16589. #define ma_PropVariantClear(pContext, pvar) PropVariantClear(pvar)
  16590. #endif
  16591. #if !defined(MAXULONG_PTR) && !defined(__WATCOMC__)
  16592. typedef size_t DWORD_PTR;
  16593. #endif
  16594. #if !defined(WAVE_FORMAT_1M08)
  16595. #define WAVE_FORMAT_1M08 0x00000001
  16596. #define WAVE_FORMAT_1S08 0x00000002
  16597. #define WAVE_FORMAT_1M16 0x00000004
  16598. #define WAVE_FORMAT_1S16 0x00000008
  16599. #define WAVE_FORMAT_2M08 0x00000010
  16600. #define WAVE_FORMAT_2S08 0x00000020
  16601. #define WAVE_FORMAT_2M16 0x00000040
  16602. #define WAVE_FORMAT_2S16 0x00000080
  16603. #define WAVE_FORMAT_4M08 0x00000100
  16604. #define WAVE_FORMAT_4S08 0x00000200
  16605. #define WAVE_FORMAT_4M16 0x00000400
  16606. #define WAVE_FORMAT_4S16 0x00000800
  16607. #endif
  16608. #if !defined(WAVE_FORMAT_44M08)
  16609. #define WAVE_FORMAT_44M08 0x00000100
  16610. #define WAVE_FORMAT_44S08 0x00000200
  16611. #define WAVE_FORMAT_44M16 0x00000400
  16612. #define WAVE_FORMAT_44S16 0x00000800
  16613. #define WAVE_FORMAT_48M08 0x00001000
  16614. #define WAVE_FORMAT_48S08 0x00002000
  16615. #define WAVE_FORMAT_48M16 0x00004000
  16616. #define WAVE_FORMAT_48S16 0x00008000
  16617. #define WAVE_FORMAT_96M08 0x00010000
  16618. #define WAVE_FORMAT_96S08 0x00020000
  16619. #define WAVE_FORMAT_96M16 0x00040000
  16620. #define WAVE_FORMAT_96S16 0x00080000
  16621. #endif
  16622. #ifndef SPEAKER_FRONT_LEFT
  16623. #define SPEAKER_FRONT_LEFT 0x1
  16624. #define SPEAKER_FRONT_RIGHT 0x2
  16625. #define SPEAKER_FRONT_CENTER 0x4
  16626. #define SPEAKER_LOW_FREQUENCY 0x8
  16627. #define SPEAKER_BACK_LEFT 0x10
  16628. #define SPEAKER_BACK_RIGHT 0x20
  16629. #define SPEAKER_FRONT_LEFT_OF_CENTER 0x40
  16630. #define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80
  16631. #define SPEAKER_BACK_CENTER 0x100
  16632. #define SPEAKER_SIDE_LEFT 0x200
  16633. #define SPEAKER_SIDE_RIGHT 0x400
  16634. #define SPEAKER_TOP_CENTER 0x800
  16635. #define SPEAKER_TOP_FRONT_LEFT 0x1000
  16636. #define SPEAKER_TOP_FRONT_CENTER 0x2000
  16637. #define SPEAKER_TOP_FRONT_RIGHT 0x4000
  16638. #define SPEAKER_TOP_BACK_LEFT 0x8000
  16639. #define SPEAKER_TOP_BACK_CENTER 0x10000
  16640. #define SPEAKER_TOP_BACK_RIGHT 0x20000
  16641. #endif
  16642. /*
  16643. Implement our own version of MA_WAVEFORMATEXTENSIBLE so we can avoid a header. Be careful with this
  16644. because MA_WAVEFORMATEX has an extra two bytes over standard WAVEFORMATEX due to padding. The
  16645. standard version uses tight packing, but for compiler compatibility we're not doing that with ours.
  16646. */
  16647. typedef struct
  16648. {
  16649. WORD wFormatTag;
  16650. WORD nChannels;
  16651. DWORD nSamplesPerSec;
  16652. DWORD nAvgBytesPerSec;
  16653. WORD nBlockAlign;
  16654. WORD wBitsPerSample;
  16655. WORD cbSize;
  16656. } MA_WAVEFORMATEX;
  16657. typedef struct
  16658. {
  16659. WORD wFormatTag;
  16660. WORD nChannels;
  16661. DWORD nSamplesPerSec;
  16662. DWORD nAvgBytesPerSec;
  16663. WORD nBlockAlign;
  16664. WORD wBitsPerSample;
  16665. WORD cbSize;
  16666. union
  16667. {
  16668. WORD wValidBitsPerSample;
  16669. WORD wSamplesPerBlock;
  16670. WORD wReserved;
  16671. } Samples;
  16672. DWORD dwChannelMask;
  16673. GUID SubFormat;
  16674. } MA_WAVEFORMATEXTENSIBLE;
  16675. #ifndef WAVE_FORMAT_EXTENSIBLE
  16676. #define WAVE_FORMAT_EXTENSIBLE 0xFFFE
  16677. #endif
  16678. #ifndef WAVE_FORMAT_PCM
  16679. #define WAVE_FORMAT_PCM 1
  16680. #endif
  16681. #ifndef WAVE_FORMAT_IEEE_FLOAT
  16682. #define WAVE_FORMAT_IEEE_FLOAT 0x0003
  16683. #endif
  16684. /* Converts an individual Win32-style channel identifier (SPEAKER_FRONT_LEFT, etc.) to miniaudio. */
  16685. static ma_uint8 ma_channel_id_to_ma__win32(DWORD id)
  16686. {
  16687. switch (id)
  16688. {
  16689. case SPEAKER_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
  16690. case SPEAKER_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
  16691. case SPEAKER_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
  16692. case SPEAKER_LOW_FREQUENCY: return MA_CHANNEL_LFE;
  16693. case SPEAKER_BACK_LEFT: return MA_CHANNEL_BACK_LEFT;
  16694. case SPEAKER_BACK_RIGHT: return MA_CHANNEL_BACK_RIGHT;
  16695. case SPEAKER_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
  16696. case SPEAKER_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  16697. case SPEAKER_BACK_CENTER: return MA_CHANNEL_BACK_CENTER;
  16698. case SPEAKER_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
  16699. case SPEAKER_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
  16700. case SPEAKER_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
  16701. case SPEAKER_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
  16702. case SPEAKER_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
  16703. case SPEAKER_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
  16704. case SPEAKER_TOP_BACK_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
  16705. case SPEAKER_TOP_BACK_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
  16706. case SPEAKER_TOP_BACK_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
  16707. default: return 0;
  16708. }
  16709. }
  16710. /* Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to Win32-style. */
  16711. static DWORD ma_channel_id_to_win32(DWORD id)
  16712. {
  16713. switch (id)
  16714. {
  16715. case MA_CHANNEL_MONO: return SPEAKER_FRONT_CENTER;
  16716. case MA_CHANNEL_FRONT_LEFT: return SPEAKER_FRONT_LEFT;
  16717. case MA_CHANNEL_FRONT_RIGHT: return SPEAKER_FRONT_RIGHT;
  16718. case MA_CHANNEL_FRONT_CENTER: return SPEAKER_FRONT_CENTER;
  16719. case MA_CHANNEL_LFE: return SPEAKER_LOW_FREQUENCY;
  16720. case MA_CHANNEL_BACK_LEFT: return SPEAKER_BACK_LEFT;
  16721. case MA_CHANNEL_BACK_RIGHT: return SPEAKER_BACK_RIGHT;
  16722. case MA_CHANNEL_FRONT_LEFT_CENTER: return SPEAKER_FRONT_LEFT_OF_CENTER;
  16723. case MA_CHANNEL_FRONT_RIGHT_CENTER: return SPEAKER_FRONT_RIGHT_OF_CENTER;
  16724. case MA_CHANNEL_BACK_CENTER: return SPEAKER_BACK_CENTER;
  16725. case MA_CHANNEL_SIDE_LEFT: return SPEAKER_SIDE_LEFT;
  16726. case MA_CHANNEL_SIDE_RIGHT: return SPEAKER_SIDE_RIGHT;
  16727. case MA_CHANNEL_TOP_CENTER: return SPEAKER_TOP_CENTER;
  16728. case MA_CHANNEL_TOP_FRONT_LEFT: return SPEAKER_TOP_FRONT_LEFT;
  16729. case MA_CHANNEL_TOP_FRONT_CENTER: return SPEAKER_TOP_FRONT_CENTER;
  16730. case MA_CHANNEL_TOP_FRONT_RIGHT: return SPEAKER_TOP_FRONT_RIGHT;
  16731. case MA_CHANNEL_TOP_BACK_LEFT: return SPEAKER_TOP_BACK_LEFT;
  16732. case MA_CHANNEL_TOP_BACK_CENTER: return SPEAKER_TOP_BACK_CENTER;
  16733. case MA_CHANNEL_TOP_BACK_RIGHT: return SPEAKER_TOP_BACK_RIGHT;
  16734. default: return 0;
  16735. }
  16736. }
  16737. /* Converts a channel mapping to a Win32-style channel mask. */
  16738. static DWORD ma_channel_map_to_channel_mask__win32(const ma_channel* pChannelMap, ma_uint32 channels)
  16739. {
  16740. DWORD dwChannelMask = 0;
  16741. ma_uint32 iChannel;
  16742. for (iChannel = 0; iChannel < channels; ++iChannel) {
  16743. dwChannelMask |= ma_channel_id_to_win32(pChannelMap[iChannel]);
  16744. }
  16745. return dwChannelMask;
  16746. }
  16747. /* Converts a Win32-style channel mask to a miniaudio channel map. */
  16748. static void ma_channel_mask_to_channel_map__win32(DWORD dwChannelMask, ma_uint32 channels, ma_channel* pChannelMap)
  16749. {
  16750. /* If the channel mask is set to 0, just assume a default Win32 channel map. */
  16751. if (dwChannelMask == 0) {
  16752. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channels, channels);
  16753. } else {
  16754. if (channels == 1 && (dwChannelMask & SPEAKER_FRONT_CENTER) != 0) {
  16755. pChannelMap[0] = MA_CHANNEL_MONO;
  16756. } else {
  16757. /* Just iterate over each bit. */
  16758. ma_uint32 iChannel = 0;
  16759. ma_uint32 iBit;
  16760. for (iBit = 0; iBit < 32 && iChannel < channels; ++iBit) {
  16761. DWORD bitValue = (dwChannelMask & (1UL << iBit));
  16762. if (bitValue != 0) {
  16763. /* The bit is set. */
  16764. pChannelMap[iChannel] = ma_channel_id_to_ma__win32(bitValue);
  16765. iChannel += 1;
  16766. }
  16767. }
  16768. }
  16769. }
  16770. }
  16771. #ifdef __cplusplus
  16772. static ma_bool32 ma_is_guid_equal(const void* a, const void* b)
  16773. {
  16774. return IsEqualGUID(*(const GUID*)a, *(const GUID*)b);
  16775. }
  16776. #else
  16777. #define ma_is_guid_equal(a, b) IsEqualGUID((const GUID*)a, (const GUID*)b)
  16778. #endif
  16779. static MA_INLINE ma_bool32 ma_is_guid_null(const void* guid)
  16780. {
  16781. static GUID nullguid = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
  16782. return ma_is_guid_equal(guid, &nullguid);
  16783. }
  16784. static ma_format ma_format_from_WAVEFORMATEX(const MA_WAVEFORMATEX* pWF)
  16785. {
  16786. MA_ASSERT(pWF != NULL);
  16787. if (pWF->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  16788. const MA_WAVEFORMATEXTENSIBLE* pWFEX = (const MA_WAVEFORMATEXTENSIBLE*)pWF;
  16789. if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_PCM)) {
  16790. if (pWFEX->Samples.wValidBitsPerSample == 32) {
  16791. return ma_format_s32;
  16792. }
  16793. if (pWFEX->Samples.wValidBitsPerSample == 24) {
  16794. if (pWFEX->wBitsPerSample == 32) {
  16795. return ma_format_s32;
  16796. }
  16797. if (pWFEX->wBitsPerSample == 24) {
  16798. return ma_format_s24;
  16799. }
  16800. }
  16801. if (pWFEX->Samples.wValidBitsPerSample == 16) {
  16802. return ma_format_s16;
  16803. }
  16804. if (pWFEX->Samples.wValidBitsPerSample == 8) {
  16805. return ma_format_u8;
  16806. }
  16807. }
  16808. if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
  16809. if (pWFEX->Samples.wValidBitsPerSample == 32) {
  16810. return ma_format_f32;
  16811. }
  16812. /*
  16813. if (pWFEX->Samples.wValidBitsPerSample == 64) {
  16814. return ma_format_f64;
  16815. }
  16816. */
  16817. }
  16818. } else {
  16819. if (pWF->wFormatTag == WAVE_FORMAT_PCM) {
  16820. if (pWF->wBitsPerSample == 32) {
  16821. return ma_format_s32;
  16822. }
  16823. if (pWF->wBitsPerSample == 24) {
  16824. return ma_format_s24;
  16825. }
  16826. if (pWF->wBitsPerSample == 16) {
  16827. return ma_format_s16;
  16828. }
  16829. if (pWF->wBitsPerSample == 8) {
  16830. return ma_format_u8;
  16831. }
  16832. }
  16833. if (pWF->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
  16834. if (pWF->wBitsPerSample == 32) {
  16835. return ma_format_f32;
  16836. }
  16837. if (pWF->wBitsPerSample == 64) {
  16838. /*return ma_format_f64;*/
  16839. }
  16840. }
  16841. }
  16842. return ma_format_unknown;
  16843. }
  16844. #endif
  16845. /*******************************************************************************
  16846. WASAPI Backend
  16847. *******************************************************************************/
  16848. #ifdef MA_HAS_WASAPI
  16849. #if 0
  16850. #if defined(_MSC_VER)
  16851. #pragma warning(push)
  16852. #pragma warning(disable:4091) /* 'typedef ': ignored on left of '' when no variable is declared */
  16853. #endif
  16854. #include <audioclient.h>
  16855. #include <mmdeviceapi.h>
  16856. #if defined(_MSC_VER)
  16857. #pragma warning(pop)
  16858. #endif
  16859. #endif /* 0 */
  16860. static ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType);
  16861. /* Some compilers don't define VerifyVersionInfoW. Need to write this ourselves. */
  16862. #define MA_WIN32_WINNT_VISTA 0x0600
  16863. #define MA_VER_MINORVERSION 0x01
  16864. #define MA_VER_MAJORVERSION 0x02
  16865. #define MA_VER_SERVICEPACKMAJOR 0x20
  16866. #define MA_VER_GREATER_EQUAL 0x03
  16867. typedef struct {
  16868. DWORD dwOSVersionInfoSize;
  16869. DWORD dwMajorVersion;
  16870. DWORD dwMinorVersion;
  16871. DWORD dwBuildNumber;
  16872. DWORD dwPlatformId;
  16873. WCHAR szCSDVersion[128];
  16874. WORD wServicePackMajor;
  16875. WORD wServicePackMinor;
  16876. WORD wSuiteMask;
  16877. BYTE wProductType;
  16878. BYTE wReserved;
  16879. } ma_OSVERSIONINFOEXW;
  16880. typedef BOOL (WINAPI * ma_PFNVerifyVersionInfoW) (ma_OSVERSIONINFOEXW* lpVersionInfo, DWORD dwTypeMask, DWORDLONG dwlConditionMask);
  16881. typedef ULONGLONG (WINAPI * ma_PFNVerSetConditionMask)(ULONGLONG dwlConditionMask, DWORD dwTypeBitMask, BYTE dwConditionMask);
  16882. #ifndef PROPERTYKEY_DEFINED
  16883. #define PROPERTYKEY_DEFINED
  16884. #ifndef __WATCOMC__
  16885. typedef struct
  16886. {
  16887. GUID fmtid;
  16888. DWORD pid;
  16889. } PROPERTYKEY;
  16890. #endif
  16891. #endif
  16892. /* Some compilers don't define PropVariantInit(). We just do this ourselves since it's just a memset(). */
  16893. static MA_INLINE void ma_PropVariantInit(MA_PROPVARIANT* pProp)
  16894. {
  16895. MA_ZERO_OBJECT(pProp);
  16896. }
  16897. static const PROPERTYKEY MA_PKEY_Device_FriendlyName = {{0xA45C254E, 0xDF1C, 0x4EFD, {0x80, 0x20, 0x67, 0xD1, 0x46, 0xA8, 0x50, 0xE0}}, 14};
  16898. static const PROPERTYKEY MA_PKEY_AudioEngine_DeviceFormat = {{0xF19F064D, 0x82C, 0x4E27, {0xBC, 0x73, 0x68, 0x82, 0xA1, 0xBB, 0x8E, 0x4C}}, 0};
  16899. static const IID MA_IID_IUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; /* 00000000-0000-0000-C000-000000000046 */
  16900. #if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK)
  16901. static const IID MA_IID_IAgileObject = {0x94EA2B94, 0xE9CC, 0x49E0, {0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90}}; /* 94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90 */
  16902. #endif
  16903. static const IID MA_IID_IAudioClient = {0x1CB9AD4C, 0xDBFA, 0x4C32, {0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}}; /* 1CB9AD4C-DBFA-4C32-B178-C2F568A703B2 = __uuidof(IAudioClient) */
  16904. static const IID MA_IID_IAudioClient2 = {0x726778CD, 0xF60A, 0x4EDA, {0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA}}; /* 726778CD-F60A-4EDA-82DE-E47610CD78AA = __uuidof(IAudioClient2) */
  16905. static const IID MA_IID_IAudioClient3 = {0x7ED4EE07, 0x8E67, 0x4CD4, {0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42}}; /* 7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42 = __uuidof(IAudioClient3) */
  16906. static const IID MA_IID_IAudioRenderClient = {0xF294ACFC, 0x3146, 0x4483, {0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}}; /* F294ACFC-3146-4483-A7BF-ADDCA7C260E2 = __uuidof(IAudioRenderClient) */
  16907. static const IID MA_IID_IAudioCaptureClient = {0xC8ADBD64, 0xE71E, 0x48A0, {0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}}; /* C8ADBD64-E71E-48A0-A4DE-185C395CD317 = __uuidof(IAudioCaptureClient) */
  16908. static const IID MA_IID_IMMNotificationClient = {0x7991EEC9, 0x7E89, 0x4D85, {0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0}}; /* 7991EEC9-7E89-4D85-8390-6C703CEC60C0 = __uuidof(IMMNotificationClient) */
  16909. #if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK)
  16910. static const IID MA_IID_DEVINTERFACE_AUDIO_RENDER = {0xE6327CAD, 0xDCEC, 0x4949, {0xAE, 0x8A, 0x99, 0x1E, 0x97, 0x6A, 0x79, 0xD2}}; /* E6327CAD-DCEC-4949-AE8A-991E976A79D2 */
  16911. static const IID MA_IID_DEVINTERFACE_AUDIO_CAPTURE = {0x2EEF81BE, 0x33FA, 0x4800, {0x96, 0x70, 0x1C, 0xD4, 0x74, 0x97, 0x2C, 0x3F}}; /* 2EEF81BE-33FA-4800-9670-1CD474972C3F */
  16912. static const IID MA_IID_IActivateAudioInterfaceCompletionHandler = {0x41D949AB, 0x9862, 0x444A, {0x80, 0xF6, 0xC2, 0x61, 0x33, 0x4D, 0xA5, 0xEB}}; /* 41D949AB-9862-444A-80F6-C261334DA5EB */
  16913. #endif
  16914. static const IID MA_CLSID_MMDeviceEnumerator = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; /* BCDE0395-E52F-467C-8E3D-C4579291692E = __uuidof(MMDeviceEnumerator) */
  16915. static const IID MA_IID_IMMDeviceEnumerator = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}}; /* A95664D2-9614-4F35-A746-DE8DB63617E6 = __uuidof(IMMDeviceEnumerator) */
  16916. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  16917. #define MA_MM_DEVICE_STATE_ACTIVE 1
  16918. #define MA_MM_DEVICE_STATE_DISABLED 2
  16919. #define MA_MM_DEVICE_STATE_NOTPRESENT 4
  16920. #define MA_MM_DEVICE_STATE_UNPLUGGED 8
  16921. typedef struct ma_IMMDeviceEnumerator ma_IMMDeviceEnumerator;
  16922. typedef struct ma_IMMDeviceCollection ma_IMMDeviceCollection;
  16923. typedef struct ma_IMMDevice ma_IMMDevice;
  16924. #else
  16925. typedef struct ma_IActivateAudioInterfaceCompletionHandler ma_IActivateAudioInterfaceCompletionHandler;
  16926. typedef struct ma_IActivateAudioInterfaceAsyncOperation ma_IActivateAudioInterfaceAsyncOperation;
  16927. #endif
  16928. typedef struct ma_IPropertyStore ma_IPropertyStore;
  16929. typedef struct ma_IAudioClient ma_IAudioClient;
  16930. typedef struct ma_IAudioClient2 ma_IAudioClient2;
  16931. typedef struct ma_IAudioClient3 ma_IAudioClient3;
  16932. typedef struct ma_IAudioRenderClient ma_IAudioRenderClient;
  16933. typedef struct ma_IAudioCaptureClient ma_IAudioCaptureClient;
  16934. typedef ma_int64 MA_REFERENCE_TIME;
  16935. #define MA_AUDCLNT_STREAMFLAGS_CROSSPROCESS 0x00010000
  16936. #define MA_AUDCLNT_STREAMFLAGS_LOOPBACK 0x00020000
  16937. #define MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK 0x00040000
  16938. #define MA_AUDCLNT_STREAMFLAGS_NOPERSIST 0x00080000
  16939. #define MA_AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000
  16940. #define MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
  16941. #define MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
  16942. #define MA_AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED 0x10000000
  16943. #define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE 0x20000000
  16944. #define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED 0x40000000
  16945. /* Buffer flags. */
  16946. #define MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY 1
  16947. #define MA_AUDCLNT_BUFFERFLAGS_SILENT 2
  16948. #define MA_AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR 4
  16949. typedef enum
  16950. {
  16951. ma_eRender = 0,
  16952. ma_eCapture = 1,
  16953. ma_eAll = 2
  16954. } ma_EDataFlow;
  16955. typedef enum
  16956. {
  16957. ma_eConsole = 0,
  16958. ma_eMultimedia = 1,
  16959. ma_eCommunications = 2
  16960. } ma_ERole;
  16961. typedef enum
  16962. {
  16963. MA_AUDCLNT_SHAREMODE_SHARED,
  16964. MA_AUDCLNT_SHAREMODE_EXCLUSIVE
  16965. } MA_AUDCLNT_SHAREMODE;
  16966. typedef enum
  16967. {
  16968. MA_AudioCategory_Other = 0 /* <-- miniaudio is only caring about Other. */
  16969. } MA_AUDIO_STREAM_CATEGORY;
  16970. typedef struct
  16971. {
  16972. ma_uint32 cbSize;
  16973. BOOL bIsOffload;
  16974. MA_AUDIO_STREAM_CATEGORY eCategory;
  16975. } ma_AudioClientProperties;
  16976. /* IUnknown */
  16977. typedef struct
  16978. {
  16979. /* IUnknown */
  16980. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IUnknown* pThis, const IID* const riid, void** ppObject);
  16981. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IUnknown* pThis);
  16982. ULONG (STDMETHODCALLTYPE * Release) (ma_IUnknown* pThis);
  16983. } ma_IUnknownVtbl;
  16984. struct ma_IUnknown
  16985. {
  16986. ma_IUnknownVtbl* lpVtbl;
  16987. };
  16988. static MA_INLINE HRESULT ma_IUnknown_QueryInterface(ma_IUnknown* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16989. static MA_INLINE ULONG ma_IUnknown_AddRef(ma_IUnknown* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16990. static MA_INLINE ULONG ma_IUnknown_Release(ma_IUnknown* pThis) { return pThis->lpVtbl->Release(pThis); }
  16991. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  16992. /* IMMNotificationClient */
  16993. typedef struct
  16994. {
  16995. /* IUnknown */
  16996. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject);
  16997. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMNotificationClient* pThis);
  16998. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMNotificationClient* pThis);
  16999. /* IMMNotificationClient */
  17000. HRESULT (STDMETHODCALLTYPE * OnDeviceStateChanged) (ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, DWORD dwNewState);
  17001. HRESULT (STDMETHODCALLTYPE * OnDeviceAdded) (ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID);
  17002. HRESULT (STDMETHODCALLTYPE * OnDeviceRemoved) (ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID);
  17003. HRESULT (STDMETHODCALLTYPE * OnDefaultDeviceChanged)(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, const WCHAR* pDefaultDeviceID);
  17004. HRESULT (STDMETHODCALLTYPE * OnPropertyValueChanged)(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, const PROPERTYKEY key);
  17005. } ma_IMMNotificationClientVtbl;
  17006. /* IMMDeviceEnumerator */
  17007. typedef struct
  17008. {
  17009. /* IUnknown */
  17010. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject);
  17011. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceEnumerator* pThis);
  17012. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceEnumerator* pThis);
  17013. /* IMMDeviceEnumerator */
  17014. HRESULT (STDMETHODCALLTYPE * EnumAudioEndpoints) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices);
  17015. HRESULT (STDMETHODCALLTYPE * GetDefaultAudioEndpoint) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint);
  17016. HRESULT (STDMETHODCALLTYPE * GetDevice) (ma_IMMDeviceEnumerator* pThis, const WCHAR* pID, ma_IMMDevice** ppDevice);
  17017. HRESULT (STDMETHODCALLTYPE * RegisterEndpointNotificationCallback) (ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient);
  17018. HRESULT (STDMETHODCALLTYPE * UnregisterEndpointNotificationCallback)(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient);
  17019. } ma_IMMDeviceEnumeratorVtbl;
  17020. struct ma_IMMDeviceEnumerator
  17021. {
  17022. ma_IMMDeviceEnumeratorVtbl* lpVtbl;
  17023. };
  17024. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_QueryInterface(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17025. static MA_INLINE ULONG ma_IMMDeviceEnumerator_AddRef(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17026. static MA_INLINE ULONG ma_IMMDeviceEnumerator_Release(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->Release(pThis); }
  17027. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_EnumAudioEndpoints(ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices) { return pThis->lpVtbl->EnumAudioEndpoints(pThis, dataFlow, dwStateMask, ppDevices); }
  17028. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint) { return pThis->lpVtbl->GetDefaultAudioEndpoint(pThis, dataFlow, role, ppEndpoint); }
  17029. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_GetDevice(ma_IMMDeviceEnumerator* pThis, const WCHAR* pID, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->GetDevice(pThis, pID, ppDevice); }
  17030. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_RegisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->RegisterEndpointNotificationCallback(pThis, pClient); }
  17031. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->UnregisterEndpointNotificationCallback(pThis, pClient); }
  17032. /* IMMDeviceCollection */
  17033. typedef struct
  17034. {
  17035. /* IUnknown */
  17036. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject);
  17037. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceCollection* pThis);
  17038. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceCollection* pThis);
  17039. /* IMMDeviceCollection */
  17040. HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IMMDeviceCollection* pThis, UINT* pDevices);
  17041. HRESULT (STDMETHODCALLTYPE * Item) (ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice);
  17042. } ma_IMMDeviceCollectionVtbl;
  17043. struct ma_IMMDeviceCollection
  17044. {
  17045. ma_IMMDeviceCollectionVtbl* lpVtbl;
  17046. };
  17047. static MA_INLINE HRESULT ma_IMMDeviceCollection_QueryInterface(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17048. static MA_INLINE ULONG ma_IMMDeviceCollection_AddRef(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17049. static MA_INLINE ULONG ma_IMMDeviceCollection_Release(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->Release(pThis); }
  17050. static MA_INLINE HRESULT ma_IMMDeviceCollection_GetCount(ma_IMMDeviceCollection* pThis, UINT* pDevices) { return pThis->lpVtbl->GetCount(pThis, pDevices); }
  17051. static MA_INLINE HRESULT ma_IMMDeviceCollection_Item(ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->Item(pThis, nDevice, ppDevice); }
  17052. /* IMMDevice */
  17053. typedef struct
  17054. {
  17055. /* IUnknown */
  17056. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDevice* pThis, const IID* const riid, void** ppObject);
  17057. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDevice* pThis);
  17058. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDevice* pThis);
  17059. /* IMMDevice */
  17060. HRESULT (STDMETHODCALLTYPE * Activate) (ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, MA_PROPVARIANT* pActivationParams, void** ppInterface);
  17061. HRESULT (STDMETHODCALLTYPE * OpenPropertyStore)(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties);
  17062. HRESULT (STDMETHODCALLTYPE * GetId) (ma_IMMDevice* pThis, WCHAR** pID);
  17063. HRESULT (STDMETHODCALLTYPE * GetState) (ma_IMMDevice* pThis, DWORD *pState);
  17064. } ma_IMMDeviceVtbl;
  17065. struct ma_IMMDevice
  17066. {
  17067. ma_IMMDeviceVtbl* lpVtbl;
  17068. };
  17069. static MA_INLINE HRESULT ma_IMMDevice_QueryInterface(ma_IMMDevice* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17070. static MA_INLINE ULONG ma_IMMDevice_AddRef(ma_IMMDevice* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17071. static MA_INLINE ULONG ma_IMMDevice_Release(ma_IMMDevice* pThis) { return pThis->lpVtbl->Release(pThis); }
  17072. static MA_INLINE HRESULT ma_IMMDevice_Activate(ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, MA_PROPVARIANT* pActivationParams, void** ppInterface) { return pThis->lpVtbl->Activate(pThis, iid, dwClsCtx, pActivationParams, ppInterface); }
  17073. static MA_INLINE HRESULT ma_IMMDevice_OpenPropertyStore(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties) { return pThis->lpVtbl->OpenPropertyStore(pThis, stgmAccess, ppProperties); }
  17074. static MA_INLINE HRESULT ma_IMMDevice_GetId(ma_IMMDevice* pThis, WCHAR** pID) { return pThis->lpVtbl->GetId(pThis, pID); }
  17075. static MA_INLINE HRESULT ma_IMMDevice_GetState(ma_IMMDevice* pThis, DWORD *pState) { return pThis->lpVtbl->GetState(pThis, pState); }
  17076. #else
  17077. /* IActivateAudioInterfaceAsyncOperation */
  17078. typedef struct
  17079. {
  17080. /* IUnknown */
  17081. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject);
  17082. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IActivateAudioInterfaceAsyncOperation* pThis);
  17083. ULONG (STDMETHODCALLTYPE * Release) (ma_IActivateAudioInterfaceAsyncOperation* pThis);
  17084. /* IActivateAudioInterfaceAsyncOperation */
  17085. HRESULT (STDMETHODCALLTYPE * GetActivateResult)(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface);
  17086. } ma_IActivateAudioInterfaceAsyncOperationVtbl;
  17087. struct ma_IActivateAudioInterfaceAsyncOperation
  17088. {
  17089. ma_IActivateAudioInterfaceAsyncOperationVtbl* lpVtbl;
  17090. };
  17091. static MA_INLINE HRESULT ma_IActivateAudioInterfaceAsyncOperation_QueryInterface(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17092. static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_AddRef(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17093. static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_Release(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->Release(pThis); }
  17094. static MA_INLINE HRESULT ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface) { return pThis->lpVtbl->GetActivateResult(pThis, pActivateResult, ppActivatedInterface); }
  17095. #endif
  17096. /* IPropertyStore */
  17097. typedef struct
  17098. {
  17099. /* IUnknown */
  17100. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject);
  17101. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IPropertyStore* pThis);
  17102. ULONG (STDMETHODCALLTYPE * Release) (ma_IPropertyStore* pThis);
  17103. /* IPropertyStore */
  17104. HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IPropertyStore* pThis, DWORD* pPropCount);
  17105. HRESULT (STDMETHODCALLTYPE * GetAt) (ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey);
  17106. HRESULT (STDMETHODCALLTYPE * GetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, MA_PROPVARIANT* pPropVar);
  17107. HRESULT (STDMETHODCALLTYPE * SetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const MA_PROPVARIANT* const pPropVar);
  17108. HRESULT (STDMETHODCALLTYPE * Commit) (ma_IPropertyStore* pThis);
  17109. } ma_IPropertyStoreVtbl;
  17110. struct ma_IPropertyStore
  17111. {
  17112. ma_IPropertyStoreVtbl* lpVtbl;
  17113. };
  17114. static MA_INLINE HRESULT ma_IPropertyStore_QueryInterface(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17115. static MA_INLINE ULONG ma_IPropertyStore_AddRef(ma_IPropertyStore* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17116. static MA_INLINE ULONG ma_IPropertyStore_Release(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Release(pThis); }
  17117. static MA_INLINE HRESULT ma_IPropertyStore_GetCount(ma_IPropertyStore* pThis, DWORD* pPropCount) { return pThis->lpVtbl->GetCount(pThis, pPropCount); }
  17118. static MA_INLINE HRESULT ma_IPropertyStore_GetAt(ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey) { return pThis->lpVtbl->GetAt(pThis, propIndex, pPropKey); }
  17119. static MA_INLINE HRESULT ma_IPropertyStore_GetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, MA_PROPVARIANT* pPropVar) { return pThis->lpVtbl->GetValue(pThis, pKey, pPropVar); }
  17120. static MA_INLINE HRESULT ma_IPropertyStore_SetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const MA_PROPVARIANT* const pPropVar) { return pThis->lpVtbl->SetValue(pThis, pKey, pPropVar); }
  17121. static MA_INLINE HRESULT ma_IPropertyStore_Commit(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Commit(pThis); }
  17122. /* IAudioClient */
  17123. typedef struct
  17124. {
  17125. /* IUnknown */
  17126. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient* pThis, const IID* const riid, void** ppObject);
  17127. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient* pThis);
  17128. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient* pThis);
  17129. /* IAudioClient */
  17130. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
  17131. HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames);
  17132. HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency);
  17133. HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames);
  17134. HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch);
  17135. HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient* pThis, MA_WAVEFORMATEX** ppDeviceFormat);
  17136. HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
  17137. HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient* pThis);
  17138. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient* pThis);
  17139. HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient* pThis);
  17140. HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient* pThis, HANDLE eventHandle);
  17141. HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient* pThis, const IID* const riid, void** pp);
  17142. } ma_IAudioClientVtbl;
  17143. struct ma_IAudioClient
  17144. {
  17145. ma_IAudioClientVtbl* lpVtbl;
  17146. };
  17147. static MA_INLINE HRESULT ma_IAudioClient_QueryInterface(ma_IAudioClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17148. static MA_INLINE ULONG ma_IAudioClient_AddRef(ma_IAudioClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17149. static MA_INLINE ULONG ma_IAudioClient_Release(ma_IAudioClient* pThis) { return pThis->lpVtbl->Release(pThis); }
  17150. static MA_INLINE HRESULT ma_IAudioClient_Initialize(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); }
  17151. static MA_INLINE HRESULT ma_IAudioClient_GetBufferSize(ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
  17152. static MA_INLINE HRESULT ma_IAudioClient_GetStreamLatency(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
  17153. static MA_INLINE HRESULT ma_IAudioClient_GetCurrentPadding(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
  17154. static MA_INLINE HRESULT ma_IAudioClient_IsFormatSupported(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); }
  17155. static MA_INLINE HRESULT ma_IAudioClient_GetMixFormat(ma_IAudioClient* pThis, MA_WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
  17156. static MA_INLINE HRESULT ma_IAudioClient_GetDevicePeriod(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); }
  17157. static MA_INLINE HRESULT ma_IAudioClient_Start(ma_IAudioClient* pThis) { return pThis->lpVtbl->Start(pThis); }
  17158. static MA_INLINE HRESULT ma_IAudioClient_Stop(ma_IAudioClient* pThis) { return pThis->lpVtbl->Stop(pThis); }
  17159. static MA_INLINE HRESULT ma_IAudioClient_Reset(ma_IAudioClient* pThis) { return pThis->lpVtbl->Reset(pThis); }
  17160. static MA_INLINE HRESULT ma_IAudioClient_SetEventHandle(ma_IAudioClient* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
  17161. static MA_INLINE HRESULT ma_IAudioClient_GetService(ma_IAudioClient* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
  17162. /* IAudioClient2 */
  17163. typedef struct
  17164. {
  17165. /* IUnknown */
  17166. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject);
  17167. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient2* pThis);
  17168. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient2* pThis);
  17169. /* IAudioClient */
  17170. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
  17171. HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames);
  17172. HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency);
  17173. HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames);
  17174. HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch);
  17175. HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient2* pThis, MA_WAVEFORMATEX** ppDeviceFormat);
  17176. HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
  17177. HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient2* pThis);
  17178. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient2* pThis);
  17179. HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient2* pThis);
  17180. HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient2* pThis, HANDLE eventHandle);
  17181. HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient2* pThis, const IID* const riid, void** pp);
  17182. /* IAudioClient2 */
  17183. HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable);
  17184. HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties);
  17185. HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient2* pThis, const MA_WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration);
  17186. } ma_IAudioClient2Vtbl;
  17187. struct ma_IAudioClient2
  17188. {
  17189. ma_IAudioClient2Vtbl* lpVtbl;
  17190. };
  17191. static MA_INLINE HRESULT ma_IAudioClient2_QueryInterface(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17192. static MA_INLINE ULONG ma_IAudioClient2_AddRef(ma_IAudioClient2* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17193. static MA_INLINE ULONG ma_IAudioClient2_Release(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Release(pThis); }
  17194. static MA_INLINE HRESULT ma_IAudioClient2_Initialize(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); }
  17195. static MA_INLINE HRESULT ma_IAudioClient2_GetBufferSize(ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
  17196. static MA_INLINE HRESULT ma_IAudioClient2_GetStreamLatency(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
  17197. static MA_INLINE HRESULT ma_IAudioClient2_GetCurrentPadding(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
  17198. static MA_INLINE HRESULT ma_IAudioClient2_IsFormatSupported(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); }
  17199. static MA_INLINE HRESULT ma_IAudioClient2_GetMixFormat(ma_IAudioClient2* pThis, MA_WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
  17200. static MA_INLINE HRESULT ma_IAudioClient2_GetDevicePeriod(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); }
  17201. static MA_INLINE HRESULT ma_IAudioClient2_Start(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Start(pThis); }
  17202. static MA_INLINE HRESULT ma_IAudioClient2_Stop(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Stop(pThis); }
  17203. static MA_INLINE HRESULT ma_IAudioClient2_Reset(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Reset(pThis); }
  17204. static MA_INLINE HRESULT ma_IAudioClient2_SetEventHandle(ma_IAudioClient2* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
  17205. static MA_INLINE HRESULT ma_IAudioClient2_GetService(ma_IAudioClient2* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
  17206. static MA_INLINE HRESULT ma_IAudioClient2_IsOffloadCapable(ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); }
  17207. static MA_INLINE HRESULT ma_IAudioClient2_SetClientProperties(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); }
  17208. static MA_INLINE HRESULT ma_IAudioClient2_GetBufferSizeLimits(ma_IAudioClient2* pThis, const MA_WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); }
  17209. /* IAudioClient3 */
  17210. typedef struct
  17211. {
  17212. /* IUnknown */
  17213. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject);
  17214. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient3* pThis);
  17215. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient3* pThis);
  17216. /* IAudioClient */
  17217. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
  17218. HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames);
  17219. HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency);
  17220. HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames);
  17221. HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch);
  17222. HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppDeviceFormat);
  17223. HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
  17224. HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient3* pThis);
  17225. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient3* pThis);
  17226. HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient3* pThis);
  17227. HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient3* pThis, HANDLE eventHandle);
  17228. HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient3* pThis, const IID* const riid, void** pp);
  17229. /* IAudioClient2 */
  17230. HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable);
  17231. HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties);
  17232. HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient3* pThis, const MA_WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration);
  17233. /* IAudioClient3 */
  17234. HRESULT (STDMETHODCALLTYPE * GetSharedModeEnginePeriod) (ma_IAudioClient3* pThis, const MA_WAVEFORMATEX* pFormat, ma_uint32* pDefaultPeriodInFrames, ma_uint32* pFundamentalPeriodInFrames, ma_uint32* pMinPeriodInFrames, ma_uint32* pMaxPeriodInFrames);
  17235. HRESULT (STDMETHODCALLTYPE * GetCurrentSharedModeEnginePeriod)(ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames);
  17236. HRESULT (STDMETHODCALLTYPE * InitializeSharedAudioStream) (ma_IAudioClient3* pThis, DWORD streamFlags, ma_uint32 periodInFrames, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
  17237. } ma_IAudioClient3Vtbl;
  17238. struct ma_IAudioClient3
  17239. {
  17240. ma_IAudioClient3Vtbl* lpVtbl;
  17241. };
  17242. static MA_INLINE HRESULT ma_IAudioClient3_QueryInterface(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17243. static MA_INLINE ULONG ma_IAudioClient3_AddRef(ma_IAudioClient3* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17244. static MA_INLINE ULONG ma_IAudioClient3_Release(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Release(pThis); }
  17245. static MA_INLINE HRESULT ma_IAudioClient3_Initialize(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); }
  17246. static MA_INLINE HRESULT ma_IAudioClient3_GetBufferSize(ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
  17247. static MA_INLINE HRESULT ma_IAudioClient3_GetStreamLatency(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
  17248. static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentPadding(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
  17249. static MA_INLINE HRESULT ma_IAudioClient3_IsFormatSupported(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); }
  17250. static MA_INLINE HRESULT ma_IAudioClient3_GetMixFormat(ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
  17251. static MA_INLINE HRESULT ma_IAudioClient3_GetDevicePeriod(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); }
  17252. static MA_INLINE HRESULT ma_IAudioClient3_Start(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Start(pThis); }
  17253. static MA_INLINE HRESULT ma_IAudioClient3_Stop(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Stop(pThis); }
  17254. static MA_INLINE HRESULT ma_IAudioClient3_Reset(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Reset(pThis); }
  17255. static MA_INLINE HRESULT ma_IAudioClient3_SetEventHandle(ma_IAudioClient3* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
  17256. static MA_INLINE HRESULT ma_IAudioClient3_GetService(ma_IAudioClient3* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
  17257. static MA_INLINE HRESULT ma_IAudioClient3_IsOffloadCapable(ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); }
  17258. static MA_INLINE HRESULT ma_IAudioClient3_SetClientProperties(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); }
  17259. static MA_INLINE HRESULT ma_IAudioClient3_GetBufferSizeLimits(ma_IAudioClient3* pThis, const MA_WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); }
  17260. static MA_INLINE HRESULT ma_IAudioClient3_GetSharedModeEnginePeriod(ma_IAudioClient3* pThis, const MA_WAVEFORMATEX* pFormat, ma_uint32* pDefaultPeriodInFrames, ma_uint32* pFundamentalPeriodInFrames, ma_uint32* pMinPeriodInFrames, ma_uint32* pMaxPeriodInFrames) { return pThis->lpVtbl->GetSharedModeEnginePeriod(pThis, pFormat, pDefaultPeriodInFrames, pFundamentalPeriodInFrames, pMinPeriodInFrames, pMaxPeriodInFrames); }
  17261. static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentSharedModeEnginePeriod(ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames) { return pThis->lpVtbl->GetCurrentSharedModeEnginePeriod(pThis, ppFormat, pCurrentPeriodInFrames); }
  17262. static MA_INLINE HRESULT ma_IAudioClient3_InitializeSharedAudioStream(ma_IAudioClient3* pThis, DWORD streamFlags, ma_uint32 periodInFrames, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGUID) { return pThis->lpVtbl->InitializeSharedAudioStream(pThis, streamFlags, periodInFrames, pFormat, pAudioSessionGUID); }
  17263. /* IAudioRenderClient */
  17264. typedef struct
  17265. {
  17266. /* IUnknown */
  17267. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject);
  17268. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioRenderClient* pThis);
  17269. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioRenderClient* pThis);
  17270. /* IAudioRenderClient */
  17271. HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData);
  17272. HRESULT (STDMETHODCALLTYPE * ReleaseBuffer)(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags);
  17273. } ma_IAudioRenderClientVtbl;
  17274. struct ma_IAudioRenderClient
  17275. {
  17276. ma_IAudioRenderClientVtbl* lpVtbl;
  17277. };
  17278. static MA_INLINE HRESULT ma_IAudioRenderClient_QueryInterface(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17279. static MA_INLINE ULONG ma_IAudioRenderClient_AddRef(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17280. static MA_INLINE ULONG ma_IAudioRenderClient_Release(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->Release(pThis); }
  17281. static MA_INLINE HRESULT ma_IAudioRenderClient_GetBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData) { return pThis->lpVtbl->GetBuffer(pThis, numFramesRequested, ppData); }
  17282. static MA_INLINE HRESULT ma_IAudioRenderClient_ReleaseBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesWritten, dwFlags); }
  17283. /* IAudioCaptureClient */
  17284. typedef struct
  17285. {
  17286. /* IUnknown */
  17287. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject);
  17288. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioCaptureClient* pThis);
  17289. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioCaptureClient* pThis);
  17290. /* IAudioRenderClient */
  17291. HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioCaptureClient* pThis, BYTE** ppData, ma_uint32* pNumFramesToRead, DWORD* pFlags, ma_uint64* pDevicePosition, ma_uint64* pQPCPosition);
  17292. HRESULT (STDMETHODCALLTYPE * ReleaseBuffer) (ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead);
  17293. HRESULT (STDMETHODCALLTYPE * GetNextPacketSize)(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket);
  17294. } ma_IAudioCaptureClientVtbl;
  17295. struct ma_IAudioCaptureClient
  17296. {
  17297. ma_IAudioCaptureClientVtbl* lpVtbl;
  17298. };
  17299. static MA_INLINE HRESULT ma_IAudioCaptureClient_QueryInterface(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17300. static MA_INLINE ULONG ma_IAudioCaptureClient_AddRef(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17301. static MA_INLINE ULONG ma_IAudioCaptureClient_Release(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->Release(pThis); }
  17302. static MA_INLINE HRESULT ma_IAudioCaptureClient_GetBuffer(ma_IAudioCaptureClient* pThis, BYTE** ppData, ma_uint32* pNumFramesToRead, DWORD* pFlags, ma_uint64* pDevicePosition, ma_uint64* pQPCPosition) { return pThis->lpVtbl->GetBuffer(pThis, ppData, pNumFramesToRead, pFlags, pDevicePosition, pQPCPosition); }
  17303. static MA_INLINE HRESULT ma_IAudioCaptureClient_ReleaseBuffer(ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesRead); }
  17304. static MA_INLINE HRESULT ma_IAudioCaptureClient_GetNextPacketSize(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket) { return pThis->lpVtbl->GetNextPacketSize(pThis, pNumFramesInNextPacket); }
  17305. #if defined(MA_WIN32_UWP)
  17306. /* mmdevapi Functions */
  17307. typedef HRESULT (WINAPI * MA_PFN_ActivateAudioInterfaceAsync)(const wchar_t* deviceInterfacePath, const IID* riid, MA_PROPVARIANT* activationParams, ma_IActivateAudioInterfaceCompletionHandler* completionHandler, ma_IActivateAudioInterfaceAsyncOperation** activationOperation);
  17308. #endif
  17309. /* Avrt Functions */
  17310. typedef HANDLE (WINAPI * MA_PFN_AvSetMmThreadCharacteristicsA)(const char* TaskName, DWORD* TaskIndex);
  17311. typedef BOOL (WINAPI * MA_PFN_AvRevertMmThreadCharacteristics)(HANDLE AvrtHandle);
  17312. #if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK)
  17313. typedef struct ma_completion_handler_uwp ma_completion_handler_uwp;
  17314. typedef struct
  17315. {
  17316. /* IUnknown */
  17317. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject);
  17318. ULONG (STDMETHODCALLTYPE * AddRef) (ma_completion_handler_uwp* pThis);
  17319. ULONG (STDMETHODCALLTYPE * Release) (ma_completion_handler_uwp* pThis);
  17320. /* IActivateAudioInterfaceCompletionHandler */
  17321. HRESULT (STDMETHODCALLTYPE * ActivateCompleted)(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation);
  17322. } ma_completion_handler_uwp_vtbl;
  17323. struct ma_completion_handler_uwp
  17324. {
  17325. ma_completion_handler_uwp_vtbl* lpVtbl;
  17326. MA_ATOMIC(4, ma_uint32) counter;
  17327. HANDLE hEvent;
  17328. };
  17329. static HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_QueryInterface(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject)
  17330. {
  17331. /*
  17332. We need to "implement" IAgileObject which is just an indicator that's used internally by WASAPI for some multithreading management. To
  17333. "implement" this, we just make sure we return pThis when the IAgileObject is requested.
  17334. */
  17335. if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IActivateAudioInterfaceCompletionHandler) && !ma_is_guid_equal(riid, &MA_IID_IAgileObject)) {
  17336. *ppObject = NULL;
  17337. return E_NOINTERFACE;
  17338. }
  17339. /* Getting here means the IID is IUnknown or IMMNotificationClient. */
  17340. *ppObject = (void*)pThis;
  17341. ((ma_completion_handler_uwp_vtbl*)pThis->lpVtbl)->AddRef(pThis);
  17342. return S_OK;
  17343. }
  17344. static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_AddRef(ma_completion_handler_uwp* pThis)
  17345. {
  17346. return (ULONG)c89atomic_fetch_add_32(&pThis->counter, 1) + 1;
  17347. }
  17348. static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_Release(ma_completion_handler_uwp* pThis)
  17349. {
  17350. ma_uint32 newRefCount = c89atomic_fetch_sub_32(&pThis->counter, 1) - 1;
  17351. if (newRefCount == 0) {
  17352. return 0; /* We don't free anything here because we never allocate the object on the heap. */
  17353. }
  17354. return (ULONG)newRefCount;
  17355. }
  17356. static HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_ActivateCompleted(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation)
  17357. {
  17358. (void)pActivateOperation;
  17359. SetEvent(pThis->hEvent);
  17360. return S_OK;
  17361. }
  17362. static ma_completion_handler_uwp_vtbl g_maCompletionHandlerVtblInstance = {
  17363. ma_completion_handler_uwp_QueryInterface,
  17364. ma_completion_handler_uwp_AddRef,
  17365. ma_completion_handler_uwp_Release,
  17366. ma_completion_handler_uwp_ActivateCompleted
  17367. };
  17368. static ma_result ma_completion_handler_uwp_init(ma_completion_handler_uwp* pHandler)
  17369. {
  17370. MA_ASSERT(pHandler != NULL);
  17371. MA_ZERO_OBJECT(pHandler);
  17372. pHandler->lpVtbl = &g_maCompletionHandlerVtblInstance;
  17373. pHandler->counter = 1;
  17374. pHandler->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
  17375. if (pHandler->hEvent == NULL) {
  17376. return ma_result_from_GetLastError(GetLastError());
  17377. }
  17378. return MA_SUCCESS;
  17379. }
  17380. static void ma_completion_handler_uwp_uninit(ma_completion_handler_uwp* pHandler)
  17381. {
  17382. if (pHandler->hEvent != NULL) {
  17383. CloseHandle(pHandler->hEvent);
  17384. }
  17385. }
  17386. static void ma_completion_handler_uwp_wait(ma_completion_handler_uwp* pHandler)
  17387. {
  17388. WaitForSingleObject((HANDLE)pHandler->hEvent, INFINITE);
  17389. }
  17390. #endif /* !MA_WIN32_DESKTOP */
  17391. /* We need a virtual table for our notification client object that's used for detecting changes to the default device. */
  17392. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17393. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_QueryInterface(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject)
  17394. {
  17395. /*
  17396. We care about two interfaces - IUnknown and IMMNotificationClient. If the requested IID is something else
  17397. we just return E_NOINTERFACE. Otherwise we need to increment the reference counter and return S_OK.
  17398. */
  17399. if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IMMNotificationClient)) {
  17400. *ppObject = NULL;
  17401. return E_NOINTERFACE;
  17402. }
  17403. /* Getting here means the IID is IUnknown or IMMNotificationClient. */
  17404. *ppObject = (void*)pThis;
  17405. ((ma_IMMNotificationClientVtbl*)pThis->lpVtbl)->AddRef(pThis);
  17406. return S_OK;
  17407. }
  17408. static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_AddRef(ma_IMMNotificationClient* pThis)
  17409. {
  17410. return (ULONG)c89atomic_fetch_add_32(&pThis->counter, 1) + 1;
  17411. }
  17412. static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_Release(ma_IMMNotificationClient* pThis)
  17413. {
  17414. ma_uint32 newRefCount = c89atomic_fetch_sub_32(&pThis->counter, 1) - 1;
  17415. if (newRefCount == 0) {
  17416. return 0; /* We don't free anything here because we never allocate the object on the heap. */
  17417. }
  17418. return (ULONG)newRefCount;
  17419. }
  17420. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceStateChanged(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, DWORD dwNewState)
  17421. {
  17422. ma_bool32 isThisDevice = MA_FALSE;
  17423. ma_bool32 isCapture = MA_FALSE;
  17424. ma_bool32 isPlayback = MA_FALSE;
  17425. #ifdef MA_DEBUG_OUTPUT
  17426. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDeviceStateChanged(pDeviceID=%S, dwNewState=%u)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)", (unsigned int)dwNewState);*/
  17427. #endif
  17428. /*
  17429. There have been reports of a hang when a playback device is disconnected. The idea with this code is to explicitly stop the device if we detect
  17430. that the device is disabled or has been unplugged.
  17431. */
  17432. if (pThis->pDevice->wasapi.allowCaptureAutoStreamRouting && (pThis->pDevice->type == ma_device_type_capture || pThis->pDevice->type == ma_device_type_duplex || pThis->pDevice->type == ma_device_type_loopback)) {
  17433. isCapture = MA_TRUE;
  17434. if (ma_strcmp_WCHAR(pThis->pDevice->capture.id.wasapi, pDeviceID) == 0) {
  17435. isThisDevice = MA_TRUE;
  17436. }
  17437. }
  17438. if (pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting && (pThis->pDevice->type == ma_device_type_playback || pThis->pDevice->type == ma_device_type_duplex)) {
  17439. isPlayback = MA_TRUE;
  17440. if (ma_strcmp_WCHAR(pThis->pDevice->playback.id.wasapi, pDeviceID) == 0) {
  17441. isThisDevice = MA_TRUE;
  17442. }
  17443. }
  17444. /*
  17445. If the device ID matches our device we need to mark our device as detached and stop it. When a
  17446. device is added in OnDeviceAdded(), we'll restart it. We only mark it as detached if the device
  17447. was started at the time of being removed.
  17448. */
  17449. if (isThisDevice) {
  17450. if ((dwNewState & MA_MM_DEVICE_STATE_ACTIVE) == 0) {
  17451. /*
  17452. Unplugged or otherwise unavailable. Mark as detached if we were in a playing state. We'll
  17453. use this to determine whether or not we need to automatically start the device when it's
  17454. plugged back in again.
  17455. */
  17456. if (ma_device_get_state(pThis->pDevice) == ma_device_state_started) {
  17457. if (isPlayback) {
  17458. pThis->pDevice->wasapi.isDetachedPlayback = MA_TRUE;
  17459. }
  17460. if (isCapture) {
  17461. pThis->pDevice->wasapi.isDetachedCapture = MA_TRUE;
  17462. }
  17463. ma_device_stop(pThis->pDevice);
  17464. }
  17465. }
  17466. if ((dwNewState & MA_MM_DEVICE_STATE_ACTIVE) != 0) {
  17467. /* The device was activated. If we were detached, we need to start it again. */
  17468. ma_bool8 tryRestartingDevice = MA_FALSE;
  17469. if (isPlayback) {
  17470. if (pThis->pDevice->wasapi.isDetachedPlayback) {
  17471. pThis->pDevice->wasapi.isDetachedPlayback = MA_FALSE;
  17472. ma_device_reroute__wasapi(pThis->pDevice, ma_device_type_playback);
  17473. tryRestartingDevice = MA_TRUE;
  17474. }
  17475. }
  17476. if (isCapture) {
  17477. if (pThis->pDevice->wasapi.isDetachedCapture) {
  17478. pThis->pDevice->wasapi.isDetachedCapture = MA_FALSE;
  17479. ma_device_reroute__wasapi(pThis->pDevice, (pThis->pDevice->type == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture);
  17480. tryRestartingDevice = MA_TRUE;
  17481. }
  17482. }
  17483. if (tryRestartingDevice) {
  17484. if (pThis->pDevice->wasapi.isDetachedPlayback == MA_FALSE && pThis->pDevice->wasapi.isDetachedCapture == MA_FALSE) {
  17485. ma_device_start(pThis->pDevice);
  17486. }
  17487. }
  17488. }
  17489. }
  17490. return S_OK;
  17491. }
  17492. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceAdded(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID)
  17493. {
  17494. #ifdef MA_DEBUG_OUTPUT
  17495. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDeviceAdded(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
  17496. #endif
  17497. /* We don't need to worry about this event for our purposes. */
  17498. (void)pThis;
  17499. (void)pDeviceID;
  17500. return S_OK;
  17501. }
  17502. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceRemoved(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID)
  17503. {
  17504. #ifdef MA_DEBUG_OUTPUT
  17505. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDeviceRemoved(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
  17506. #endif
  17507. /* We don't need to worry about this event for our purposes. */
  17508. (void)pThis;
  17509. (void)pDeviceID;
  17510. return S_OK;
  17511. }
  17512. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDefaultDeviceChanged(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, const WCHAR* pDefaultDeviceID)
  17513. {
  17514. #ifdef MA_DEBUG_OUTPUT
  17515. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDefaultDeviceChanged(dataFlow=%d, role=%d, pDefaultDeviceID=%S)\n", dataFlow, role, (pDefaultDeviceID != NULL) ? pDefaultDeviceID : L"(NULL)");*/
  17516. #endif
  17517. /* We only ever use the eConsole role in miniaudio. */
  17518. if (role != ma_eConsole) {
  17519. ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting: role != eConsole\n");
  17520. return S_OK;
  17521. }
  17522. /* We only care about devices with the same data flow and role as the current device. */
  17523. if ((pThis->pDevice->type == ma_device_type_playback && dataFlow != ma_eRender) ||
  17524. (pThis->pDevice->type == ma_device_type_capture && dataFlow != ma_eCapture) ||
  17525. (pThis->pDevice->type == ma_device_type_loopback && dataFlow != ma_eRender)) {
  17526. ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because dataFlow does match device type.\n");
  17527. return S_OK;
  17528. }
  17529. /* We need to consider dataFlow as ma_eCapture if device is ma_device_type_loopback */
  17530. if (pThis->pDevice->type == ma_device_type_loopback) {
  17531. dataFlow = ma_eCapture;
  17532. }
  17533. /* Don't do automatic stream routing if we're not allowed. */
  17534. if ((dataFlow == ma_eRender && pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting == MA_FALSE) ||
  17535. (dataFlow == ma_eCapture && pThis->pDevice->wasapi.allowCaptureAutoStreamRouting == MA_FALSE)) {
  17536. ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because automatic stream routing has been disabled by the device config.\n");
  17537. return S_OK;
  17538. }
  17539. /*
  17540. Not currently supporting automatic stream routing in exclusive mode. This is not working correctly on my machine due to
  17541. AUDCLNT_E_DEVICE_IN_USE errors when reinitializing the device. If this is a bug in miniaudio, we can try re-enabling this once
  17542. it's fixed.
  17543. */
  17544. if ((dataFlow == ma_eRender && pThis->pDevice->playback.shareMode == ma_share_mode_exclusive) ||
  17545. (dataFlow == ma_eCapture && pThis->pDevice->capture.shareMode == ma_share_mode_exclusive)) {
  17546. ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because the device shared mode is exclusive.\n");
  17547. return S_OK;
  17548. }
  17549. /*
  17550. Second attempt at device rerouting. We're going to retrieve the device's state at the time of
  17551. the route change. We're then going to stop the device, reinitialize the device, and then start
  17552. it again if the state before stopping was ma_device_state_started.
  17553. */
  17554. {
  17555. ma_uint32 previousState = ma_device_get_state(pThis->pDevice);
  17556. ma_bool8 restartDevice = MA_FALSE;
  17557. if (previousState == ma_device_state_uninitialized || previousState == ma_device_state_starting) {
  17558. ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because the device is in the process of starting.\n");
  17559. return S_OK;
  17560. }
  17561. if (previousState == ma_device_state_started) {
  17562. ma_device_stop(pThis->pDevice);
  17563. restartDevice = MA_TRUE;
  17564. }
  17565. if (pDefaultDeviceID != NULL) { /* <-- The input device ID will be null if there's no other device available. */
  17566. ma_mutex_lock(&pThis->pDevice->wasapi.rerouteLock);
  17567. {
  17568. if (dataFlow == ma_eRender) {
  17569. ma_device_reroute__wasapi(pThis->pDevice, ma_device_type_playback);
  17570. if (pThis->pDevice->wasapi.isDetachedPlayback) {
  17571. pThis->pDevice->wasapi.isDetachedPlayback = MA_FALSE;
  17572. if (pThis->pDevice->type == ma_device_type_duplex && pThis->pDevice->wasapi.isDetachedCapture) {
  17573. restartDevice = MA_FALSE; /* It's a duplex device and the capture side is detached. We cannot be restarting the device just yet. */
  17574. }
  17575. else {
  17576. restartDevice = MA_TRUE; /* It's not a duplex device, or the capture side is also attached so we can go ahead and restart the device. */
  17577. }
  17578. }
  17579. }
  17580. else {
  17581. ma_device_reroute__wasapi(pThis->pDevice, (pThis->pDevice->type == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture);
  17582. if (pThis->pDevice->wasapi.isDetachedCapture) {
  17583. pThis->pDevice->wasapi.isDetachedCapture = MA_FALSE;
  17584. if (pThis->pDevice->type == ma_device_type_duplex && pThis->pDevice->wasapi.isDetachedPlayback) {
  17585. restartDevice = MA_FALSE; /* It's a duplex device and the playback side is detached. We cannot be restarting the device just yet. */
  17586. }
  17587. else {
  17588. restartDevice = MA_TRUE; /* It's not a duplex device, or the playback side is also attached so we can go ahead and restart the device. */
  17589. }
  17590. }
  17591. }
  17592. }
  17593. ma_mutex_unlock(&pThis->pDevice->wasapi.rerouteLock);
  17594. if (restartDevice) {
  17595. ma_device_start(pThis->pDevice);
  17596. }
  17597. }
  17598. }
  17599. return S_OK;
  17600. }
  17601. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnPropertyValueChanged(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, const PROPERTYKEY key)
  17602. {
  17603. #ifdef MA_DEBUG_OUTPUT
  17604. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnPropertyValueChanged(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
  17605. #endif
  17606. (void)pThis;
  17607. (void)pDeviceID;
  17608. (void)key;
  17609. return S_OK;
  17610. }
  17611. static ma_IMMNotificationClientVtbl g_maNotificationCientVtbl = {
  17612. ma_IMMNotificationClient_QueryInterface,
  17613. ma_IMMNotificationClient_AddRef,
  17614. ma_IMMNotificationClient_Release,
  17615. ma_IMMNotificationClient_OnDeviceStateChanged,
  17616. ma_IMMNotificationClient_OnDeviceAdded,
  17617. ma_IMMNotificationClient_OnDeviceRemoved,
  17618. ma_IMMNotificationClient_OnDefaultDeviceChanged,
  17619. ma_IMMNotificationClient_OnPropertyValueChanged
  17620. };
  17621. #endif /* MA_WIN32_DESKTOP */
  17622. static const char* ma_to_usage_string__wasapi(ma_wasapi_usage usage)
  17623. {
  17624. switch (usage)
  17625. {
  17626. case ma_wasapi_usage_default: return NULL;
  17627. case ma_wasapi_usage_games: return "Games";
  17628. case ma_wasapi_usage_pro_audio: return "Pro Audio";
  17629. default: break;
  17630. }
  17631. return NULL;
  17632. }
  17633. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17634. typedef ma_IMMDevice ma_WASAPIDeviceInterface;
  17635. #else
  17636. typedef ma_IUnknown ma_WASAPIDeviceInterface;
  17637. #endif
  17638. #define MA_CONTEXT_COMMAND_QUIT__WASAPI 1
  17639. #define MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI 2
  17640. #define MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI 3
  17641. static ma_context_command__wasapi ma_context_init_command__wasapi(int code)
  17642. {
  17643. ma_context_command__wasapi cmd;
  17644. MA_ZERO_OBJECT(&cmd);
  17645. cmd.code = code;
  17646. return cmd;
  17647. }
  17648. static ma_result ma_context_post_command__wasapi(ma_context* pContext, const ma_context_command__wasapi* pCmd)
  17649. {
  17650. /* For now we are doing everything synchronously, but I might relax this later if the need arises. */
  17651. ma_result result;
  17652. ma_bool32 isUsingLocalEvent = MA_FALSE;
  17653. ma_event localEvent;
  17654. MA_ASSERT(pContext != NULL);
  17655. MA_ASSERT(pCmd != NULL);
  17656. if (pCmd->pEvent == NULL) {
  17657. isUsingLocalEvent = MA_TRUE;
  17658. result = ma_event_init(&localEvent);
  17659. if (result != MA_SUCCESS) {
  17660. return result; /* Failed to create the event for this command. */
  17661. }
  17662. }
  17663. /* Here is where we add the command to the list. If there's not enough room we'll spin until there is. */
  17664. ma_mutex_lock(&pContext->wasapi.commandLock);
  17665. {
  17666. ma_uint32 index;
  17667. /* Spin until we've got some space available. */
  17668. while (pContext->wasapi.commandCount == ma_countof(pContext->wasapi.commands)) {
  17669. ma_yield();
  17670. }
  17671. /* Space is now available. Can safely add to the list. */
  17672. index = (pContext->wasapi.commandIndex + pContext->wasapi.commandCount) % ma_countof(pContext->wasapi.commands);
  17673. pContext->wasapi.commands[index] = *pCmd;
  17674. pContext->wasapi.commands[index].pEvent = &localEvent;
  17675. pContext->wasapi.commandCount += 1;
  17676. /* Now that the command has been added, release the semaphore so ma_context_next_command__wasapi() can return. */
  17677. ma_semaphore_release(&pContext->wasapi.commandSem);
  17678. }
  17679. ma_mutex_unlock(&pContext->wasapi.commandLock);
  17680. if (isUsingLocalEvent) {
  17681. ma_event_wait(&localEvent);
  17682. ma_event_uninit(&localEvent);
  17683. }
  17684. return MA_SUCCESS;
  17685. }
  17686. static ma_result ma_context_next_command__wasapi(ma_context* pContext, ma_context_command__wasapi* pCmd)
  17687. {
  17688. ma_result result = MA_SUCCESS;
  17689. MA_ASSERT(pContext != NULL);
  17690. MA_ASSERT(pCmd != NULL);
  17691. result = ma_semaphore_wait(&pContext->wasapi.commandSem);
  17692. if (result == MA_SUCCESS) {
  17693. ma_mutex_lock(&pContext->wasapi.commandLock);
  17694. {
  17695. *pCmd = pContext->wasapi.commands[pContext->wasapi.commandIndex];
  17696. pContext->wasapi.commandIndex = (pContext->wasapi.commandIndex + 1) % ma_countof(pContext->wasapi.commands);
  17697. pContext->wasapi.commandCount -= 1;
  17698. }
  17699. ma_mutex_unlock(&pContext->wasapi.commandLock);
  17700. }
  17701. return result;
  17702. }
  17703. static ma_thread_result MA_THREADCALL ma_context_command_thread__wasapi(void* pUserData)
  17704. {
  17705. ma_result result;
  17706. ma_context* pContext = (ma_context*)pUserData;
  17707. MA_ASSERT(pContext != NULL);
  17708. for (;;) {
  17709. ma_context_command__wasapi cmd;
  17710. result = ma_context_next_command__wasapi(pContext, &cmd);
  17711. if (result != MA_SUCCESS) {
  17712. break;
  17713. }
  17714. switch (cmd.code)
  17715. {
  17716. case MA_CONTEXT_COMMAND_QUIT__WASAPI:
  17717. {
  17718. /* Do nothing. Handled after the switch. */
  17719. } break;
  17720. case MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI:
  17721. {
  17722. if (cmd.data.createAudioClient.deviceType == ma_device_type_playback) {
  17723. *cmd.data.createAudioClient.pResult = ma_result_from_HRESULT(ma_IAudioClient_GetService((ma_IAudioClient*)cmd.data.createAudioClient.pAudioClient, &MA_IID_IAudioRenderClient, cmd.data.createAudioClient.ppAudioClientService));
  17724. } else {
  17725. *cmd.data.createAudioClient.pResult = ma_result_from_HRESULT(ma_IAudioClient_GetService((ma_IAudioClient*)cmd.data.createAudioClient.pAudioClient, &MA_IID_IAudioCaptureClient, cmd.data.createAudioClient.ppAudioClientService));
  17726. }
  17727. } break;
  17728. case MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI:
  17729. {
  17730. if (cmd.data.releaseAudioClient.deviceType == ma_device_type_playback) {
  17731. if (cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback != NULL) {
  17732. ma_IAudioClient_Release((ma_IAudioClient*)cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback);
  17733. cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback = NULL;
  17734. }
  17735. }
  17736. if (cmd.data.releaseAudioClient.deviceType == ma_device_type_capture) {
  17737. if (cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture != NULL) {
  17738. ma_IAudioClient_Release((ma_IAudioClient*)cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture);
  17739. cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture = NULL;
  17740. }
  17741. }
  17742. } break;
  17743. default:
  17744. {
  17745. /* Unknown command. Ignore it, but trigger an assert in debug mode so we're aware of it. */
  17746. MA_ASSERT(MA_FALSE);
  17747. } break;
  17748. }
  17749. if (cmd.pEvent != NULL) {
  17750. ma_event_signal(cmd.pEvent);
  17751. }
  17752. if (cmd.code == MA_CONTEXT_COMMAND_QUIT__WASAPI) {
  17753. break; /* Received a quit message. Get out of here. */
  17754. }
  17755. }
  17756. return (ma_thread_result)0;
  17757. }
  17758. static ma_result ma_device_create_IAudioClient_service__wasapi(ma_context* pContext, ma_device_type deviceType, ma_IAudioClient* pAudioClient, void** ppAudioClientService)
  17759. {
  17760. ma_result result;
  17761. ma_result cmdResult;
  17762. ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI);
  17763. cmd.data.createAudioClient.deviceType = deviceType;
  17764. cmd.data.createAudioClient.pAudioClient = (void*)pAudioClient;
  17765. cmd.data.createAudioClient.ppAudioClientService = ppAudioClientService;
  17766. cmd.data.createAudioClient.pResult = &cmdResult; /* Declared locally, but won't be dereferenced after this function returns since execution of the command will wait here. */
  17767. result = ma_context_post_command__wasapi(pContext, &cmd); /* This will not return until the command has actually been run. */
  17768. if (result != MA_SUCCESS) {
  17769. return result;
  17770. }
  17771. return *cmd.data.createAudioClient.pResult;
  17772. }
  17773. #if 0 /* Not used at the moment, but leaving here for future use. */
  17774. static ma_result ma_device_release_IAudioClient_service__wasapi(ma_device* pDevice, ma_device_type deviceType)
  17775. {
  17776. ma_result result;
  17777. ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI);
  17778. cmd.data.releaseAudioClient.pDevice = pDevice;
  17779. cmd.data.releaseAudioClient.deviceType = deviceType;
  17780. result = ma_context_post_command__wasapi(pDevice->pContext, &cmd); /* This will not return until the command has actually been run. */
  17781. if (result != MA_SUCCESS) {
  17782. return result;
  17783. }
  17784. return MA_SUCCESS;
  17785. }
  17786. #endif
  17787. static void ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(const MA_WAVEFORMATEX* pWF, ma_share_mode shareMode, ma_device_info* pInfo)
  17788. {
  17789. MA_ASSERT(pWF != NULL);
  17790. MA_ASSERT(pInfo != NULL);
  17791. if (pInfo->nativeDataFormatCount >= ma_countof(pInfo->nativeDataFormats)) {
  17792. return; /* Too many data formats. Need to ignore this one. Don't think this should ever happen with WASAPI. */
  17793. }
  17794. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].format = ma_format_from_WAVEFORMATEX(pWF);
  17795. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].channels = pWF->nChannels;
  17796. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].sampleRate = pWF->nSamplesPerSec;
  17797. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].flags = (shareMode == ma_share_mode_exclusive) ? MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE : 0;
  17798. pInfo->nativeDataFormatCount += 1;
  17799. }
  17800. static ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pContext, /*ma_IMMDevice**/void* pMMDevice, ma_IAudioClient* pAudioClient, ma_device_info* pInfo)
  17801. {
  17802. HRESULT hr;
  17803. MA_WAVEFORMATEX* pWF = NULL;
  17804. MA_ASSERT(pAudioClient != NULL);
  17805. MA_ASSERT(pInfo != NULL);
  17806. /* Shared Mode. We use GetMixFormat() here. */
  17807. hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pAudioClient, (MA_WAVEFORMATEX**)&pWF);
  17808. if (SUCCEEDED(hr)) {
  17809. ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_shared, pInfo);
  17810. } else {
  17811. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve mix format for device info retrieval.");
  17812. return ma_result_from_HRESULT(hr);
  17813. }
  17814. /*
  17815. Exlcusive Mode. We repeatedly call IsFormatSupported() here. This is not currently supported on
  17816. UWP. Failure to retrieve the exclusive mode format is not considered an error, so from here on
  17817. out, MA_SUCCESS is guaranteed to be returned.
  17818. */
  17819. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17820. {
  17821. ma_IPropertyStore *pProperties;
  17822. /*
  17823. The first thing to do is get the format from PKEY_AudioEngine_DeviceFormat. This should give us a channel count we assume is
  17824. correct which will simplify our searching.
  17825. */
  17826. hr = ma_IMMDevice_OpenPropertyStore((ma_IMMDevice*)pMMDevice, STGM_READ, &pProperties);
  17827. if (SUCCEEDED(hr)) {
  17828. MA_PROPVARIANT var;
  17829. ma_PropVariantInit(&var);
  17830. hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_AudioEngine_DeviceFormat, &var);
  17831. if (SUCCEEDED(hr)) {
  17832. pWF = (MA_WAVEFORMATEX*)var.blob.pBlobData;
  17833. /*
  17834. In my testing, the format returned by PKEY_AudioEngine_DeviceFormat is suitable for exclusive mode so we check this format
  17835. first. If this fails, fall back to a search.
  17836. */
  17837. hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pWF, NULL);
  17838. if (SUCCEEDED(hr)) {
  17839. /* The format returned by PKEY_AudioEngine_DeviceFormat is supported. */
  17840. ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_exclusive, pInfo);
  17841. } else {
  17842. /*
  17843. The format returned by PKEY_AudioEngine_DeviceFormat is not supported, so fall back to a search. We assume the channel
  17844. count returned by MA_PKEY_AudioEngine_DeviceFormat is valid and correct. For simplicity we're only returning one format.
  17845. */
  17846. ma_uint32 channels = pWF->nChannels;
  17847. ma_channel defaultChannelMap[MA_MAX_CHANNELS];
  17848. MA_WAVEFORMATEXTENSIBLE wf;
  17849. ma_bool32 found;
  17850. ma_uint32 iFormat;
  17851. /* Make sure we don't overflow the channel map. */
  17852. if (channels > MA_MAX_CHANNELS) {
  17853. channels = MA_MAX_CHANNELS;
  17854. }
  17855. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, defaultChannelMap, ma_countof(defaultChannelMap), channels);
  17856. MA_ZERO_OBJECT(&wf);
  17857. wf.cbSize = sizeof(wf);
  17858. wf.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  17859. wf.nChannels = (WORD)channels;
  17860. wf.dwChannelMask = ma_channel_map_to_channel_mask__win32(defaultChannelMap, channels);
  17861. found = MA_FALSE;
  17862. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); ++iFormat) {
  17863. ma_format format = g_maFormatPriorities[iFormat];
  17864. ma_uint32 iSampleRate;
  17865. wf.wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8);
  17866. wf.nBlockAlign = (WORD)(wf.nChannels * wf.wBitsPerSample / 8);
  17867. wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
  17868. wf.Samples.wValidBitsPerSample = /*(format == ma_format_s24_32) ? 24 :*/ wf.wBitsPerSample;
  17869. if (format == ma_format_f32) {
  17870. wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  17871. } else {
  17872. wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
  17873. }
  17874. for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iSampleRate) {
  17875. wf.nSamplesPerSec = g_maStandardSampleRatePriorities[iSampleRate];
  17876. hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, (MA_WAVEFORMATEX*)&wf, NULL);
  17877. if (SUCCEEDED(hr)) {
  17878. ma_add_native_data_format_to_device_info_from_WAVEFORMATEX((MA_WAVEFORMATEX*)&wf, ma_share_mode_exclusive, pInfo);
  17879. found = MA_TRUE;
  17880. break;
  17881. }
  17882. }
  17883. if (found) {
  17884. break;
  17885. }
  17886. }
  17887. ma_PropVariantClear(pContext, &var);
  17888. if (!found) {
  17889. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to find suitable device format for device info retrieval.");
  17890. }
  17891. }
  17892. } else {
  17893. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to retrieve device format for device info retrieval.");
  17894. }
  17895. ma_IPropertyStore_Release(pProperties);
  17896. } else {
  17897. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to open property store for device info retrieval.");
  17898. }
  17899. }
  17900. #else
  17901. {
  17902. (void)pMMDevice; /* Unused. */
  17903. }
  17904. #endif
  17905. return MA_SUCCESS;
  17906. }
  17907. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17908. static ma_EDataFlow ma_device_type_to_EDataFlow(ma_device_type deviceType)
  17909. {
  17910. if (deviceType == ma_device_type_playback) {
  17911. return ma_eRender;
  17912. } else if (deviceType == ma_device_type_capture) {
  17913. return ma_eCapture;
  17914. } else {
  17915. MA_ASSERT(MA_FALSE);
  17916. return ma_eRender; /* Should never hit this. */
  17917. }
  17918. }
  17919. static ma_result ma_context_create_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator** ppDeviceEnumerator)
  17920. {
  17921. HRESULT hr;
  17922. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17923. MA_ASSERT(pContext != NULL);
  17924. MA_ASSERT(ppDeviceEnumerator != NULL);
  17925. *ppDeviceEnumerator = NULL; /* Safety. */
  17926. hr = ma_CoCreateInstance(pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  17927. if (FAILED(hr)) {
  17928. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.");
  17929. return ma_result_from_HRESULT(hr);
  17930. }
  17931. *ppDeviceEnumerator = pDeviceEnumerator;
  17932. return MA_SUCCESS;
  17933. }
  17934. static WCHAR* ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator* pDeviceEnumerator, ma_device_type deviceType)
  17935. {
  17936. HRESULT hr;
  17937. ma_IMMDevice* pMMDefaultDevice = NULL;
  17938. WCHAR* pDefaultDeviceID = NULL;
  17939. ma_EDataFlow dataFlow;
  17940. ma_ERole role;
  17941. MA_ASSERT(pContext != NULL);
  17942. MA_ASSERT(pDeviceEnumerator != NULL);
  17943. (void)pContext;
  17944. /* Grab the EDataFlow type from the device type. */
  17945. dataFlow = ma_device_type_to_EDataFlow(deviceType);
  17946. /* The role is always eConsole, but we may make this configurable later. */
  17947. role = ma_eConsole;
  17948. hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, dataFlow, role, &pMMDefaultDevice);
  17949. if (FAILED(hr)) {
  17950. return NULL;
  17951. }
  17952. hr = ma_IMMDevice_GetId(pMMDefaultDevice, &pDefaultDeviceID);
  17953. ma_IMMDevice_Release(pMMDefaultDevice);
  17954. pMMDefaultDevice = NULL;
  17955. if (FAILED(hr)) {
  17956. return NULL;
  17957. }
  17958. return pDefaultDeviceID;
  17959. }
  17960. static WCHAR* ma_context_get_default_device_id__wasapi(ma_context* pContext, ma_device_type deviceType) /* Free the returned pointer with ma_CoTaskMemFree() */
  17961. {
  17962. ma_result result;
  17963. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17964. WCHAR* pDefaultDeviceID = NULL;
  17965. MA_ASSERT(pContext != NULL);
  17966. result = ma_context_create_IMMDeviceEnumerator__wasapi(pContext, &pDeviceEnumerator);
  17967. if (result != MA_SUCCESS) {
  17968. return NULL;
  17969. }
  17970. pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType);
  17971. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  17972. return pDefaultDeviceID;
  17973. }
  17974. static ma_result ma_context_get_MMDevice__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IMMDevice** ppMMDevice)
  17975. {
  17976. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17977. HRESULT hr;
  17978. MA_ASSERT(pContext != NULL);
  17979. MA_ASSERT(ppMMDevice != NULL);
  17980. hr = ma_CoCreateInstance(pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  17981. if (FAILED(hr)) {
  17982. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create IMMDeviceEnumerator.\n");
  17983. return ma_result_from_HRESULT(hr);
  17984. }
  17985. if (pDeviceID == NULL) {
  17986. hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, (deviceType == ma_device_type_capture) ? ma_eCapture : ma_eRender, ma_eConsole, ppMMDevice);
  17987. } else {
  17988. hr = ma_IMMDeviceEnumerator_GetDevice(pDeviceEnumerator, pDeviceID->wasapi, ppMMDevice);
  17989. }
  17990. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  17991. if (FAILED(hr)) {
  17992. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve IMMDevice.\n");
  17993. return ma_result_from_HRESULT(hr);
  17994. }
  17995. return MA_SUCCESS;
  17996. }
  17997. static ma_result ma_context_get_device_id_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, ma_device_id* pDeviceID)
  17998. {
  17999. WCHAR* pDeviceIDString;
  18000. HRESULT hr;
  18001. MA_ASSERT(pDeviceID != NULL);
  18002. hr = ma_IMMDevice_GetId(pMMDevice, &pDeviceIDString);
  18003. if (SUCCEEDED(hr)) {
  18004. size_t idlen = ma_strlen_WCHAR(pDeviceIDString);
  18005. if (idlen+1 > ma_countof(pDeviceID->wasapi)) {
  18006. ma_CoTaskMemFree(pContext, pDeviceIDString);
  18007. MA_ASSERT(MA_FALSE); /* NOTE: If this is triggered, please report it. It means the format of the ID must haved change and is too long to fit in our fixed sized buffer. */
  18008. return MA_ERROR;
  18009. }
  18010. MA_COPY_MEMORY(pDeviceID->wasapi, pDeviceIDString, idlen * sizeof(wchar_t));
  18011. pDeviceID->wasapi[idlen] = '\0';
  18012. ma_CoTaskMemFree(pContext, pDeviceIDString);
  18013. return MA_SUCCESS;
  18014. }
  18015. return MA_ERROR;
  18016. }
  18017. static ma_result ma_context_get_device_info_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, WCHAR* pDefaultDeviceID, ma_bool32 onlySimpleInfo, ma_device_info* pInfo)
  18018. {
  18019. ma_result result;
  18020. HRESULT hr;
  18021. MA_ASSERT(pContext != NULL);
  18022. MA_ASSERT(pMMDevice != NULL);
  18023. MA_ASSERT(pInfo != NULL);
  18024. /* ID. */
  18025. result = ma_context_get_device_id_from_MMDevice__wasapi(pContext, pMMDevice, &pInfo->id);
  18026. if (result == MA_SUCCESS) {
  18027. if (pDefaultDeviceID != NULL) {
  18028. if (ma_strcmp_WCHAR(pInfo->id.wasapi, pDefaultDeviceID) == 0) {
  18029. pInfo->isDefault = MA_TRUE;
  18030. }
  18031. }
  18032. }
  18033. /* Description / Friendly Name */
  18034. {
  18035. ma_IPropertyStore *pProperties;
  18036. hr = ma_IMMDevice_OpenPropertyStore(pMMDevice, STGM_READ, &pProperties);
  18037. if (SUCCEEDED(hr)) {
  18038. MA_PROPVARIANT var;
  18039. ma_PropVariantInit(&var);
  18040. hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &var);
  18041. if (SUCCEEDED(hr)) {
  18042. WideCharToMultiByte(CP_UTF8, 0, var.pwszVal, -1, pInfo->name, sizeof(pInfo->name), 0, FALSE);
  18043. ma_PropVariantClear(pContext, &var);
  18044. }
  18045. ma_IPropertyStore_Release(pProperties);
  18046. }
  18047. }
  18048. /* Format */
  18049. if (!onlySimpleInfo) {
  18050. ma_IAudioClient* pAudioClient;
  18051. hr = ma_IMMDevice_Activate(pMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient);
  18052. if (SUCCEEDED(hr)) {
  18053. result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, pMMDevice, pAudioClient, pInfo);
  18054. ma_IAudioClient_Release(pAudioClient);
  18055. return result;
  18056. } else {
  18057. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate audio client for device info retrieval.");
  18058. return ma_result_from_HRESULT(hr);
  18059. }
  18060. }
  18061. return MA_SUCCESS;
  18062. }
  18063. static ma_result ma_context_enumerate_devices_by_type__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator* pDeviceEnumerator, ma_device_type deviceType, ma_enum_devices_callback_proc callback, void* pUserData)
  18064. {
  18065. ma_result result = MA_SUCCESS;
  18066. UINT deviceCount;
  18067. HRESULT hr;
  18068. ma_uint32 iDevice;
  18069. WCHAR* pDefaultDeviceID = NULL;
  18070. ma_IMMDeviceCollection* pDeviceCollection = NULL;
  18071. MA_ASSERT(pContext != NULL);
  18072. MA_ASSERT(callback != NULL);
  18073. /* Grab the default device. We use this to know whether or not flag the returned device info as being the default. */
  18074. pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType);
  18075. /* We need to enumerate the devices which returns a device collection. */
  18076. hr = ma_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, ma_device_type_to_EDataFlow(deviceType), MA_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection);
  18077. if (SUCCEEDED(hr)) {
  18078. hr = ma_IMMDeviceCollection_GetCount(pDeviceCollection, &deviceCount);
  18079. if (FAILED(hr)) {
  18080. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to get device count.\n");
  18081. result = ma_result_from_HRESULT(hr);
  18082. goto done;
  18083. }
  18084. for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
  18085. ma_device_info deviceInfo;
  18086. ma_IMMDevice* pMMDevice;
  18087. MA_ZERO_OBJECT(&deviceInfo);
  18088. hr = ma_IMMDeviceCollection_Item(pDeviceCollection, iDevice, &pMMDevice);
  18089. if (SUCCEEDED(hr)) {
  18090. result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, MA_TRUE, &deviceInfo); /* MA_TRUE = onlySimpleInfo. */
  18091. ma_IMMDevice_Release(pMMDevice);
  18092. if (result == MA_SUCCESS) {
  18093. ma_bool32 cbResult = callback(pContext, deviceType, &deviceInfo, pUserData);
  18094. if (cbResult == MA_FALSE) {
  18095. break;
  18096. }
  18097. }
  18098. }
  18099. }
  18100. }
  18101. done:
  18102. if (pDefaultDeviceID != NULL) {
  18103. ma_CoTaskMemFree(pContext, pDefaultDeviceID);
  18104. pDefaultDeviceID = NULL;
  18105. }
  18106. if (pDeviceCollection != NULL) {
  18107. ma_IMMDeviceCollection_Release(pDeviceCollection);
  18108. pDeviceCollection = NULL;
  18109. }
  18110. return result;
  18111. }
  18112. static ma_result ma_context_get_IAudioClient_Desktop__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, MA_PROPVARIANT* pActivationParams, ma_IAudioClient** ppAudioClient, ma_IMMDevice** ppMMDevice)
  18113. {
  18114. ma_result result;
  18115. HRESULT hr;
  18116. MA_ASSERT(pContext != NULL);
  18117. MA_ASSERT(ppAudioClient != NULL);
  18118. MA_ASSERT(ppMMDevice != NULL);
  18119. result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, ppMMDevice);
  18120. if (result != MA_SUCCESS) {
  18121. return result;
  18122. }
  18123. hr = ma_IMMDevice_Activate(*ppMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, pActivationParams, (void**)ppAudioClient);
  18124. if (FAILED(hr)) {
  18125. return ma_result_from_HRESULT(hr);
  18126. }
  18127. return MA_SUCCESS;
  18128. }
  18129. #else
  18130. static ma_result ma_context_get_IAudioClient_UWP__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, MA_PROPVARIANT* pActivationParams, ma_IAudioClient** ppAudioClient, ma_IUnknown** ppActivatedInterface)
  18131. {
  18132. ma_IActivateAudioInterfaceAsyncOperation *pAsyncOp = NULL;
  18133. ma_completion_handler_uwp completionHandler;
  18134. IID iid;
  18135. WCHAR* iidStr;
  18136. HRESULT hr;
  18137. ma_result result;
  18138. HRESULT activateResult;
  18139. ma_IUnknown* pActivatedInterface;
  18140. MA_ASSERT(pContext != NULL);
  18141. MA_ASSERT(ppAudioClient != NULL);
  18142. if (pDeviceID != NULL) {
  18143. iidStr = (WCHAR*)pDeviceID->wasapi;
  18144. } else {
  18145. if (deviceType == ma_device_type_capture) {
  18146. iid = MA_IID_DEVINTERFACE_AUDIO_CAPTURE;
  18147. } else {
  18148. iid = MA_IID_DEVINTERFACE_AUDIO_RENDER;
  18149. }
  18150. #if defined(__cplusplus)
  18151. hr = StringFromIID(iid, &iidStr);
  18152. #else
  18153. hr = StringFromIID(&iid, &iidStr);
  18154. #endif
  18155. if (FAILED(hr)) {
  18156. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to convert device IID to string for ActivateAudioInterfaceAsync(). Out of memory.\n");
  18157. return ma_result_from_HRESULT(hr);
  18158. }
  18159. }
  18160. result = ma_completion_handler_uwp_init(&completionHandler);
  18161. if (result != MA_SUCCESS) {
  18162. ma_CoTaskMemFree(pContext, iidStr);
  18163. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for waiting for ActivateAudioInterfaceAsync().\n");
  18164. return result;
  18165. }
  18166. hr = ((MA_PFN_ActivateAudioInterfaceAsync)pContext->wasapi.ActivateAudioInterfaceAsync)(iidStr, &MA_IID_IAudioClient, pActivationParams, (ma_IActivateAudioInterfaceCompletionHandler*)&completionHandler, (ma_IActivateAudioInterfaceAsyncOperation**)&pAsyncOp);
  18167. if (FAILED(hr)) {
  18168. ma_completion_handler_uwp_uninit(&completionHandler);
  18169. ma_CoTaskMemFree(pContext, iidStr);
  18170. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] ActivateAudioInterfaceAsync() failed.\n");
  18171. return ma_result_from_HRESULT(hr);
  18172. }
  18173. if (pDeviceID == NULL) {
  18174. ma_CoTaskMemFree(pContext, iidStr);
  18175. }
  18176. /* Wait for the async operation for finish. */
  18177. ma_completion_handler_uwp_wait(&completionHandler);
  18178. ma_completion_handler_uwp_uninit(&completionHandler);
  18179. hr = ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(pAsyncOp, &activateResult, &pActivatedInterface);
  18180. ma_IActivateAudioInterfaceAsyncOperation_Release(pAsyncOp);
  18181. if (FAILED(hr) || FAILED(activateResult)) {
  18182. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate device.\n");
  18183. return FAILED(hr) ? ma_result_from_HRESULT(hr) : ma_result_from_HRESULT(activateResult);
  18184. }
  18185. /* Here is where we grab the IAudioClient interface. */
  18186. hr = ma_IUnknown_QueryInterface(pActivatedInterface, &MA_IID_IAudioClient, (void**)ppAudioClient);
  18187. if (FAILED(hr)) {
  18188. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to query IAudioClient interface.\n");
  18189. return ma_result_from_HRESULT(hr);
  18190. }
  18191. if (ppActivatedInterface) {
  18192. *ppActivatedInterface = pActivatedInterface;
  18193. } else {
  18194. ma_IUnknown_Release(pActivatedInterface);
  18195. }
  18196. return MA_SUCCESS;
  18197. }
  18198. #endif
  18199. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ne-audioclientactivationparams-audioclient_activation_type */
  18200. typedef enum
  18201. {
  18202. MA_AUDIOCLIENT_ACTIVATION_TYPE_DEFAULT,
  18203. MA_AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK
  18204. } MA_AUDIOCLIENT_ACTIVATION_TYPE;
  18205. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ne-audioclientactivationparams-process_loopback_mode */
  18206. typedef enum
  18207. {
  18208. MA_PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
  18209. MA_PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE
  18210. } MA_PROCESS_LOOPBACK_MODE;
  18211. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params */
  18212. typedef struct
  18213. {
  18214. DWORD TargetProcessId;
  18215. MA_PROCESS_LOOPBACK_MODE ProcessLoopbackMode;
  18216. } MA_AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS;
  18217. #if defined(_MSC_VER) && !defined(__clang__)
  18218. #pragma warning(push)
  18219. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  18220. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  18221. #pragma GCC diagnostic push
  18222. #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  18223. #if defined(__clang__)
  18224. #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
  18225. #endif
  18226. #endif
  18227. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_activation_params */
  18228. typedef struct
  18229. {
  18230. MA_AUDIOCLIENT_ACTIVATION_TYPE ActivationType;
  18231. union
  18232. {
  18233. MA_AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS ProcessLoopbackParams;
  18234. };
  18235. } MA_AUDIOCLIENT_ACTIVATION_PARAMS;
  18236. #if defined(_MSC_VER) && !defined(__clang__)
  18237. #pragma warning(pop)
  18238. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  18239. #pragma GCC diagnostic pop
  18240. #endif
  18241. #define MA_VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK L"VAD\\Process_Loopback"
  18242. static ma_result ma_context_get_IAudioClient__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_uint32 loopbackProcessID, ma_bool32 loopbackProcessExclude, ma_IAudioClient** ppAudioClient, ma_WASAPIDeviceInterface** ppDeviceInterface)
  18243. {
  18244. ma_result result;
  18245. ma_bool32 usingProcessLoopback = MA_FALSE;
  18246. MA_AUDIOCLIENT_ACTIVATION_PARAMS audioclientActivationParams;
  18247. MA_PROPVARIANT activationParams;
  18248. MA_PROPVARIANT* pActivationParams = NULL;
  18249. ma_device_id virtualDeviceID;
  18250. /* Activation parameters specific to loopback mode. Note that process-specific loopback will only work when a default device ID is specified. */
  18251. if (deviceType == ma_device_type_loopback && loopbackProcessID != 0 && pDeviceID == NULL) {
  18252. usingProcessLoopback = MA_TRUE;
  18253. }
  18254. if (usingProcessLoopback) {
  18255. MA_ZERO_OBJECT(&audioclientActivationParams);
  18256. audioclientActivationParams.ActivationType = MA_AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK;
  18257. audioclientActivationParams.ProcessLoopbackParams.ProcessLoopbackMode = (loopbackProcessExclude) ? MA_PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE : MA_PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE;
  18258. audioclientActivationParams.ProcessLoopbackParams.TargetProcessId = (DWORD)loopbackProcessID;
  18259. ma_PropVariantInit(&activationParams);
  18260. activationParams.vt = MA_VT_BLOB;
  18261. activationParams.blob.cbSize = sizeof(audioclientActivationParams);
  18262. activationParams.blob.pBlobData = (BYTE*)&audioclientActivationParams;
  18263. pActivationParams = &activationParams;
  18264. /* When requesting a specific device ID we need to use a special device ID. */
  18265. MA_COPY_MEMORY(virtualDeviceID.wasapi, MA_VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, (wcslen(MA_VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK) + 1) * sizeof(wchar_t)); /* +1 for the null terminator. */
  18266. pDeviceID = &virtualDeviceID;
  18267. } else {
  18268. pActivationParams = NULL; /* No activation parameters required. */
  18269. }
  18270. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18271. result = ma_context_get_IAudioClient_Desktop__wasapi(pContext, deviceType, pDeviceID, pActivationParams, ppAudioClient, ppDeviceInterface);
  18272. #else
  18273. result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, pActivationParams, ppAudioClient, ppDeviceInterface);
  18274. #endif
  18275. /*
  18276. If loopback mode was requested with a process ID and initialization failed, it could be because it's
  18277. trying to run on an older version of Windows where it's not supported. We need to let the caller
  18278. know about this with a log message.
  18279. */
  18280. if (result != MA_SUCCESS) {
  18281. if (usingProcessLoopback) {
  18282. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Loopback mode requested to %s process ID %u, but initialization failed. Support for this feature begins with Windows 10 Build 20348. Confirm your version of Windows or consider not using process-specific loopback.\n", (loopbackProcessExclude) ? "exclude" : "include", loopbackProcessID);
  18283. }
  18284. }
  18285. return result;
  18286. }
  18287. static ma_result ma_context_enumerate_devices__wasapi(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  18288. {
  18289. /* Different enumeration for desktop and UWP. */
  18290. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18291. /* Desktop */
  18292. HRESULT hr;
  18293. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  18294. hr = ma_CoCreateInstance(pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  18295. if (FAILED(hr)) {
  18296. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.");
  18297. return ma_result_from_HRESULT(hr);
  18298. }
  18299. ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_playback, callback, pUserData);
  18300. ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_capture, callback, pUserData);
  18301. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  18302. #else
  18303. /*
  18304. UWP
  18305. The MMDevice API is only supported on desktop applications. For now, while I'm still figuring out how to properly enumerate
  18306. over devices without using MMDevice, I'm restricting devices to defaults.
  18307. Hint: DeviceInformation::FindAllAsync() with DeviceClass.AudioCapture/AudioRender. https://blogs.windows.com/buildingapps/2014/05/15/real-time-audio-in-windows-store-and-windows-phone-apps/
  18308. */
  18309. if (callback) {
  18310. ma_bool32 cbResult = MA_TRUE;
  18311. /* Playback. */
  18312. if (cbResult) {
  18313. ma_device_info deviceInfo;
  18314. MA_ZERO_OBJECT(&deviceInfo);
  18315. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  18316. deviceInfo.isDefault = MA_TRUE;
  18317. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  18318. }
  18319. /* Capture. */
  18320. if (cbResult) {
  18321. ma_device_info deviceInfo;
  18322. MA_ZERO_OBJECT(&deviceInfo);
  18323. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  18324. deviceInfo.isDefault = MA_TRUE;
  18325. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  18326. }
  18327. }
  18328. #endif
  18329. return MA_SUCCESS;
  18330. }
  18331. static ma_result ma_context_get_device_info__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  18332. {
  18333. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18334. ma_result result;
  18335. ma_IMMDevice* pMMDevice = NULL;
  18336. WCHAR* pDefaultDeviceID = NULL;
  18337. result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, &pMMDevice);
  18338. if (result != MA_SUCCESS) {
  18339. return result;
  18340. }
  18341. /* We need the default device ID so we can set the isDefault flag in the device info. */
  18342. pDefaultDeviceID = ma_context_get_default_device_id__wasapi(pContext, deviceType);
  18343. result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, MA_FALSE, pDeviceInfo); /* MA_FALSE = !onlySimpleInfo. */
  18344. if (pDefaultDeviceID != NULL) {
  18345. ma_CoTaskMemFree(pContext, pDefaultDeviceID);
  18346. pDefaultDeviceID = NULL;
  18347. }
  18348. ma_IMMDevice_Release(pMMDevice);
  18349. return result;
  18350. #else
  18351. ma_IAudioClient* pAudioClient;
  18352. ma_result result;
  18353. /* UWP currently only uses default devices. */
  18354. if (deviceType == ma_device_type_playback) {
  18355. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  18356. } else {
  18357. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  18358. }
  18359. result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, NULL, &pAudioClient, NULL);
  18360. if (result != MA_SUCCESS) {
  18361. return result;
  18362. }
  18363. result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, NULL, pAudioClient, pDeviceInfo);
  18364. pDeviceInfo->isDefault = MA_TRUE; /* UWP only supports default devices. */
  18365. ma_IAudioClient_Release(pAudioClient);
  18366. return result;
  18367. #endif
  18368. }
  18369. static ma_result ma_device_uninit__wasapi(ma_device* pDevice)
  18370. {
  18371. MA_ASSERT(pDevice != NULL);
  18372. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18373. if (pDevice->wasapi.pDeviceEnumerator) {
  18374. ((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator)->lpVtbl->UnregisterEndpointNotificationCallback((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator, &pDevice->wasapi.notificationClient);
  18375. ma_IMMDeviceEnumerator_Release((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator);
  18376. }
  18377. #endif
  18378. if (pDevice->wasapi.pRenderClient) {
  18379. if (pDevice->wasapi.pMappedBufferPlayback != NULL) {
  18380. ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0);
  18381. pDevice->wasapi.pMappedBufferPlayback = NULL;
  18382. pDevice->wasapi.mappedBufferPlaybackCap = 0;
  18383. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  18384. }
  18385. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
  18386. }
  18387. if (pDevice->wasapi.pCaptureClient) {
  18388. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  18389. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  18390. pDevice->wasapi.pMappedBufferCapture = NULL;
  18391. pDevice->wasapi.mappedBufferCaptureCap = 0;
  18392. pDevice->wasapi.mappedBufferCaptureLen = 0;
  18393. }
  18394. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  18395. }
  18396. if (pDevice->wasapi.pAudioClientPlayback) {
  18397. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  18398. }
  18399. if (pDevice->wasapi.pAudioClientCapture) {
  18400. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  18401. }
  18402. if (pDevice->wasapi.hEventPlayback) {
  18403. CloseHandle((HANDLE)pDevice->wasapi.hEventPlayback);
  18404. }
  18405. if (pDevice->wasapi.hEventCapture) {
  18406. CloseHandle((HANDLE)pDevice->wasapi.hEventCapture);
  18407. }
  18408. return MA_SUCCESS;
  18409. }
  18410. typedef struct
  18411. {
  18412. /* Input. */
  18413. ma_format formatIn;
  18414. ma_uint32 channelsIn;
  18415. ma_uint32 sampleRateIn;
  18416. ma_channel channelMapIn[MA_MAX_CHANNELS];
  18417. ma_uint32 periodSizeInFramesIn;
  18418. ma_uint32 periodSizeInMillisecondsIn;
  18419. ma_uint32 periodsIn;
  18420. ma_share_mode shareMode;
  18421. ma_performance_profile performanceProfile;
  18422. ma_bool32 noAutoConvertSRC;
  18423. ma_bool32 noDefaultQualitySRC;
  18424. ma_bool32 noHardwareOffloading;
  18425. ma_uint32 loopbackProcessID;
  18426. ma_bool32 loopbackProcessExclude;
  18427. /* Output. */
  18428. ma_IAudioClient* pAudioClient;
  18429. ma_IAudioRenderClient* pRenderClient;
  18430. ma_IAudioCaptureClient* pCaptureClient;
  18431. ma_format formatOut;
  18432. ma_uint32 channelsOut;
  18433. ma_uint32 sampleRateOut;
  18434. ma_channel channelMapOut[MA_MAX_CHANNELS];
  18435. ma_uint32 periodSizeInFramesOut;
  18436. ma_uint32 periodsOut;
  18437. ma_bool32 usingAudioClient3;
  18438. char deviceName[256];
  18439. ma_device_id id;
  18440. } ma_device_init_internal_data__wasapi;
  18441. static ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_init_internal_data__wasapi* pData)
  18442. {
  18443. HRESULT hr;
  18444. ma_result result = MA_SUCCESS;
  18445. const char* errorMsg = "";
  18446. MA_AUDCLNT_SHAREMODE shareMode = MA_AUDCLNT_SHAREMODE_SHARED;
  18447. DWORD streamFlags = 0;
  18448. MA_REFERENCE_TIME periodDurationInMicroseconds;
  18449. ma_bool32 wasInitializedUsingIAudioClient3 = MA_FALSE;
  18450. MA_WAVEFORMATEXTENSIBLE wf;
  18451. ma_WASAPIDeviceInterface* pDeviceInterface = NULL;
  18452. ma_IAudioClient2* pAudioClient2;
  18453. ma_uint32 nativeSampleRate;
  18454. ma_bool32 usingProcessLoopback = MA_FALSE;
  18455. MA_ASSERT(pContext != NULL);
  18456. MA_ASSERT(pData != NULL);
  18457. /* This function is only used to initialize one device type: either playback, capture or loopback. Never full-duplex. */
  18458. if (deviceType == ma_device_type_duplex) {
  18459. return MA_INVALID_ARGS;
  18460. }
  18461. usingProcessLoopback = deviceType == ma_device_type_loopback && pData->loopbackProcessID != 0 && pDeviceID == NULL;
  18462. pData->pAudioClient = NULL;
  18463. pData->pRenderClient = NULL;
  18464. pData->pCaptureClient = NULL;
  18465. streamFlags = MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  18466. if (!pData->noAutoConvertSRC && pData->sampleRateIn != 0 && pData->shareMode != ma_share_mode_exclusive) { /* <-- Exclusive streams must use the native sample rate. */
  18467. streamFlags |= MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM;
  18468. }
  18469. if (!pData->noDefaultQualitySRC && pData->sampleRateIn != 0 && (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) != 0) {
  18470. streamFlags |= MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
  18471. }
  18472. if (deviceType == ma_device_type_loopback) {
  18473. streamFlags |= MA_AUDCLNT_STREAMFLAGS_LOOPBACK;
  18474. }
  18475. result = ma_context_get_IAudioClient__wasapi(pContext, deviceType, pDeviceID, pData->loopbackProcessID, pData->loopbackProcessExclude, &pData->pAudioClient, &pDeviceInterface);
  18476. if (result != MA_SUCCESS) {
  18477. goto done;
  18478. }
  18479. MA_ZERO_OBJECT(&wf);
  18480. /* Try enabling hardware offloading. */
  18481. if (!pData->noHardwareOffloading) {
  18482. hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient2, (void**)&pAudioClient2);
  18483. if (SUCCEEDED(hr)) {
  18484. BOOL isHardwareOffloadingSupported = 0;
  18485. hr = ma_IAudioClient2_IsOffloadCapable(pAudioClient2, MA_AudioCategory_Other, &isHardwareOffloadingSupported);
  18486. if (SUCCEEDED(hr) && isHardwareOffloadingSupported) {
  18487. ma_AudioClientProperties clientProperties;
  18488. MA_ZERO_OBJECT(&clientProperties);
  18489. clientProperties.cbSize = sizeof(clientProperties);
  18490. clientProperties.bIsOffload = 1;
  18491. clientProperties.eCategory = MA_AudioCategory_Other;
  18492. ma_IAudioClient2_SetClientProperties(pAudioClient2, &clientProperties);
  18493. }
  18494. pAudioClient2->lpVtbl->Release(pAudioClient2);
  18495. }
  18496. }
  18497. /* Here is where we try to determine the best format to use with the device. If the client if wanting exclusive mode, first try finding the best format for that. If this fails, fall back to shared mode. */
  18498. result = MA_FORMAT_NOT_SUPPORTED;
  18499. if (pData->shareMode == ma_share_mode_exclusive) {
  18500. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18501. /* In exclusive mode on desktop we always use the backend's native format. */
  18502. ma_IPropertyStore* pStore = NULL;
  18503. hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pStore);
  18504. if (SUCCEEDED(hr)) {
  18505. MA_PROPVARIANT prop;
  18506. ma_PropVariantInit(&prop);
  18507. hr = ma_IPropertyStore_GetValue(pStore, &MA_PKEY_AudioEngine_DeviceFormat, &prop);
  18508. if (SUCCEEDED(hr)) {
  18509. MA_WAVEFORMATEX* pActualFormat = (MA_WAVEFORMATEX*)prop.blob.pBlobData;
  18510. hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pData->pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pActualFormat, NULL);
  18511. if (SUCCEEDED(hr)) {
  18512. MA_COPY_MEMORY(&wf, pActualFormat, sizeof(MA_WAVEFORMATEXTENSIBLE));
  18513. }
  18514. ma_PropVariantClear(pContext, &prop);
  18515. }
  18516. ma_IPropertyStore_Release(pStore);
  18517. }
  18518. #else
  18519. /*
  18520. I do not know how to query the device's native format on UWP so for now I'm just disabling support for
  18521. exclusive mode. The alternative is to enumerate over different formats and check IsFormatSupported()
  18522. until you find one that works.
  18523. TODO: Add support for exclusive mode to UWP.
  18524. */
  18525. hr = S_FALSE;
  18526. #endif
  18527. if (hr == S_OK) {
  18528. shareMode = MA_AUDCLNT_SHAREMODE_EXCLUSIVE;
  18529. result = MA_SUCCESS;
  18530. } else {
  18531. result = MA_SHARE_MODE_NOT_SUPPORTED;
  18532. }
  18533. } else {
  18534. /* In shared mode we are always using the format reported by the operating system. */
  18535. MA_WAVEFORMATEXTENSIBLE* pNativeFormat = NULL;
  18536. hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pData->pAudioClient, (MA_WAVEFORMATEX**)&pNativeFormat);
  18537. if (hr != S_OK) {
  18538. /* When using process-specific loopback, GetMixFormat() seems to always fail. */
  18539. if (usingProcessLoopback) {
  18540. wf.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
  18541. wf.nChannels = 2;
  18542. wf.nSamplesPerSec = 44100;
  18543. wf.wBitsPerSample = 32;
  18544. wf.nBlockAlign = wf.nChannels * wf.wBitsPerSample / 8;
  18545. wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
  18546. wf.cbSize = sizeof(MA_WAVEFORMATEX);
  18547. result = MA_SUCCESS;
  18548. } else {
  18549. result = MA_FORMAT_NOT_SUPPORTED;
  18550. }
  18551. } else {
  18552. /*
  18553. I've seen cases where cbSize will be set to sizeof(WAVEFORMATEX) even though the structure itself
  18554. is given the format tag of WAVE_FORMAT_EXTENSIBLE. If the format tag is WAVE_FORMAT_EXTENSIBLE
  18555. want to make sure we copy the whole WAVEFORMATEXTENSIBLE structure. Otherwise we'll have to be
  18556. safe and only copy the WAVEFORMATEX part.
  18557. */
  18558. if (pNativeFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  18559. MA_COPY_MEMORY(&wf, pNativeFormat, sizeof(MA_WAVEFORMATEXTENSIBLE));
  18560. } else {
  18561. /* I've seen a case where cbSize was set to 0. Assume sizeof(WAVEFORMATEX) in this case. */
  18562. size_t cbSize = pNativeFormat->cbSize;
  18563. if (cbSize == 0) {
  18564. cbSize = sizeof(MA_WAVEFORMATEX);
  18565. }
  18566. /* Make sure we don't copy more than the capacity of `wf`. */
  18567. if (cbSize > sizeof(wf)) {
  18568. cbSize = sizeof(wf);
  18569. }
  18570. MA_COPY_MEMORY(&wf, pNativeFormat, cbSize);
  18571. }
  18572. result = MA_SUCCESS;
  18573. }
  18574. ma_CoTaskMemFree(pContext, pNativeFormat);
  18575. shareMode = MA_AUDCLNT_SHAREMODE_SHARED;
  18576. }
  18577. /* Return an error if we still haven't found a format. */
  18578. if (result != MA_SUCCESS) {
  18579. errorMsg = "[WASAPI] Failed to find best device mix format.";
  18580. goto done;
  18581. }
  18582. /*
  18583. Override the native sample rate with the one requested by the caller, but only if we're not using the default sample rate. We'll use
  18584. WASAPI to perform the sample rate conversion.
  18585. */
  18586. nativeSampleRate = wf.nSamplesPerSec;
  18587. if (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) {
  18588. wf.nSamplesPerSec = (pData->sampleRateIn != 0) ? pData->sampleRateIn : MA_DEFAULT_SAMPLE_RATE;
  18589. wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
  18590. }
  18591. pData->formatOut = ma_format_from_WAVEFORMATEX((MA_WAVEFORMATEX*)&wf);
  18592. if (pData->formatOut == ma_format_unknown) {
  18593. /*
  18594. The format isn't supported. This is almost certainly because the exclusive mode format isn't supported by miniaudio. We need to return MA_SHARE_MODE_NOT_SUPPORTED
  18595. in this case so that the caller can detect it and fall back to shared mode if desired. We should never get here if shared mode was requested, but just for
  18596. completeness we'll check for it and return MA_FORMAT_NOT_SUPPORTED.
  18597. */
  18598. if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) {
  18599. result = MA_SHARE_MODE_NOT_SUPPORTED;
  18600. } else {
  18601. result = MA_FORMAT_NOT_SUPPORTED;
  18602. }
  18603. errorMsg = "[WASAPI] Native format not supported.";
  18604. goto done;
  18605. }
  18606. pData->channelsOut = wf.nChannels;
  18607. pData->sampleRateOut = wf.nSamplesPerSec;
  18608. /*
  18609. Get the internal channel map based on the channel mask. There is a possibility that GetMixFormat() returns
  18610. a WAVEFORMATEX instead of a WAVEFORMATEXTENSIBLE, in which case the channel mask will be undefined. In this
  18611. case we'll just use the default channel map.
  18612. */
  18613. if (wf.wFormatTag == WAVE_FORMAT_EXTENSIBLE || wf.cbSize >= sizeof(MA_WAVEFORMATEXTENSIBLE)) {
  18614. ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pData->channelsOut, pData->channelMapOut);
  18615. } else {
  18616. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut);
  18617. }
  18618. /* Period size. */
  18619. pData->periodsOut = (pData->periodsIn != 0) ? pData->periodsIn : MA_DEFAULT_PERIODS;
  18620. pData->periodSizeInFramesOut = pData->periodSizeInFramesIn;
  18621. if (pData->periodSizeInFramesOut == 0) {
  18622. if (pData->periodSizeInMillisecondsIn == 0) {
  18623. if (pData->performanceProfile == ma_performance_profile_low_latency) {
  18624. pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, wf.nSamplesPerSec);
  18625. } else {
  18626. pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, wf.nSamplesPerSec);
  18627. }
  18628. } else {
  18629. pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, wf.nSamplesPerSec);
  18630. }
  18631. }
  18632. periodDurationInMicroseconds = ((ma_uint64)pData->periodSizeInFramesOut * 1000 * 1000) / wf.nSamplesPerSec;
  18633. /* Slightly different initialization for shared and exclusive modes. We try exclusive mode first, and if it fails, fall back to shared mode. */
  18634. if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) {
  18635. MA_REFERENCE_TIME bufferDuration = periodDurationInMicroseconds * pData->periodsOut * 10;
  18636. /*
  18637. If the periodicy is too small, Initialize() will fail with AUDCLNT_E_INVALID_DEVICE_PERIOD. In this case we should just keep increasing
  18638. it and trying it again.
  18639. */
  18640. hr = E_FAIL;
  18641. for (;;) {
  18642. hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, bufferDuration, (MA_WAVEFORMATEX*)&wf, NULL);
  18643. if (hr == MA_AUDCLNT_E_INVALID_DEVICE_PERIOD) {
  18644. if (bufferDuration > 500*10000) {
  18645. break;
  18646. } else {
  18647. if (bufferDuration == 0) { /* <-- Just a sanity check to prevent an infinit loop. Should never happen, but it makes me feel better. */
  18648. break;
  18649. }
  18650. bufferDuration = bufferDuration * 2;
  18651. continue;
  18652. }
  18653. } else {
  18654. break;
  18655. }
  18656. }
  18657. if (hr == MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) {
  18658. ma_uint32 bufferSizeInFrames;
  18659. hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames);
  18660. if (SUCCEEDED(hr)) {
  18661. bufferDuration = (MA_REFERENCE_TIME)((10000.0 * 1000 / wf.nSamplesPerSec * bufferSizeInFrames) + 0.5);
  18662. /* Unfortunately we need to release and re-acquire the audio client according to MSDN. Seems silly - why not just call IAudioClient_Initialize() again?! */
  18663. ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient);
  18664. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18665. hr = ma_IMMDevice_Activate(pDeviceInterface, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pData->pAudioClient);
  18666. #else
  18667. hr = ma_IUnknown_QueryInterface(pDeviceInterface, &MA_IID_IAudioClient, (void**)&pData->pAudioClient);
  18668. #endif
  18669. if (SUCCEEDED(hr)) {
  18670. hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, bufferDuration, (MA_WAVEFORMATEX*)&wf, NULL);
  18671. }
  18672. }
  18673. }
  18674. if (FAILED(hr)) {
  18675. /* Failed to initialize in exclusive mode. Don't fall back to shared mode - instead tell the client about it. They can reinitialize in shared mode if they want. */
  18676. if (hr == E_ACCESSDENIED) {
  18677. errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Access denied.", result = MA_ACCESS_DENIED;
  18678. } else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) {
  18679. errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Device in use.", result = MA_BUSY;
  18680. } else {
  18681. errorMsg = "[WASAPI] Failed to initialize device in exclusive mode."; result = ma_result_from_HRESULT(hr);
  18682. }
  18683. goto done;
  18684. }
  18685. }
  18686. if (shareMode == MA_AUDCLNT_SHAREMODE_SHARED) {
  18687. /*
  18688. Low latency shared mode via IAudioClient3.
  18689. NOTE
  18690. ====
  18691. Contrary to the documentation on MSDN (https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-initializesharedaudiostream), the
  18692. use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM and AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY with IAudioClient3_InitializeSharedAudioStream() absolutely does not work. Using
  18693. any of these flags will result in HRESULT code 0x88890021. The other problem is that calling IAudioClient3_GetSharedModeEnginePeriod() with a sample rate different to
  18694. that returned by IAudioClient_GetMixFormat() also results in an error. I'm therefore disabling low-latency shared mode with AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM.
  18695. */
  18696. #ifndef MA_WASAPI_NO_LOW_LATENCY_SHARED_MODE
  18697. {
  18698. if ((streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) == 0 || nativeSampleRate == wf.nSamplesPerSec) {
  18699. ma_IAudioClient3* pAudioClient3 = NULL;
  18700. hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient3, (void**)&pAudioClient3);
  18701. if (SUCCEEDED(hr)) {
  18702. ma_uint32 defaultPeriodInFrames;
  18703. ma_uint32 fundamentalPeriodInFrames;
  18704. ma_uint32 minPeriodInFrames;
  18705. ma_uint32 maxPeriodInFrames;
  18706. hr = ma_IAudioClient3_GetSharedModeEnginePeriod(pAudioClient3, (MA_WAVEFORMATEX*)&wf, &defaultPeriodInFrames, &fundamentalPeriodInFrames, &minPeriodInFrames, &maxPeriodInFrames);
  18707. if (SUCCEEDED(hr)) {
  18708. ma_uint32 desiredPeriodInFrames = pData->periodSizeInFramesOut;
  18709. ma_uint32 actualPeriodInFrames = desiredPeriodInFrames;
  18710. /* Make sure the period size is a multiple of fundamentalPeriodInFrames. */
  18711. actualPeriodInFrames = actualPeriodInFrames / fundamentalPeriodInFrames;
  18712. actualPeriodInFrames = actualPeriodInFrames * fundamentalPeriodInFrames;
  18713. /* The period needs to be clamped between minPeriodInFrames and maxPeriodInFrames. */
  18714. actualPeriodInFrames = ma_clamp(actualPeriodInFrames, minPeriodInFrames, maxPeriodInFrames);
  18715. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Trying IAudioClient3_InitializeSharedAudioStream(actualPeriodInFrames=%d)\n", actualPeriodInFrames);
  18716. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " defaultPeriodInFrames=%d\n", defaultPeriodInFrames);
  18717. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " fundamentalPeriodInFrames=%d\n", fundamentalPeriodInFrames);
  18718. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " minPeriodInFrames=%d\n", minPeriodInFrames);
  18719. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " maxPeriodInFrames=%d\n", maxPeriodInFrames);
  18720. /* If the client requested a largish buffer than we don't actually want to use low latency shared mode because it forces small buffers. */
  18721. if (actualPeriodInFrames >= desiredPeriodInFrames) {
  18722. /*
  18723. MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY must not be in the stream flags. If either of these are specified,
  18724. IAudioClient3_InitializeSharedAudioStream() will fail.
  18725. */
  18726. hr = ma_IAudioClient3_InitializeSharedAudioStream(pAudioClient3, streamFlags & ~(MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY), actualPeriodInFrames, (MA_WAVEFORMATEX*)&wf, NULL);
  18727. if (SUCCEEDED(hr)) {
  18728. wasInitializedUsingIAudioClient3 = MA_TRUE;
  18729. pData->periodSizeInFramesOut = actualPeriodInFrames;
  18730. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Using IAudioClient3\n");
  18731. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " periodSizeInFramesOut=%d\n", pData->periodSizeInFramesOut);
  18732. } else {
  18733. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] IAudioClient3_InitializeSharedAudioStream failed. Falling back to IAudioClient.\n");
  18734. }
  18735. } else {
  18736. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Not using IAudioClient3 because the desired period size is larger than the maximum supported by IAudioClient3.\n");
  18737. }
  18738. } else {
  18739. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] IAudioClient3_GetSharedModeEnginePeriod failed. Falling back to IAudioClient.\n");
  18740. }
  18741. ma_IAudioClient3_Release(pAudioClient3);
  18742. pAudioClient3 = NULL;
  18743. }
  18744. }
  18745. }
  18746. #else
  18747. {
  18748. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Not using IAudioClient3 because MA_WASAPI_NO_LOW_LATENCY_SHARED_MODE is enabled.\n");
  18749. }
  18750. #endif
  18751. /* If we don't have an IAudioClient3 then we need to use the normal initialization routine. */
  18752. if (!wasInitializedUsingIAudioClient3) {
  18753. MA_REFERENCE_TIME bufferDuration = periodDurationInMicroseconds * pData->periodsOut * 10; /* <-- Multiply by 10 for microseconds to 100-nanoseconds. */
  18754. hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, 0, (const MA_WAVEFORMATEX*)&wf, NULL);
  18755. if (FAILED(hr)) {
  18756. if (hr == E_ACCESSDENIED) {
  18757. errorMsg = "[WASAPI] Failed to initialize device. Access denied.", result = MA_ACCESS_DENIED;
  18758. } else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) {
  18759. errorMsg = "[WASAPI] Failed to initialize device. Device in use.", result = MA_BUSY;
  18760. } else {
  18761. errorMsg = "[WASAPI] Failed to initialize device.", result = ma_result_from_HRESULT(hr);
  18762. }
  18763. goto done;
  18764. }
  18765. }
  18766. }
  18767. if (!wasInitializedUsingIAudioClient3) {
  18768. ma_uint32 bufferSizeInFrames = 0;
  18769. hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames);
  18770. if (FAILED(hr)) {
  18771. errorMsg = "[WASAPI] Failed to get audio client's actual buffer size.", result = ma_result_from_HRESULT(hr);
  18772. goto done;
  18773. }
  18774. /*
  18775. When using process loopback mode, retrieval of the buffer size seems to result in totally
  18776. incorrect values. In this case we'll just assume it's the same size as what we requested
  18777. when we initialized the client.
  18778. */
  18779. if (usingProcessLoopback) {
  18780. bufferSizeInFrames = (ma_uint32)((periodDurationInMicroseconds * pData->periodsOut) * pData->sampleRateOut / 1000000);
  18781. }
  18782. pData->periodSizeInFramesOut = bufferSizeInFrames / pData->periodsOut;
  18783. }
  18784. pData->usingAudioClient3 = wasInitializedUsingIAudioClient3;
  18785. if (deviceType == ma_device_type_playback) {
  18786. result = ma_device_create_IAudioClient_service__wasapi(pContext, deviceType, (ma_IAudioClient*)pData->pAudioClient, (void**)&pData->pRenderClient);
  18787. } else {
  18788. result = ma_device_create_IAudioClient_service__wasapi(pContext, deviceType, (ma_IAudioClient*)pData->pAudioClient, (void**)&pData->pCaptureClient);
  18789. }
  18790. /*if (FAILED(hr)) {*/
  18791. if (result != MA_SUCCESS) {
  18792. errorMsg = "[WASAPI] Failed to get audio client service.";
  18793. goto done;
  18794. }
  18795. /* Grab the name of the device. */
  18796. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18797. {
  18798. ma_IPropertyStore *pProperties;
  18799. hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pProperties);
  18800. if (SUCCEEDED(hr)) {
  18801. MA_PROPVARIANT varName;
  18802. ma_PropVariantInit(&varName);
  18803. hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &varName);
  18804. if (SUCCEEDED(hr)) {
  18805. WideCharToMultiByte(CP_UTF8, 0, varName.pwszVal, -1, pData->deviceName, sizeof(pData->deviceName), 0, FALSE);
  18806. ma_PropVariantClear(pContext, &varName);
  18807. }
  18808. ma_IPropertyStore_Release(pProperties);
  18809. }
  18810. }
  18811. #endif
  18812. /*
  18813. For the WASAPI backend we need to know the actual IDs of the device in order to do automatic
  18814. stream routing so that IDs can be compared and we can determine which device has been detached
  18815. and whether or not it matches with our ma_device.
  18816. */
  18817. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18818. {
  18819. /* Desktop */
  18820. ma_context_get_device_id_from_MMDevice__wasapi(pContext, pDeviceInterface, &pData->id);
  18821. }
  18822. #else
  18823. {
  18824. /* UWP */
  18825. /* TODO: Implement me. Need to figure out how to get the ID of the default device. */
  18826. }
  18827. #endif
  18828. done:
  18829. /* Clean up. */
  18830. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18831. if (pDeviceInterface != NULL) {
  18832. ma_IMMDevice_Release(pDeviceInterface);
  18833. }
  18834. #else
  18835. if (pDeviceInterface != NULL) {
  18836. ma_IUnknown_Release(pDeviceInterface);
  18837. }
  18838. #endif
  18839. if (result != MA_SUCCESS) {
  18840. if (pData->pRenderClient) {
  18841. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pData->pRenderClient);
  18842. pData->pRenderClient = NULL;
  18843. }
  18844. if (pData->pCaptureClient) {
  18845. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pData->pCaptureClient);
  18846. pData->pCaptureClient = NULL;
  18847. }
  18848. if (pData->pAudioClient) {
  18849. ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient);
  18850. pData->pAudioClient = NULL;
  18851. }
  18852. if (errorMsg != NULL && errorMsg[0] != '\0') {
  18853. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "%s\n", errorMsg);
  18854. }
  18855. return result;
  18856. } else {
  18857. return MA_SUCCESS;
  18858. }
  18859. }
  18860. static ma_result ma_device_reinit__wasapi(ma_device* pDevice, ma_device_type deviceType)
  18861. {
  18862. ma_device_init_internal_data__wasapi data;
  18863. ma_result result;
  18864. MA_ASSERT(pDevice != NULL);
  18865. /* We only re-initialize the playback or capture device. Never a full-duplex device. */
  18866. if (deviceType == ma_device_type_duplex) {
  18867. return MA_INVALID_ARGS;
  18868. }
  18869. /*
  18870. Before reinitializing the device we need to free the previous audio clients.
  18871. There's a known memory leak here. We will be calling this from the routing change callback that
  18872. is fired by WASAPI. If we attempt to release the IAudioClient we will deadlock. In my opinion
  18873. this is a bug. I'm not sure what I need to do to handle this cleanly, but I think we'll probably
  18874. need some system where we post an event, but delay the execution of it until the callback has
  18875. returned. I'm not sure how to do this reliably, however. I have set up some infrastructure for
  18876. a command thread which might be useful for this.
  18877. */
  18878. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
  18879. if (pDevice->wasapi.pCaptureClient) {
  18880. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  18881. pDevice->wasapi.pCaptureClient = NULL;
  18882. }
  18883. if (pDevice->wasapi.pAudioClientCapture) {
  18884. /*ma_device_release_IAudioClient_service__wasapi(pDevice, ma_device_type_capture);*/
  18885. pDevice->wasapi.pAudioClientCapture = NULL;
  18886. }
  18887. }
  18888. if (deviceType == ma_device_type_playback) {
  18889. if (pDevice->wasapi.pRenderClient) {
  18890. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
  18891. pDevice->wasapi.pRenderClient = NULL;
  18892. }
  18893. if (pDevice->wasapi.pAudioClientPlayback) {
  18894. /*ma_device_release_IAudioClient_service__wasapi(pDevice, ma_device_type_playback);*/
  18895. pDevice->wasapi.pAudioClientPlayback = NULL;
  18896. }
  18897. }
  18898. if (deviceType == ma_device_type_playback) {
  18899. data.formatIn = pDevice->playback.format;
  18900. data.channelsIn = pDevice->playback.channels;
  18901. MA_COPY_MEMORY(data.channelMapIn, pDevice->playback.channelMap, sizeof(pDevice->playback.channelMap));
  18902. data.shareMode = pDevice->playback.shareMode;
  18903. } else {
  18904. data.formatIn = pDevice->capture.format;
  18905. data.channelsIn = pDevice->capture.channels;
  18906. MA_COPY_MEMORY(data.channelMapIn, pDevice->capture.channelMap, sizeof(pDevice->capture.channelMap));
  18907. data.shareMode = pDevice->capture.shareMode;
  18908. }
  18909. data.sampleRateIn = pDevice->sampleRate;
  18910. data.periodSizeInFramesIn = pDevice->wasapi.originalPeriodSizeInFrames;
  18911. data.periodSizeInMillisecondsIn = pDevice->wasapi.originalPeriodSizeInMilliseconds;
  18912. data.periodsIn = pDevice->wasapi.originalPeriods;
  18913. data.performanceProfile = pDevice->wasapi.originalPerformanceProfile;
  18914. data.noAutoConvertSRC = pDevice->wasapi.noAutoConvertSRC;
  18915. data.noDefaultQualitySRC = pDevice->wasapi.noDefaultQualitySRC;
  18916. data.noHardwareOffloading = pDevice->wasapi.noHardwareOffloading;
  18917. data.loopbackProcessID = pDevice->wasapi.loopbackProcessID;
  18918. data.loopbackProcessExclude = pDevice->wasapi.loopbackProcessExclude;
  18919. result = ma_device_init_internal__wasapi(pDevice->pContext, deviceType, NULL, &data);
  18920. if (result != MA_SUCCESS) {
  18921. return result;
  18922. }
  18923. /* At this point we have some new objects ready to go. We need to uninitialize the previous ones and then set the new ones. */
  18924. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
  18925. pDevice->wasapi.pAudioClientCapture = data.pAudioClient;
  18926. pDevice->wasapi.pCaptureClient = data.pCaptureClient;
  18927. pDevice->capture.internalFormat = data.formatOut;
  18928. pDevice->capture.internalChannels = data.channelsOut;
  18929. pDevice->capture.internalSampleRate = data.sampleRateOut;
  18930. MA_COPY_MEMORY(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  18931. pDevice->capture.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  18932. pDevice->capture.internalPeriods = data.periodsOut;
  18933. ma_strcpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), data.deviceName);
  18934. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, (HANDLE)pDevice->wasapi.hEventCapture);
  18935. pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut;
  18936. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture);
  18937. /* We must always have a valid ID. */
  18938. ma_strcpy_s_WCHAR(pDevice->capture.id.wasapi, sizeof(pDevice->capture.id.wasapi), data.id.wasapi);
  18939. }
  18940. if (deviceType == ma_device_type_playback) {
  18941. pDevice->wasapi.pAudioClientPlayback = data.pAudioClient;
  18942. pDevice->wasapi.pRenderClient = data.pRenderClient;
  18943. pDevice->playback.internalFormat = data.formatOut;
  18944. pDevice->playback.internalChannels = data.channelsOut;
  18945. pDevice->playback.internalSampleRate = data.sampleRateOut;
  18946. MA_COPY_MEMORY(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  18947. pDevice->playback.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  18948. pDevice->playback.internalPeriods = data.periodsOut;
  18949. ma_strcpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), data.deviceName);
  18950. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, (HANDLE)pDevice->wasapi.hEventPlayback);
  18951. pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut;
  18952. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback);
  18953. /* We must always have a valid ID because rerouting will look at it. */
  18954. ma_strcpy_s_WCHAR(pDevice->playback.id.wasapi, sizeof(pDevice->playback.id.wasapi), data.id.wasapi);
  18955. }
  18956. return MA_SUCCESS;
  18957. }
  18958. static ma_result ma_device_init__wasapi(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  18959. {
  18960. ma_result result = MA_SUCCESS;
  18961. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18962. HRESULT hr;
  18963. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  18964. #endif
  18965. MA_ASSERT(pDevice != NULL);
  18966. MA_ZERO_OBJECT(&pDevice->wasapi);
  18967. pDevice->wasapi.usage = pConfig->wasapi.usage;
  18968. pDevice->wasapi.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
  18969. pDevice->wasapi.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
  18970. pDevice->wasapi.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
  18971. pDevice->wasapi.loopbackProcessID = pConfig->wasapi.loopbackProcessID;
  18972. pDevice->wasapi.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude;
  18973. /* Exclusive mode is not allowed with loopback. */
  18974. if (pConfig->deviceType == ma_device_type_loopback && pConfig->playback.shareMode == ma_share_mode_exclusive) {
  18975. return MA_INVALID_DEVICE_CONFIG;
  18976. }
  18977. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  18978. ma_device_init_internal_data__wasapi data;
  18979. data.formatIn = pDescriptorCapture->format;
  18980. data.channelsIn = pDescriptorCapture->channels;
  18981. data.sampleRateIn = pDescriptorCapture->sampleRate;
  18982. MA_COPY_MEMORY(data.channelMapIn, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
  18983. data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
  18984. data.periodSizeInMillisecondsIn = pDescriptorCapture->periodSizeInMilliseconds;
  18985. data.periodsIn = pDescriptorCapture->periodCount;
  18986. data.shareMode = pDescriptorCapture->shareMode;
  18987. data.performanceProfile = pConfig->performanceProfile;
  18988. data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
  18989. data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
  18990. data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
  18991. data.loopbackProcessID = pConfig->wasapi.loopbackProcessID;
  18992. data.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude;
  18993. result = ma_device_init_internal__wasapi(pDevice->pContext, (pConfig->deviceType == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture, pDescriptorCapture->pDeviceID, &data);
  18994. if (result != MA_SUCCESS) {
  18995. return result;
  18996. }
  18997. pDevice->wasapi.pAudioClientCapture = data.pAudioClient;
  18998. pDevice->wasapi.pCaptureClient = data.pCaptureClient;
  18999. pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorCapture->periodSizeInMilliseconds;
  19000. pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
  19001. pDevice->wasapi.originalPeriods = pDescriptorCapture->periodCount;
  19002. pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile;
  19003. /*
  19004. The event for capture needs to be manual reset for the same reason as playback. We keep the initial state set to unsignaled,
  19005. however, because we want to block until we actually have something for the first call to ma_device_read().
  19006. */
  19007. pDevice->wasapi.hEventCapture = (ma_handle)CreateEventA(NULL, FALSE, FALSE, NULL); /* Auto reset, unsignaled by default. */
  19008. if (pDevice->wasapi.hEventCapture == NULL) {
  19009. result = ma_result_from_GetLastError(GetLastError());
  19010. if (pDevice->wasapi.pCaptureClient != NULL) {
  19011. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  19012. pDevice->wasapi.pCaptureClient = NULL;
  19013. }
  19014. if (pDevice->wasapi.pAudioClientCapture != NULL) {
  19015. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19016. pDevice->wasapi.pAudioClientCapture = NULL;
  19017. }
  19018. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for capture.");
  19019. return result;
  19020. }
  19021. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, (HANDLE)pDevice->wasapi.hEventCapture);
  19022. pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut;
  19023. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture);
  19024. /* We must always have a valid ID. */
  19025. ma_strcpy_s_WCHAR(pDevice->capture.id.wasapi, sizeof(pDevice->capture.id.wasapi), data.id.wasapi);
  19026. /* The descriptor needs to be updated with actual values. */
  19027. pDescriptorCapture->format = data.formatOut;
  19028. pDescriptorCapture->channels = data.channelsOut;
  19029. pDescriptorCapture->sampleRate = data.sampleRateOut;
  19030. MA_COPY_MEMORY(pDescriptorCapture->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  19031. pDescriptorCapture->periodSizeInFrames = data.periodSizeInFramesOut;
  19032. pDescriptorCapture->periodCount = data.periodsOut;
  19033. }
  19034. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  19035. ma_device_init_internal_data__wasapi data;
  19036. data.formatIn = pDescriptorPlayback->format;
  19037. data.channelsIn = pDescriptorPlayback->channels;
  19038. data.sampleRateIn = pDescriptorPlayback->sampleRate;
  19039. MA_COPY_MEMORY(data.channelMapIn, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
  19040. data.periodSizeInFramesIn = pDescriptorPlayback->periodSizeInFrames;
  19041. data.periodSizeInMillisecondsIn = pDescriptorPlayback->periodSizeInMilliseconds;
  19042. data.periodsIn = pDescriptorPlayback->periodCount;
  19043. data.shareMode = pDescriptorPlayback->shareMode;
  19044. data.performanceProfile = pConfig->performanceProfile;
  19045. data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
  19046. data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
  19047. data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
  19048. data.loopbackProcessID = pConfig->wasapi.loopbackProcessID;
  19049. data.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude;
  19050. result = ma_device_init_internal__wasapi(pDevice->pContext, ma_device_type_playback, pDescriptorPlayback->pDeviceID, &data);
  19051. if (result != MA_SUCCESS) {
  19052. if (pConfig->deviceType == ma_device_type_duplex) {
  19053. if (pDevice->wasapi.pCaptureClient != NULL) {
  19054. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  19055. pDevice->wasapi.pCaptureClient = NULL;
  19056. }
  19057. if (pDevice->wasapi.pAudioClientCapture != NULL) {
  19058. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19059. pDevice->wasapi.pAudioClientCapture = NULL;
  19060. }
  19061. CloseHandle((HANDLE)pDevice->wasapi.hEventCapture);
  19062. pDevice->wasapi.hEventCapture = NULL;
  19063. }
  19064. return result;
  19065. }
  19066. pDevice->wasapi.pAudioClientPlayback = data.pAudioClient;
  19067. pDevice->wasapi.pRenderClient = data.pRenderClient;
  19068. pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorPlayback->periodSizeInMilliseconds;
  19069. pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
  19070. pDevice->wasapi.originalPeriods = pDescriptorPlayback->periodCount;
  19071. pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile;
  19072. /*
  19073. The event for playback is needs to be manual reset because we want to explicitly control the fact that it becomes signalled
  19074. only after the whole available space has been filled, never before.
  19075. The playback event also needs to be initially set to a signaled state so that the first call to ma_device_write() is able
  19076. to get passed WaitForMultipleObjects().
  19077. */
  19078. pDevice->wasapi.hEventPlayback = (ma_handle)CreateEventA(NULL, FALSE, TRUE, NULL); /* Auto reset, signaled by default. */
  19079. if (pDevice->wasapi.hEventPlayback == NULL) {
  19080. result = ma_result_from_GetLastError(GetLastError());
  19081. if (pConfig->deviceType == ma_device_type_duplex) {
  19082. if (pDevice->wasapi.pCaptureClient != NULL) {
  19083. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  19084. pDevice->wasapi.pCaptureClient = NULL;
  19085. }
  19086. if (pDevice->wasapi.pAudioClientCapture != NULL) {
  19087. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19088. pDevice->wasapi.pAudioClientCapture = NULL;
  19089. }
  19090. CloseHandle((HANDLE)pDevice->wasapi.hEventCapture);
  19091. pDevice->wasapi.hEventCapture = NULL;
  19092. }
  19093. if (pDevice->wasapi.pRenderClient != NULL) {
  19094. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
  19095. pDevice->wasapi.pRenderClient = NULL;
  19096. }
  19097. if (pDevice->wasapi.pAudioClientPlayback != NULL) {
  19098. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  19099. pDevice->wasapi.pAudioClientPlayback = NULL;
  19100. }
  19101. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for playback.");
  19102. return result;
  19103. }
  19104. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, (HANDLE)pDevice->wasapi.hEventPlayback);
  19105. pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut;
  19106. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback);
  19107. /* We must always have a valid ID because rerouting will look at it. */
  19108. ma_strcpy_s_WCHAR(pDevice->playback.id.wasapi, sizeof(pDevice->playback.id.wasapi), data.id.wasapi);
  19109. /* The descriptor needs to be updated with actual values. */
  19110. pDescriptorPlayback->format = data.formatOut;
  19111. pDescriptorPlayback->channels = data.channelsOut;
  19112. pDescriptorPlayback->sampleRate = data.sampleRateOut;
  19113. MA_COPY_MEMORY(pDescriptorPlayback->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  19114. pDescriptorPlayback->periodSizeInFrames = data.periodSizeInFramesOut;
  19115. pDescriptorPlayback->periodCount = data.periodsOut;
  19116. }
  19117. /*
  19118. We need to register a notification client to detect when the device has been disabled, unplugged or re-routed (when the default device changes). When
  19119. we are connecting to the default device we want to do automatic stream routing when the device is disabled or unplugged. Otherwise we want to just
  19120. stop the device outright and let the application handle it.
  19121. */
  19122. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  19123. if (pConfig->wasapi.noAutoStreamRouting == MA_FALSE) {
  19124. if ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) && pConfig->capture.pDeviceID == NULL) {
  19125. pDevice->wasapi.allowCaptureAutoStreamRouting = MA_TRUE;
  19126. }
  19127. if ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID == NULL) {
  19128. pDevice->wasapi.allowPlaybackAutoStreamRouting = MA_TRUE;
  19129. }
  19130. }
  19131. ma_mutex_init(&pDevice->wasapi.rerouteLock);
  19132. hr = ma_CoCreateInstance(pDevice->pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  19133. if (FAILED(hr)) {
  19134. ma_device_uninit__wasapi(pDevice);
  19135. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.");
  19136. return ma_result_from_HRESULT(hr);
  19137. }
  19138. pDevice->wasapi.notificationClient.lpVtbl = (void*)&g_maNotificationCientVtbl;
  19139. pDevice->wasapi.notificationClient.counter = 1;
  19140. pDevice->wasapi.notificationClient.pDevice = pDevice;
  19141. hr = pDeviceEnumerator->lpVtbl->RegisterEndpointNotificationCallback(pDeviceEnumerator, &pDevice->wasapi.notificationClient);
  19142. if (SUCCEEDED(hr)) {
  19143. pDevice->wasapi.pDeviceEnumerator = (ma_ptr)pDeviceEnumerator;
  19144. } else {
  19145. /* Not the end of the world if we fail to register the notification callback. We just won't support automatic stream routing. */
  19146. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  19147. }
  19148. #endif
  19149. ma_atomic_bool32_set(&pDevice->wasapi.isStartedCapture, MA_FALSE);
  19150. ma_atomic_bool32_set(&pDevice->wasapi.isStartedPlayback, MA_FALSE);
  19151. return MA_SUCCESS;
  19152. }
  19153. static ma_result ma_device__get_available_frames__wasapi(ma_device* pDevice, ma_IAudioClient* pAudioClient, ma_uint32* pFrameCount)
  19154. {
  19155. ma_uint32 paddingFramesCount;
  19156. HRESULT hr;
  19157. ma_share_mode shareMode;
  19158. MA_ASSERT(pDevice != NULL);
  19159. MA_ASSERT(pFrameCount != NULL);
  19160. *pFrameCount = 0;
  19161. if ((ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientPlayback && (ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientCapture) {
  19162. return MA_INVALID_OPERATION;
  19163. }
  19164. /*
  19165. I've had a report that GetCurrentPadding() is returning a frame count of 0 which is preventing
  19166. higher level function calls from doing anything because it thinks nothing is available. I have
  19167. taken a look at the documentation and it looks like this is unnecessary in exclusive mode.
  19168. From Microsoft's documentation:
  19169. For an exclusive-mode rendering or capture stream that was initialized with the
  19170. AUDCLNT_STREAMFLAGS_EVENTCALLBACK flag, the client typically has no use for the padding
  19171. value reported by GetCurrentPadding. Instead, the client accesses an entire buffer during
  19172. each processing pass.
  19173. Considering this, I'm going to skip GetCurrentPadding() for exclusive mode and just report the
  19174. entire buffer. This depends on the caller making sure they wait on the event handler.
  19175. */
  19176. shareMode = ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) ? pDevice->playback.shareMode : pDevice->capture.shareMode;
  19177. if (shareMode == ma_share_mode_shared) {
  19178. /* Shared mode. */
  19179. hr = ma_IAudioClient_GetCurrentPadding(pAudioClient, &paddingFramesCount);
  19180. if (FAILED(hr)) {
  19181. return ma_result_from_HRESULT(hr);
  19182. }
  19183. if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) {
  19184. *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesPlayback - paddingFramesCount;
  19185. } else {
  19186. *pFrameCount = paddingFramesCount;
  19187. }
  19188. } else {
  19189. /* Exclusive mode. */
  19190. if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) {
  19191. *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesPlayback;
  19192. } else {
  19193. *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesCapture;
  19194. }
  19195. }
  19196. return MA_SUCCESS;
  19197. }
  19198. static ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType)
  19199. {
  19200. ma_result result;
  19201. if (deviceType == ma_device_type_duplex) {
  19202. return MA_INVALID_ARGS;
  19203. }
  19204. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "=== CHANGING DEVICE ===\n");
  19205. result = ma_device_reinit__wasapi(pDevice, deviceType);
  19206. if (result != MA_SUCCESS) {
  19207. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WASAPI] Reinitializing device after route change failed.\n");
  19208. return result;
  19209. }
  19210. ma_device__post_init_setup(pDevice, deviceType);
  19211. ma_device__on_notification_rerouted(pDevice);
  19212. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "=== DEVICE CHANGED ===\n");
  19213. return MA_SUCCESS;
  19214. }
  19215. static ma_result ma_device_start__wasapi_nolock(ma_device* pDevice)
  19216. {
  19217. HRESULT hr;
  19218. if (pDevice->pContext->wasapi.hAvrt) {
  19219. const char* pTaskName = ma_to_usage_string__wasapi(pDevice->wasapi.usage);
  19220. if (pTaskName) {
  19221. DWORD idx = 0;
  19222. pDevice->wasapi.hAvrtHandle = (ma_handle)((MA_PFN_AvSetMmThreadCharacteristicsA)pDevice->pContext->wasapi.AvSetMmThreadCharacteristicsA)(pTaskName, &idx);
  19223. }
  19224. }
  19225. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  19226. hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19227. if (FAILED(hr)) {
  19228. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal capture device.");
  19229. return ma_result_from_HRESULT(hr);
  19230. }
  19231. ma_atomic_bool32_set(&pDevice->wasapi.isStartedCapture, MA_TRUE);
  19232. }
  19233. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  19234. hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  19235. if (FAILED(hr)) {
  19236. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device.");
  19237. return ma_result_from_HRESULT(hr);
  19238. }
  19239. ma_atomic_bool32_set(&pDevice->wasapi.isStartedPlayback, MA_TRUE);
  19240. }
  19241. return MA_SUCCESS;
  19242. }
  19243. static ma_result ma_device_start__wasapi(ma_device* pDevice)
  19244. {
  19245. ma_result result;
  19246. MA_ASSERT(pDevice != NULL);
  19247. /* Wait for any rerouting to finish before attempting to start the device. */
  19248. ma_mutex_lock(&pDevice->wasapi.rerouteLock);
  19249. {
  19250. result = ma_device_start__wasapi_nolock(pDevice);
  19251. }
  19252. ma_mutex_unlock(&pDevice->wasapi.rerouteLock);
  19253. return result;
  19254. }
  19255. static ma_result ma_device_stop__wasapi_nolock(ma_device* pDevice)
  19256. {
  19257. ma_result result;
  19258. HRESULT hr;
  19259. MA_ASSERT(pDevice != NULL);
  19260. if (pDevice->wasapi.hAvrtHandle) {
  19261. ((MA_PFN_AvRevertMmThreadCharacteristics)pDevice->pContext->wasapi.AvRevertMmThreadcharacteristics)((HANDLE)pDevice->wasapi.hAvrtHandle);
  19262. pDevice->wasapi.hAvrtHandle = NULL;
  19263. }
  19264. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  19265. hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19266. if (FAILED(hr)) {
  19267. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal capture device.");
  19268. return ma_result_from_HRESULT(hr);
  19269. }
  19270. /* The audio client needs to be reset otherwise restarting will fail. */
  19271. hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19272. if (FAILED(hr)) {
  19273. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal capture device.");
  19274. return ma_result_from_HRESULT(hr);
  19275. }
  19276. /* If we have a mapped buffer we need to release it. */
  19277. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  19278. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  19279. pDevice->wasapi.pMappedBufferCapture = NULL;
  19280. pDevice->wasapi.mappedBufferCaptureCap = 0;
  19281. pDevice->wasapi.mappedBufferCaptureLen = 0;
  19282. }
  19283. ma_atomic_bool32_set(&pDevice->wasapi.isStartedCapture, MA_FALSE);
  19284. }
  19285. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  19286. /*
  19287. The buffer needs to be drained before stopping the device. Not doing this will result in the last few frames not getting output to
  19288. the speakers. This is a problem for very short sounds because it'll result in a significant portion of it not getting played.
  19289. */
  19290. if (ma_atomic_bool32_get(&pDevice->wasapi.isStartedPlayback)) {
  19291. /* We need to make sure we put a timeout here or else we'll risk getting stuck in a deadlock in some cases. */
  19292. DWORD waitTime = pDevice->wasapi.actualBufferSizeInFramesPlayback / pDevice->playback.internalSampleRate;
  19293. if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
  19294. WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, waitTime);
  19295. }
  19296. else {
  19297. ma_uint32 prevFramesAvaialablePlayback = (ma_uint32)-1;
  19298. ma_uint32 framesAvailablePlayback;
  19299. for (;;) {
  19300. result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &framesAvailablePlayback);
  19301. if (result != MA_SUCCESS) {
  19302. break;
  19303. }
  19304. if (framesAvailablePlayback >= pDevice->wasapi.actualBufferSizeInFramesPlayback) {
  19305. break;
  19306. }
  19307. /*
  19308. Just a safety check to avoid an infinite loop. If this iteration results in a situation where the number of available frames
  19309. has not changed, get out of the loop. I don't think this should ever happen, but I think it's nice to have just in case.
  19310. */
  19311. if (framesAvailablePlayback == prevFramesAvaialablePlayback) {
  19312. break;
  19313. }
  19314. prevFramesAvaialablePlayback = framesAvailablePlayback;
  19315. WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, waitTime * 1000);
  19316. ResetEvent((HANDLE)pDevice->wasapi.hEventPlayback); /* Manual reset. */
  19317. }
  19318. }
  19319. }
  19320. hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  19321. if (FAILED(hr)) {
  19322. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal playback device.");
  19323. return ma_result_from_HRESULT(hr);
  19324. }
  19325. /* The audio client needs to be reset otherwise restarting will fail. */
  19326. hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  19327. if (FAILED(hr)) {
  19328. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal playback device.");
  19329. return ma_result_from_HRESULT(hr);
  19330. }
  19331. if (pDevice->wasapi.pMappedBufferPlayback != NULL) {
  19332. ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0);
  19333. pDevice->wasapi.pMappedBufferPlayback = NULL;
  19334. pDevice->wasapi.mappedBufferPlaybackCap = 0;
  19335. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  19336. }
  19337. ma_atomic_bool32_set(&pDevice->wasapi.isStartedPlayback, MA_FALSE);
  19338. }
  19339. return MA_SUCCESS;
  19340. }
  19341. static ma_result ma_device_stop__wasapi(ma_device* pDevice)
  19342. {
  19343. ma_result result;
  19344. MA_ASSERT(pDevice != NULL);
  19345. /* Wait for any rerouting to finish before attempting to stop the device. */
  19346. ma_mutex_lock(&pDevice->wasapi.rerouteLock);
  19347. {
  19348. result = ma_device_stop__wasapi_nolock(pDevice);
  19349. }
  19350. ma_mutex_unlock(&pDevice->wasapi.rerouteLock);
  19351. return result;
  19352. }
  19353. #ifndef MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS
  19354. #define MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS 5000
  19355. #endif
  19356. static ma_result ma_device_read__wasapi(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  19357. {
  19358. ma_result result = MA_SUCCESS;
  19359. ma_uint32 totalFramesProcessed = 0;
  19360. /*
  19361. When reading, we need to get a buffer and process all of it before releasing it. Because the
  19362. frame count (frameCount) can be different to the size of the buffer, we'll need to cache the
  19363. pointer to the buffer.
  19364. */
  19365. /* Keep running until we've processed the requested number of frames. */
  19366. while (ma_device_get_state(pDevice) == ma_device_state_started && totalFramesProcessed < frameCount) {
  19367. ma_uint32 framesRemaining = frameCount - totalFramesProcessed;
  19368. /* If we have a mapped data buffer, consume that first. */
  19369. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  19370. /* We have a cached data pointer so consume that before grabbing another one from WASAPI. */
  19371. ma_uint32 framesToProcessNow = framesRemaining;
  19372. if (framesToProcessNow > pDevice->wasapi.mappedBufferCaptureLen) {
  19373. framesToProcessNow = pDevice->wasapi.mappedBufferCaptureLen;
  19374. }
  19375. /* Now just copy the data over to the output buffer. */
  19376. ma_copy_pcm_frames(
  19377. ma_offset_pcm_frames_ptr(pFrames, totalFramesProcessed, pDevice->capture.internalFormat, pDevice->capture.internalChannels),
  19378. ma_offset_pcm_frames_const_ptr(pDevice->wasapi.pMappedBufferCapture, pDevice->wasapi.mappedBufferCaptureCap - pDevice->wasapi.mappedBufferCaptureLen, pDevice->capture.internalFormat, pDevice->capture.internalChannels),
  19379. framesToProcessNow,
  19380. pDevice->capture.internalFormat, pDevice->capture.internalChannels
  19381. );
  19382. totalFramesProcessed += framesToProcessNow;
  19383. pDevice->wasapi.mappedBufferCaptureLen -= framesToProcessNow;
  19384. /* If the data buffer has been fully consumed we need to release it. */
  19385. if (pDevice->wasapi.mappedBufferCaptureLen == 0) {
  19386. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  19387. pDevice->wasapi.pMappedBufferCapture = NULL;
  19388. pDevice->wasapi.mappedBufferCaptureCap = 0;
  19389. }
  19390. } else {
  19391. /* We don't have any cached data pointer, so grab another one. */
  19392. HRESULT hr;
  19393. DWORD flags = 0;
  19394. /* First just ask WASAPI for a data buffer. If it's not available, we'll wait for more. */
  19395. hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pDevice->wasapi.pMappedBufferCapture, &pDevice->wasapi.mappedBufferCaptureCap, &flags, NULL, NULL);
  19396. if (hr == S_OK) {
  19397. /* We got a data buffer. Continue to the next loop iteration which will then read from the mapped pointer. */
  19398. pDevice->wasapi.mappedBufferCaptureLen = pDevice->wasapi.mappedBufferCaptureCap;
  19399. /*
  19400. There have been reports that indicate that at times the AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY is reported for every
  19401. call to IAudioCaptureClient_GetBuffer() above which results in spamming of the debug messages below. To partially
  19402. work around this, I'm only outputting these messages when MA_DEBUG_OUTPUT is explicitly defined. The better solution
  19403. would be to figure out why the flag is always getting reported.
  19404. */
  19405. #if defined(MA_DEBUG_OUTPUT)
  19406. {
  19407. if (flags != 0) {
  19408. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Capture Flags: %ld\n", flags);
  19409. if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
  19410. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity (possible overrun). Attempting recovery. mappedBufferCaptureCap=%d\n", pDevice->wasapi.mappedBufferCaptureCap);
  19411. }
  19412. }
  19413. }
  19414. #endif
  19415. /* Overrun detection. */
  19416. if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
  19417. /* Glitched. Probably due to an overrun. */
  19418. /*
  19419. If we got an overrun it probably means we're straddling the end of the buffer. In normal capture
  19420. mode this is the fault of the client application because they're responsible for ensuring data is
  19421. processed fast enough. In duplex mode, however, the processing of audio is tied to the playback
  19422. device, so this can possibly be the result of a timing de-sync.
  19423. In capture mode we're not going to do any kind of recovery because the real fix is for the client
  19424. application to process faster. In duplex mode, we'll treat this as a desync and reset the buffers
  19425. to prevent a never-ending sequence of glitches due to straddling the end of the buffer.
  19426. */
  19427. if (pDevice->type == ma_device_type_duplex) {
  19428. /*
  19429. Experiment:
  19430. If we empty out the *entire* buffer we may end up putting ourselves into an underrun position
  19431. which isn't really any better than the overrun we're probably in right now. Instead we'll just
  19432. empty out about half.
  19433. */
  19434. ma_uint32 i;
  19435. ma_uint32 periodCount = (pDevice->wasapi.actualBufferSizeInFramesCapture / pDevice->wasapi.periodSizeInFramesCapture);
  19436. ma_uint32 iterationCount = periodCount / 2;
  19437. if ((periodCount % 2) > 0) {
  19438. iterationCount += 1;
  19439. }
  19440. for (i = 0; i < iterationCount; i += 1) {
  19441. hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  19442. if (FAILED(hr)) {
  19443. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: IAudioCaptureClient_ReleaseBuffer() failed with %ld.\n", hr);
  19444. break;
  19445. }
  19446. flags = 0;
  19447. hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pDevice->wasapi.pMappedBufferCapture, &pDevice->wasapi.mappedBufferCaptureCap, &flags, NULL, NULL);
  19448. if (hr == MA_AUDCLNT_S_BUFFER_EMPTY || FAILED(hr)) {
  19449. /*
  19450. The buffer has been completely emptied or an error occurred. In this case we'll need
  19451. to reset the state of the mapped buffer which will trigger the next iteration to get
  19452. a fresh buffer from WASAPI.
  19453. */
  19454. pDevice->wasapi.pMappedBufferCapture = NULL;
  19455. pDevice->wasapi.mappedBufferCaptureCap = 0;
  19456. pDevice->wasapi.mappedBufferCaptureLen = 0;
  19457. if (hr == MA_AUDCLNT_S_BUFFER_EMPTY) {
  19458. if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
  19459. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: Buffer emptied, and data discontinuity still reported.\n");
  19460. } else {
  19461. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: Buffer emptied.\n");
  19462. }
  19463. }
  19464. if (FAILED(hr)) {
  19465. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: IAudioCaptureClient_GetBuffer() failed with %ld.\n", hr);
  19466. }
  19467. break;
  19468. }
  19469. }
  19470. /* If at this point we have a valid buffer mapped, make sure the buffer length is set appropriately. */
  19471. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  19472. pDevice->wasapi.mappedBufferCaptureLen = pDevice->wasapi.mappedBufferCaptureCap;
  19473. }
  19474. }
  19475. }
  19476. continue;
  19477. } else {
  19478. if (hr == MA_AUDCLNT_S_BUFFER_EMPTY || hr == MA_AUDCLNT_E_BUFFER_ERROR) {
  19479. /*
  19480. No data is available. We need to wait for more. There's two situations to consider
  19481. here. The first is normal capture mode. If this times out it probably means the
  19482. microphone isn't delivering data for whatever reason. In this case we'll just
  19483. abort the read and return whatever we were able to get. The other situations is
  19484. loopback mode, in which case a timeout probably just means the nothing is playing
  19485. through the speakers.
  19486. */
  19487. /* Experiment: Use a shorter timeout for loopback mode. */
  19488. DWORD timeoutInMilliseconds = MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS;
  19489. if (pDevice->type == ma_device_type_loopback) {
  19490. timeoutInMilliseconds = 10;
  19491. }
  19492. if (WaitForSingleObject((HANDLE)pDevice->wasapi.hEventCapture, timeoutInMilliseconds) != WAIT_OBJECT_0) {
  19493. if (pDevice->type == ma_device_type_loopback) {
  19494. continue; /* Keep waiting in loopback mode. */
  19495. } else {
  19496. result = MA_ERROR;
  19497. break; /* Wait failed. */
  19498. }
  19499. }
  19500. /* At this point we should be able to loop back to the start of the loop and try retrieving a data buffer again. */
  19501. } else {
  19502. /* An error occured and we need to abort. */
  19503. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from capture device in preparation for reading from the device. HRESULT = %d. Stopping device.\n", (int)hr);
  19504. result = ma_result_from_HRESULT(hr);
  19505. break;
  19506. }
  19507. }
  19508. }
  19509. }
  19510. /*
  19511. If we were unable to process the entire requested frame count, but we still have a mapped buffer,
  19512. there's a good chance either an error occurred or the device was stopped mid-read. In this case
  19513. we'll need to make sure the buffer is released.
  19514. */
  19515. if (totalFramesProcessed < frameCount && pDevice->wasapi.pMappedBufferCapture != NULL) {
  19516. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  19517. pDevice->wasapi.pMappedBufferCapture = NULL;
  19518. pDevice->wasapi.mappedBufferCaptureCap = 0;
  19519. pDevice->wasapi.mappedBufferCaptureLen = 0;
  19520. }
  19521. if (pFramesRead != NULL) {
  19522. *pFramesRead = totalFramesProcessed;
  19523. }
  19524. return result;
  19525. }
  19526. static ma_result ma_device_write__wasapi(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  19527. {
  19528. ma_result result = MA_SUCCESS;
  19529. ma_uint32 totalFramesProcessed = 0;
  19530. /* Keep writing to the device until it's stopped or we've consumed all of our input. */
  19531. while (ma_device_get_state(pDevice) == ma_device_state_started && totalFramesProcessed < frameCount) {
  19532. ma_uint32 framesRemaining = frameCount - totalFramesProcessed;
  19533. /*
  19534. We're going to do this in a similar way to capture. We'll first check if the cached data pointer
  19535. is valid, and if so, read from that. Otherwise We will call IAudioRenderClient_GetBuffer() with
  19536. a requested buffer size equal to our actual period size. If it returns AUDCLNT_E_BUFFER_TOO_LARGE
  19537. it means we need to wait for some data to become available.
  19538. */
  19539. if (pDevice->wasapi.pMappedBufferPlayback != NULL) {
  19540. /* We still have some space available in the mapped data buffer. Write to it. */
  19541. ma_uint32 framesToProcessNow = framesRemaining;
  19542. if (framesToProcessNow > (pDevice->wasapi.mappedBufferPlaybackCap - pDevice->wasapi.mappedBufferPlaybackLen)) {
  19543. framesToProcessNow = (pDevice->wasapi.mappedBufferPlaybackCap - pDevice->wasapi.mappedBufferPlaybackLen);
  19544. }
  19545. /* Now just copy the data over to the output buffer. */
  19546. ma_copy_pcm_frames(
  19547. ma_offset_pcm_frames_ptr(pDevice->wasapi.pMappedBufferPlayback, pDevice->wasapi.mappedBufferPlaybackLen, pDevice->playback.internalFormat, pDevice->playback.internalChannels),
  19548. ma_offset_pcm_frames_const_ptr(pFrames, totalFramesProcessed, pDevice->playback.internalFormat, pDevice->playback.internalChannels),
  19549. framesToProcessNow,
  19550. pDevice->playback.internalFormat, pDevice->playback.internalChannels
  19551. );
  19552. totalFramesProcessed += framesToProcessNow;
  19553. pDevice->wasapi.mappedBufferPlaybackLen += framesToProcessNow;
  19554. /* If the data buffer has been fully consumed we need to release it. */
  19555. if (pDevice->wasapi.mappedBufferPlaybackLen == pDevice->wasapi.mappedBufferPlaybackCap) {
  19556. ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0);
  19557. pDevice->wasapi.pMappedBufferPlayback = NULL;
  19558. pDevice->wasapi.mappedBufferPlaybackCap = 0;
  19559. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  19560. /*
  19561. In exclusive mode we need to wait here. Exclusive mode is weird because GetBuffer() never
  19562. seems to return AUDCLNT_E_BUFFER_TOO_LARGE, which is what we normally use to determine
  19563. whether or not we need to wait for more data.
  19564. */
  19565. if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
  19566. if (WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS) != WAIT_OBJECT_0) {
  19567. result = MA_ERROR;
  19568. break; /* Wait failed. Probably timed out. */
  19569. }
  19570. }
  19571. }
  19572. } else {
  19573. /* We don't have a mapped data buffer so we'll need to get one. */
  19574. HRESULT hr;
  19575. ma_uint32 bufferSizeInFrames;
  19576. /* Special rules for exclusive mode. */
  19577. if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
  19578. bufferSizeInFrames = pDevice->wasapi.actualBufferSizeInFramesPlayback;
  19579. } else {
  19580. bufferSizeInFrames = pDevice->wasapi.periodSizeInFramesPlayback;
  19581. }
  19582. hr = ma_IAudioRenderClient_GetBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, bufferSizeInFrames, (BYTE**)&pDevice->wasapi.pMappedBufferPlayback);
  19583. if (hr == S_OK) {
  19584. /* We have data available. */
  19585. pDevice->wasapi.mappedBufferPlaybackCap = bufferSizeInFrames;
  19586. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  19587. } else {
  19588. if (hr == MA_AUDCLNT_E_BUFFER_TOO_LARGE || hr == MA_AUDCLNT_E_BUFFER_ERROR) {
  19589. /* Not enough data available. We need to wait for more. */
  19590. if (WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS) != WAIT_OBJECT_0) {
  19591. result = MA_ERROR;
  19592. break; /* Wait failed. Probably timed out. */
  19593. }
  19594. } else {
  19595. /* Some error occurred. We'll need to abort. */
  19596. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from playback device in preparation for writing to the device. HRESULT = %d. Stopping device.\n", (int)hr);
  19597. result = ma_result_from_HRESULT(hr);
  19598. break;
  19599. }
  19600. }
  19601. }
  19602. }
  19603. if (pFramesWritten != NULL) {
  19604. *pFramesWritten = totalFramesProcessed;
  19605. }
  19606. return result;
  19607. }
  19608. static ma_result ma_device_data_loop_wakeup__wasapi(ma_device* pDevice)
  19609. {
  19610. MA_ASSERT(pDevice != NULL);
  19611. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  19612. SetEvent((HANDLE)pDevice->wasapi.hEventCapture);
  19613. }
  19614. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  19615. SetEvent((HANDLE)pDevice->wasapi.hEventPlayback);
  19616. }
  19617. return MA_SUCCESS;
  19618. }
  19619. static ma_result ma_context_uninit__wasapi(ma_context* pContext)
  19620. {
  19621. ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_QUIT__WASAPI);
  19622. MA_ASSERT(pContext != NULL);
  19623. MA_ASSERT(pContext->backend == ma_backend_wasapi);
  19624. ma_context_post_command__wasapi(pContext, &cmd);
  19625. ma_thread_wait(&pContext->wasapi.commandThread);
  19626. if (pContext->wasapi.hAvrt) {
  19627. ma_dlclose(pContext, pContext->wasapi.hAvrt);
  19628. pContext->wasapi.hAvrt = NULL;
  19629. }
  19630. #if defined(MA_WIN32_UWP)
  19631. {
  19632. if (pContext->wasapi.hMMDevapi) {
  19633. ma_dlclose(pContext, pContext->wasapi.hMMDevapi);
  19634. pContext->wasapi.hMMDevapi = NULL;
  19635. }
  19636. }
  19637. #endif
  19638. /* Only after the thread has been terminated can we uninitialize the sync objects for the command thread. */
  19639. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  19640. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19641. return MA_SUCCESS;
  19642. }
  19643. static ma_result ma_context_init__wasapi(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  19644. {
  19645. ma_result result = MA_SUCCESS;
  19646. MA_ASSERT(pContext != NULL);
  19647. (void)pConfig;
  19648. #ifdef MA_WIN32_DESKTOP
  19649. /*
  19650. WASAPI is only supported in Vista SP1 and newer. The reason for SP1 and not the base version of Vista is that event-driven
  19651. exclusive mode does not work until SP1.
  19652. Unfortunately older compilers don't define these functions so we need to dynamically load them in order to avoid a link error.
  19653. */
  19654. {
  19655. ma_OSVERSIONINFOEXW osvi;
  19656. ma_handle kernel32DLL;
  19657. ma_PFNVerifyVersionInfoW _VerifyVersionInfoW;
  19658. ma_PFNVerSetConditionMask _VerSetConditionMask;
  19659. kernel32DLL = ma_dlopen(pContext, "kernel32.dll");
  19660. if (kernel32DLL == NULL) {
  19661. return MA_NO_BACKEND;
  19662. }
  19663. _VerifyVersionInfoW = (ma_PFNVerifyVersionInfoW )ma_dlsym(pContext, kernel32DLL, "VerifyVersionInfoW");
  19664. _VerSetConditionMask = (ma_PFNVerSetConditionMask)ma_dlsym(pContext, kernel32DLL, "VerSetConditionMask");
  19665. if (_VerifyVersionInfoW == NULL || _VerSetConditionMask == NULL) {
  19666. ma_dlclose(pContext, kernel32DLL);
  19667. return MA_NO_BACKEND;
  19668. }
  19669. MA_ZERO_OBJECT(&osvi);
  19670. osvi.dwOSVersionInfoSize = sizeof(osvi);
  19671. osvi.dwMajorVersion = ((MA_WIN32_WINNT_VISTA >> 8) & 0xFF);
  19672. osvi.dwMinorVersion = ((MA_WIN32_WINNT_VISTA >> 0) & 0xFF);
  19673. osvi.wServicePackMajor = 1;
  19674. if (_VerifyVersionInfoW(&osvi, MA_VER_MAJORVERSION | MA_VER_MINORVERSION | MA_VER_SERVICEPACKMAJOR, _VerSetConditionMask(_VerSetConditionMask(_VerSetConditionMask(0, MA_VER_MAJORVERSION, MA_VER_GREATER_EQUAL), MA_VER_MINORVERSION, MA_VER_GREATER_EQUAL), MA_VER_SERVICEPACKMAJOR, MA_VER_GREATER_EQUAL))) {
  19675. result = MA_SUCCESS;
  19676. } else {
  19677. result = MA_NO_BACKEND;
  19678. }
  19679. ma_dlclose(pContext, kernel32DLL);
  19680. }
  19681. #endif
  19682. if (result != MA_SUCCESS) {
  19683. return result;
  19684. }
  19685. MA_ZERO_OBJECT(&pContext->wasapi);
  19686. /*
  19687. Annoyingly, WASAPI does not allow you to release an IAudioClient object from a different thread
  19688. than the one that retrieved it with GetService(). This can result in a deadlock in two
  19689. situations:
  19690. 1) When calling ma_device_uninit() from a different thread to ma_device_init(); and
  19691. 2) When uninitializing and reinitializing the internal IAudioClient object in response to
  19692. automatic stream routing.
  19693. We could define ma_device_uninit() such that it must be called on the same thread as
  19694. ma_device_init(). We could also just not release the IAudioClient when performing automatic
  19695. stream routing to avoid the deadlock. Neither of these are acceptable solutions in my view so
  19696. we're going to have to work around this with a worker thread. This is not ideal, but I can't
  19697. think of a better way to do this.
  19698. More information about this can be found here:
  19699. https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nn-audioclient-iaudiorenderclient
  19700. Note this section:
  19701. When releasing an IAudioRenderClient interface instance, the client must call the interface's
  19702. Release method from the same thread as the call to IAudioClient::GetService that created the
  19703. object.
  19704. */
  19705. {
  19706. result = ma_mutex_init(&pContext->wasapi.commandLock);
  19707. if (result != MA_SUCCESS) {
  19708. return result;
  19709. }
  19710. result = ma_semaphore_init(0, &pContext->wasapi.commandSem);
  19711. if (result != MA_SUCCESS) {
  19712. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19713. return result;
  19714. }
  19715. result = ma_thread_create(&pContext->wasapi.commandThread, ma_thread_priority_normal, 0, ma_context_command_thread__wasapi, pContext, &pContext->allocationCallbacks);
  19716. if (result != MA_SUCCESS) {
  19717. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  19718. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19719. return result;
  19720. }
  19721. #if defined(MA_WIN32_UWP)
  19722. {
  19723. /* Link to mmdevapi so we can get access to ActivateAudioInterfaceAsync(). */
  19724. pContext->wasapi.hMMDevapi = ma_dlopen(pContext, "mmdevapi.dll");
  19725. if (pContext->wasapi.hMMDevapi) {
  19726. pContext->wasapi.ActivateAudioInterfaceAsync = ma_dlsym(pContext, pContext->wasapi.hMMDevapi, "ActivateAudioInterfaceAsync");
  19727. if (pContext->wasapi.ActivateAudioInterfaceAsync == NULL) {
  19728. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  19729. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19730. ma_dlclose(pContext, pContext->wasapi.hMMDevapi);
  19731. return MA_NO_BACKEND; /* ActivateAudioInterfaceAsync() could not be loaded. */
  19732. }
  19733. } else {
  19734. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  19735. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19736. return MA_NO_BACKEND; /* Failed to load mmdevapi.dll which is required for ActivateAudioInterfaceAsync() */
  19737. }
  19738. }
  19739. #endif
  19740. /* Optionally use the Avrt API to specify the audio thread's latency sensitivity requirements */
  19741. pContext->wasapi.hAvrt = ma_dlopen(pContext, "avrt.dll");
  19742. if (pContext->wasapi.hAvrt) {
  19743. pContext->wasapi.AvSetMmThreadCharacteristicsA = ma_dlsym(pContext, pContext->wasapi.hAvrt, "AvSetMmThreadCharacteristicsA");
  19744. pContext->wasapi.AvRevertMmThreadcharacteristics = ma_dlsym(pContext, pContext->wasapi.hAvrt, "AvRevertMmThreadCharacteristics");
  19745. /* If either function could not be found, disable use of avrt entirely. */
  19746. if (!pContext->wasapi.AvSetMmThreadCharacteristicsA || !pContext->wasapi.AvRevertMmThreadcharacteristics) {
  19747. pContext->wasapi.AvSetMmThreadCharacteristicsA = NULL;
  19748. pContext->wasapi.AvRevertMmThreadcharacteristics = NULL;
  19749. ma_dlclose(pContext, pContext->wasapi.hAvrt);
  19750. pContext->wasapi.hAvrt = NULL;
  19751. }
  19752. }
  19753. }
  19754. pCallbacks->onContextInit = ma_context_init__wasapi;
  19755. pCallbacks->onContextUninit = ma_context_uninit__wasapi;
  19756. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__wasapi;
  19757. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__wasapi;
  19758. pCallbacks->onDeviceInit = ma_device_init__wasapi;
  19759. pCallbacks->onDeviceUninit = ma_device_uninit__wasapi;
  19760. pCallbacks->onDeviceStart = ma_device_start__wasapi;
  19761. pCallbacks->onDeviceStop = ma_device_stop__wasapi;
  19762. pCallbacks->onDeviceRead = ma_device_read__wasapi;
  19763. pCallbacks->onDeviceWrite = ma_device_write__wasapi;
  19764. pCallbacks->onDeviceDataLoop = NULL;
  19765. pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__wasapi;
  19766. return MA_SUCCESS;
  19767. }
  19768. #endif
  19769. /******************************************************************************
  19770. DirectSound Backend
  19771. ******************************************************************************/
  19772. #ifdef MA_HAS_DSOUND
  19773. /*#include <dsound.h>*/
  19774. /*static const GUID MA_GUID_IID_DirectSoundNotify = {0xb0210783, 0x89cd, 0x11d0, {0xaf, 0x08, 0x00, 0xa0, 0xc9, 0x25, 0xcd, 0x16}};*/
  19775. /* miniaudio only uses priority or exclusive modes. */
  19776. #define MA_DSSCL_NORMAL 1
  19777. #define MA_DSSCL_PRIORITY 2
  19778. #define MA_DSSCL_EXCLUSIVE 3
  19779. #define MA_DSSCL_WRITEPRIMARY 4
  19780. #define MA_DSCAPS_PRIMARYMONO 0x00000001
  19781. #define MA_DSCAPS_PRIMARYSTEREO 0x00000002
  19782. #define MA_DSCAPS_PRIMARY8BIT 0x00000004
  19783. #define MA_DSCAPS_PRIMARY16BIT 0x00000008
  19784. #define MA_DSCAPS_CONTINUOUSRATE 0x00000010
  19785. #define MA_DSCAPS_EMULDRIVER 0x00000020
  19786. #define MA_DSCAPS_CERTIFIED 0x00000040
  19787. #define MA_DSCAPS_SECONDARYMONO 0x00000100
  19788. #define MA_DSCAPS_SECONDARYSTEREO 0x00000200
  19789. #define MA_DSCAPS_SECONDARY8BIT 0x00000400
  19790. #define MA_DSCAPS_SECONDARY16BIT 0x00000800
  19791. #define MA_DSBCAPS_PRIMARYBUFFER 0x00000001
  19792. #define MA_DSBCAPS_STATIC 0x00000002
  19793. #define MA_DSBCAPS_LOCHARDWARE 0x00000004
  19794. #define MA_DSBCAPS_LOCSOFTWARE 0x00000008
  19795. #define MA_DSBCAPS_CTRL3D 0x00000010
  19796. #define MA_DSBCAPS_CTRLFREQUENCY 0x00000020
  19797. #define MA_DSBCAPS_CTRLPAN 0x00000040
  19798. #define MA_DSBCAPS_CTRLVOLUME 0x00000080
  19799. #define MA_DSBCAPS_CTRLPOSITIONNOTIFY 0x00000100
  19800. #define MA_DSBCAPS_CTRLFX 0x00000200
  19801. #define MA_DSBCAPS_STICKYFOCUS 0x00004000
  19802. #define MA_DSBCAPS_GLOBALFOCUS 0x00008000
  19803. #define MA_DSBCAPS_GETCURRENTPOSITION2 0x00010000
  19804. #define MA_DSBCAPS_MUTE3DATMAXDISTANCE 0x00020000
  19805. #define MA_DSBCAPS_LOCDEFER 0x00040000
  19806. #define MA_DSBCAPS_TRUEPLAYPOSITION 0x00080000
  19807. #define MA_DSBPLAY_LOOPING 0x00000001
  19808. #define MA_DSBPLAY_LOCHARDWARE 0x00000002
  19809. #define MA_DSBPLAY_LOCSOFTWARE 0x00000004
  19810. #define MA_DSBPLAY_TERMINATEBY_TIME 0x00000008
  19811. #define MA_DSBPLAY_TERMINATEBY_DISTANCE 0x00000010
  19812. #define MA_DSBPLAY_TERMINATEBY_PRIORITY 0x00000020
  19813. #define MA_DSCBSTART_LOOPING 0x00000001
  19814. typedef struct
  19815. {
  19816. DWORD dwSize;
  19817. DWORD dwFlags;
  19818. DWORD dwBufferBytes;
  19819. DWORD dwReserved;
  19820. MA_WAVEFORMATEX* lpwfxFormat;
  19821. GUID guid3DAlgorithm;
  19822. } MA_DSBUFFERDESC;
  19823. typedef struct
  19824. {
  19825. DWORD dwSize;
  19826. DWORD dwFlags;
  19827. DWORD dwBufferBytes;
  19828. DWORD dwReserved;
  19829. MA_WAVEFORMATEX* lpwfxFormat;
  19830. DWORD dwFXCount;
  19831. void* lpDSCFXDesc; /* <-- miniaudio doesn't use this, so set to void*. */
  19832. } MA_DSCBUFFERDESC;
  19833. typedef struct
  19834. {
  19835. DWORD dwSize;
  19836. DWORD dwFlags;
  19837. DWORD dwMinSecondarySampleRate;
  19838. DWORD dwMaxSecondarySampleRate;
  19839. DWORD dwPrimaryBuffers;
  19840. DWORD dwMaxHwMixingAllBuffers;
  19841. DWORD dwMaxHwMixingStaticBuffers;
  19842. DWORD dwMaxHwMixingStreamingBuffers;
  19843. DWORD dwFreeHwMixingAllBuffers;
  19844. DWORD dwFreeHwMixingStaticBuffers;
  19845. DWORD dwFreeHwMixingStreamingBuffers;
  19846. DWORD dwMaxHw3DAllBuffers;
  19847. DWORD dwMaxHw3DStaticBuffers;
  19848. DWORD dwMaxHw3DStreamingBuffers;
  19849. DWORD dwFreeHw3DAllBuffers;
  19850. DWORD dwFreeHw3DStaticBuffers;
  19851. DWORD dwFreeHw3DStreamingBuffers;
  19852. DWORD dwTotalHwMemBytes;
  19853. DWORD dwFreeHwMemBytes;
  19854. DWORD dwMaxContigFreeHwMemBytes;
  19855. DWORD dwUnlockTransferRateHwBuffers;
  19856. DWORD dwPlayCpuOverheadSwBuffers;
  19857. DWORD dwReserved1;
  19858. DWORD dwReserved2;
  19859. } MA_DSCAPS;
  19860. typedef struct
  19861. {
  19862. DWORD dwSize;
  19863. DWORD dwFlags;
  19864. DWORD dwBufferBytes;
  19865. DWORD dwUnlockTransferRate;
  19866. DWORD dwPlayCpuOverhead;
  19867. } MA_DSBCAPS;
  19868. typedef struct
  19869. {
  19870. DWORD dwSize;
  19871. DWORD dwFlags;
  19872. DWORD dwFormats;
  19873. DWORD dwChannels;
  19874. } MA_DSCCAPS;
  19875. typedef struct
  19876. {
  19877. DWORD dwSize;
  19878. DWORD dwFlags;
  19879. DWORD dwBufferBytes;
  19880. DWORD dwReserved;
  19881. } MA_DSCBCAPS;
  19882. typedef struct
  19883. {
  19884. DWORD dwOffset;
  19885. HANDLE hEventNotify;
  19886. } MA_DSBPOSITIONNOTIFY;
  19887. typedef struct ma_IDirectSound ma_IDirectSound;
  19888. typedef struct ma_IDirectSoundBuffer ma_IDirectSoundBuffer;
  19889. typedef struct ma_IDirectSoundCapture ma_IDirectSoundCapture;
  19890. typedef struct ma_IDirectSoundCaptureBuffer ma_IDirectSoundCaptureBuffer;
  19891. typedef struct ma_IDirectSoundNotify ma_IDirectSoundNotify;
  19892. /*
  19893. COM objects. The way these work is that you have a vtable (a list of function pointers, kind of
  19894. like how C++ works internally), and then you have a structure with a single member, which is a
  19895. pointer to the vtable. The vtable is where the methods of the object are defined. Methods need
  19896. to be in a specific order, and parent classes need to have their methods declared first.
  19897. */
  19898. /* IDirectSound */
  19899. typedef struct
  19900. {
  19901. /* IUnknown */
  19902. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSound* pThis, const IID* const riid, void** ppObject);
  19903. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSound* pThis);
  19904. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSound* pThis);
  19905. /* IDirectSound */
  19906. HRESULT (STDMETHODCALLTYPE * CreateSoundBuffer) (ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter);
  19907. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps);
  19908. HRESULT (STDMETHODCALLTYPE * DuplicateSoundBuffer)(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate);
  19909. HRESULT (STDMETHODCALLTYPE * SetCooperativeLevel) (ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel);
  19910. HRESULT (STDMETHODCALLTYPE * Compact) (ma_IDirectSound* pThis);
  19911. HRESULT (STDMETHODCALLTYPE * GetSpeakerConfig) (ma_IDirectSound* pThis, DWORD* pSpeakerConfig);
  19912. HRESULT (STDMETHODCALLTYPE * SetSpeakerConfig) (ma_IDirectSound* pThis, DWORD dwSpeakerConfig);
  19913. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSound* pThis, const GUID* pGuidDevice);
  19914. } ma_IDirectSoundVtbl;
  19915. struct ma_IDirectSound
  19916. {
  19917. ma_IDirectSoundVtbl* lpVtbl;
  19918. };
  19919. static MA_INLINE HRESULT ma_IDirectSound_QueryInterface(ma_IDirectSound* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19920. static MA_INLINE ULONG ma_IDirectSound_AddRef(ma_IDirectSound* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  19921. static MA_INLINE ULONG ma_IDirectSound_Release(ma_IDirectSound* pThis) { return pThis->lpVtbl->Release(pThis); }
  19922. static MA_INLINE HRESULT ma_IDirectSound_CreateSoundBuffer(ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateSoundBuffer(pThis, pDSBufferDesc, ppDSBuffer, pUnkOuter); }
  19923. static MA_INLINE HRESULT ma_IDirectSound_GetCaps(ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCaps); }
  19924. static MA_INLINE HRESULT ma_IDirectSound_DuplicateSoundBuffer(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate) { return pThis->lpVtbl->DuplicateSoundBuffer(pThis, pDSBufferOriginal, ppDSBufferDuplicate); }
  19925. static MA_INLINE HRESULT ma_IDirectSound_SetCooperativeLevel(ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel) { return pThis->lpVtbl->SetCooperativeLevel(pThis, hwnd, dwLevel); }
  19926. static MA_INLINE HRESULT ma_IDirectSound_Compact(ma_IDirectSound* pThis) { return pThis->lpVtbl->Compact(pThis); }
  19927. static MA_INLINE HRESULT ma_IDirectSound_GetSpeakerConfig(ma_IDirectSound* pThis, DWORD* pSpeakerConfig) { return pThis->lpVtbl->GetSpeakerConfig(pThis, pSpeakerConfig); }
  19928. static MA_INLINE HRESULT ma_IDirectSound_SetSpeakerConfig(ma_IDirectSound* pThis, DWORD dwSpeakerConfig) { return pThis->lpVtbl->SetSpeakerConfig(pThis, dwSpeakerConfig); }
  19929. static MA_INLINE HRESULT ma_IDirectSound_Initialize(ma_IDirectSound* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); }
  19930. /* IDirectSoundBuffer */
  19931. typedef struct
  19932. {
  19933. /* IUnknown */
  19934. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject);
  19935. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundBuffer* pThis);
  19936. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundBuffer* pThis);
  19937. /* IDirectSoundBuffer */
  19938. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps);
  19939. HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor);
  19940. HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundBuffer* pThis, MA_WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten);
  19941. HRESULT (STDMETHODCALLTYPE * GetVolume) (ma_IDirectSoundBuffer* pThis, LONG* pVolume);
  19942. HRESULT (STDMETHODCALLTYPE * GetPan) (ma_IDirectSoundBuffer* pThis, LONG* pPan);
  19943. HRESULT (STDMETHODCALLTYPE * GetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD* pFrequency);
  19944. HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundBuffer* pThis, DWORD* pStatus);
  19945. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc);
  19946. HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags);
  19947. HRESULT (STDMETHODCALLTYPE * Play) (ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags);
  19948. HRESULT (STDMETHODCALLTYPE * SetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition);
  19949. HRESULT (STDMETHODCALLTYPE * SetFormat) (ma_IDirectSoundBuffer* pThis, const MA_WAVEFORMATEX* pFormat);
  19950. HRESULT (STDMETHODCALLTYPE * SetVolume) (ma_IDirectSoundBuffer* pThis, LONG volume);
  19951. HRESULT (STDMETHODCALLTYPE * SetPan) (ma_IDirectSoundBuffer* pThis, LONG pan);
  19952. HRESULT (STDMETHODCALLTYPE * SetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD dwFrequency);
  19953. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundBuffer* pThis);
  19954. HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2);
  19955. HRESULT (STDMETHODCALLTYPE * Restore) (ma_IDirectSoundBuffer* pThis);
  19956. } ma_IDirectSoundBufferVtbl;
  19957. struct ma_IDirectSoundBuffer
  19958. {
  19959. ma_IDirectSoundBufferVtbl* lpVtbl;
  19960. };
  19961. static MA_INLINE HRESULT ma_IDirectSoundBuffer_QueryInterface(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19962. static MA_INLINE ULONG ma_IDirectSoundBuffer_AddRef(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  19963. static MA_INLINE ULONG ma_IDirectSoundBuffer_Release(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Release(pThis); }
  19964. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCaps(ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSBufferCaps); }
  19965. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCurrentPlayCursor, pCurrentWriteCursor); }
  19966. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetFormat(ma_IDirectSoundBuffer* pThis, MA_WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); }
  19967. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetVolume(ma_IDirectSoundBuffer* pThis, LONG* pVolume) { return pThis->lpVtbl->GetVolume(pThis, pVolume); }
  19968. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetPan(ma_IDirectSoundBuffer* pThis, LONG* pPan) { return pThis->lpVtbl->GetPan(pThis, pPan); }
  19969. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetFrequency(ma_IDirectSoundBuffer* pThis, DWORD* pFrequency) { return pThis->lpVtbl->GetFrequency(pThis, pFrequency); }
  19970. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetStatus(ma_IDirectSoundBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); }
  19971. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Initialize(ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSound, pDSBufferDesc); }
  19972. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Lock(ma_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags) { return pThis->lpVtbl->Lock(pThis, dwOffset, dwBytes, ppAudioPtr1, pAudioBytes1, ppAudioPtr2, pAudioBytes2, dwFlags); }
  19973. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Play(ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags) { return pThis->lpVtbl->Play(pThis, dwReserved1, dwPriority, dwFlags); }
  19974. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition) { return pThis->lpVtbl->SetCurrentPosition(pThis, dwNewPosition); }
  19975. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFormat(ma_IDirectSoundBuffer* pThis, const MA_WAVEFORMATEX* pFormat) { return pThis->lpVtbl->SetFormat(pThis, pFormat); }
  19976. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetVolume(ma_IDirectSoundBuffer* pThis, LONG volume) { return pThis->lpVtbl->SetVolume(pThis, volume); }
  19977. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetPan(ma_IDirectSoundBuffer* pThis, LONG pan) { return pThis->lpVtbl->SetPan(pThis, pan); }
  19978. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFrequency(ma_IDirectSoundBuffer* pThis, DWORD dwFrequency) { return pThis->lpVtbl->SetFrequency(pThis, dwFrequency); }
  19979. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Stop(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); }
  19980. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Unlock(ma_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); }
  19981. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Restore(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Restore(pThis); }
  19982. /* IDirectSoundCapture */
  19983. typedef struct
  19984. {
  19985. /* IUnknown */
  19986. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject);
  19987. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCapture* pThis);
  19988. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCapture* pThis);
  19989. /* IDirectSoundCapture */
  19990. HRESULT (STDMETHODCALLTYPE * CreateCaptureBuffer)(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter);
  19991. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps);
  19992. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice);
  19993. } ma_IDirectSoundCaptureVtbl;
  19994. struct ma_IDirectSoundCapture
  19995. {
  19996. ma_IDirectSoundCaptureVtbl* lpVtbl;
  19997. };
  19998. static MA_INLINE HRESULT ma_IDirectSoundCapture_QueryInterface (ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19999. static MA_INLINE ULONG ma_IDirectSoundCapture_AddRef (ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  20000. static MA_INLINE ULONG ma_IDirectSoundCapture_Release (ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->Release(pThis); }
  20001. static MA_INLINE HRESULT ma_IDirectSoundCapture_CreateCaptureBuffer(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateCaptureBuffer(pThis, pDSCBufferDesc, ppDSCBuffer, pUnkOuter); }
  20002. static MA_INLINE HRESULT ma_IDirectSoundCapture_GetCaps (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCCaps); }
  20003. static MA_INLINE HRESULT ma_IDirectSoundCapture_Initialize (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); }
  20004. /* IDirectSoundCaptureBuffer */
  20005. typedef struct
  20006. {
  20007. /* IUnknown */
  20008. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject);
  20009. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCaptureBuffer* pThis);
  20010. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCaptureBuffer* pThis);
  20011. /* IDirectSoundCaptureBuffer */
  20012. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps);
  20013. HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition);
  20014. HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundCaptureBuffer* pThis, MA_WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten);
  20015. HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus);
  20016. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc);
  20017. HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags);
  20018. HRESULT (STDMETHODCALLTYPE * Start) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags);
  20019. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundCaptureBuffer* pThis);
  20020. HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2);
  20021. } ma_IDirectSoundCaptureBufferVtbl;
  20022. struct ma_IDirectSoundCaptureBuffer
  20023. {
  20024. ma_IDirectSoundCaptureBufferVtbl* lpVtbl;
  20025. };
  20026. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_QueryInterface(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  20027. static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_AddRef(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  20028. static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_Release(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Release(pThis); }
  20029. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCaps(ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCBCaps); }
  20030. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCurrentPosition(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCapturePosition, pReadPosition); }
  20031. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetFormat(ma_IDirectSoundCaptureBuffer* pThis, MA_WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); }
  20032. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetStatus(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); }
  20033. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Initialize(ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSoundCapture, pDSCBufferDesc); }
  20034. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Lock(ma_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags) { return pThis->lpVtbl->Lock(pThis, dwOffset, dwBytes, ppAudioPtr1, pAudioBytes1, ppAudioPtr2, pAudioBytes2, dwFlags); }
  20035. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Start(ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags) { return pThis->lpVtbl->Start(pThis, dwFlags); }
  20036. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Stop(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); }
  20037. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Unlock(ma_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); }
  20038. /* IDirectSoundNotify */
  20039. typedef struct
  20040. {
  20041. /* IUnknown */
  20042. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject);
  20043. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundNotify* pThis);
  20044. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundNotify* pThis);
  20045. /* IDirectSoundNotify */
  20046. HRESULT (STDMETHODCALLTYPE * SetNotificationPositions)(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies);
  20047. } ma_IDirectSoundNotifyVtbl;
  20048. struct ma_IDirectSoundNotify
  20049. {
  20050. ma_IDirectSoundNotifyVtbl* lpVtbl;
  20051. };
  20052. static MA_INLINE HRESULT ma_IDirectSoundNotify_QueryInterface(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  20053. static MA_INLINE ULONG ma_IDirectSoundNotify_AddRef(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  20054. static MA_INLINE ULONG ma_IDirectSoundNotify_Release(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->Release(pThis); }
  20055. static MA_INLINE HRESULT ma_IDirectSoundNotify_SetNotificationPositions(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies) { return pThis->lpVtbl->SetNotificationPositions(pThis, dwPositionNotifies, pPositionNotifies); }
  20056. typedef BOOL (CALLBACK * ma_DSEnumCallbackAProc) (GUID* pDeviceGUID, const char* pDeviceDescription, const char* pModule, void* pContext);
  20057. typedef HRESULT (WINAPI * ma_DirectSoundCreateProc) (const GUID* pcGuidDevice, ma_IDirectSound** ppDS8, ma_IUnknown* pUnkOuter);
  20058. typedef HRESULT (WINAPI * ma_DirectSoundEnumerateAProc) (ma_DSEnumCallbackAProc pDSEnumCallback, void* pContext);
  20059. typedef HRESULT (WINAPI * ma_DirectSoundCaptureCreateProc) (const GUID* pcGuidDevice, ma_IDirectSoundCapture** ppDSC8, ma_IUnknown* pUnkOuter);
  20060. typedef HRESULT (WINAPI * ma_DirectSoundCaptureEnumerateAProc)(ma_DSEnumCallbackAProc pDSEnumCallback, void* pContext);
  20061. static ma_uint32 ma_get_best_sample_rate_within_range(ma_uint32 sampleRateMin, ma_uint32 sampleRateMax)
  20062. {
  20063. /* Normalize the range in case we were given something stupid. */
  20064. if (sampleRateMin < (ma_uint32)ma_standard_sample_rate_min) {
  20065. sampleRateMin = (ma_uint32)ma_standard_sample_rate_min;
  20066. }
  20067. if (sampleRateMax > (ma_uint32)ma_standard_sample_rate_max) {
  20068. sampleRateMax = (ma_uint32)ma_standard_sample_rate_max;
  20069. }
  20070. if (sampleRateMin > sampleRateMax) {
  20071. sampleRateMin = sampleRateMax;
  20072. }
  20073. if (sampleRateMin == sampleRateMax) {
  20074. return sampleRateMax;
  20075. } else {
  20076. size_t iStandardRate;
  20077. for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) {
  20078. ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate];
  20079. if (standardRate >= sampleRateMin && standardRate <= sampleRateMax) {
  20080. return standardRate;
  20081. }
  20082. }
  20083. }
  20084. /* Should never get here. */
  20085. MA_ASSERT(MA_FALSE);
  20086. return 0;
  20087. }
  20088. /*
  20089. Retrieves the channel count and channel map for the given speaker configuration. If the speaker configuration is unknown,
  20090. the channel count and channel map will be left unmodified.
  20091. */
  20092. static void ma_get_channels_from_speaker_config__dsound(DWORD speakerConfig, WORD* pChannelsOut, DWORD* pChannelMapOut)
  20093. {
  20094. WORD channels;
  20095. DWORD channelMap;
  20096. channels = 0;
  20097. if (pChannelsOut != NULL) {
  20098. channels = *pChannelsOut;
  20099. }
  20100. channelMap = 0;
  20101. if (pChannelMapOut != NULL) {
  20102. channelMap = *pChannelMapOut;
  20103. }
  20104. /*
  20105. The speaker configuration is a combination of speaker config and speaker geometry. The lower 8 bits is what we care about. The upper
  20106. 16 bits is for the geometry.
  20107. */
  20108. switch ((BYTE)(speakerConfig)) {
  20109. case 1 /*DSSPEAKER_HEADPHONE*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  20110. case 2 /*DSSPEAKER_MONO*/: channels = 1; channelMap = SPEAKER_FRONT_CENTER; break;
  20111. case 3 /*DSSPEAKER_QUAD*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  20112. case 4 /*DSSPEAKER_STEREO*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  20113. case 5 /*DSSPEAKER_SURROUND*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER; break;
  20114. case 6 /*DSSPEAKER_5POINT1_BACK*/ /*DSSPEAKER_5POINT1*/: channels = 6; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  20115. case 7 /*DSSPEAKER_7POINT1_WIDE*/ /*DSSPEAKER_7POINT1*/: channels = 8; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER; break;
  20116. case 8 /*DSSPEAKER_7POINT1_SURROUND*/: channels = 8; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; break;
  20117. case 9 /*DSSPEAKER_5POINT1_SURROUND*/: channels = 6; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; break;
  20118. default: break;
  20119. }
  20120. if (pChannelsOut != NULL) {
  20121. *pChannelsOut = channels;
  20122. }
  20123. if (pChannelMapOut != NULL) {
  20124. *pChannelMapOut = channelMap;
  20125. }
  20126. }
  20127. static ma_result ma_context_create_IDirectSound__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSound** ppDirectSound)
  20128. {
  20129. ma_IDirectSound* pDirectSound;
  20130. HWND hWnd;
  20131. HRESULT hr;
  20132. MA_ASSERT(pContext != NULL);
  20133. MA_ASSERT(ppDirectSound != NULL);
  20134. *ppDirectSound = NULL;
  20135. pDirectSound = NULL;
  20136. if (FAILED(((ma_DirectSoundCreateProc)pContext->dsound.DirectSoundCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSound, NULL))) {
  20137. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCreate() failed for playback device.");
  20138. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  20139. }
  20140. /* The cooperative level must be set before doing anything else. */
  20141. hWnd = ((MA_PFN_GetForegroundWindow)pContext->win32.GetForegroundWindow)();
  20142. if (hWnd == 0) {
  20143. hWnd = ((MA_PFN_GetDesktopWindow)pContext->win32.GetDesktopWindow)();
  20144. }
  20145. hr = ma_IDirectSound_SetCooperativeLevel(pDirectSound, hWnd, (shareMode == ma_share_mode_exclusive) ? MA_DSSCL_EXCLUSIVE : MA_DSSCL_PRIORITY);
  20146. if (FAILED(hr)) {
  20147. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_SetCooperateiveLevel() failed for playback device.");
  20148. return ma_result_from_HRESULT(hr);
  20149. }
  20150. *ppDirectSound = pDirectSound;
  20151. return MA_SUCCESS;
  20152. }
  20153. static ma_result ma_context_create_IDirectSoundCapture__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSoundCapture** ppDirectSoundCapture)
  20154. {
  20155. ma_IDirectSoundCapture* pDirectSoundCapture;
  20156. HRESULT hr;
  20157. MA_ASSERT(pContext != NULL);
  20158. MA_ASSERT(ppDirectSoundCapture != NULL);
  20159. /* DirectSound does not support exclusive mode for capture. */
  20160. if (shareMode == ma_share_mode_exclusive) {
  20161. return MA_SHARE_MODE_NOT_SUPPORTED;
  20162. }
  20163. *ppDirectSoundCapture = NULL;
  20164. pDirectSoundCapture = NULL;
  20165. hr = ((ma_DirectSoundCaptureCreateProc)pContext->dsound.DirectSoundCaptureCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSoundCapture, NULL);
  20166. if (FAILED(hr)) {
  20167. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCaptureCreate() failed for capture device.");
  20168. return ma_result_from_HRESULT(hr);
  20169. }
  20170. *ppDirectSoundCapture = pDirectSoundCapture;
  20171. return MA_SUCCESS;
  20172. }
  20173. static ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* pContext, ma_IDirectSoundCapture* pDirectSoundCapture, WORD* pChannels, WORD* pBitsPerSample, DWORD* pSampleRate)
  20174. {
  20175. HRESULT hr;
  20176. MA_DSCCAPS caps;
  20177. WORD bitsPerSample;
  20178. DWORD sampleRate;
  20179. MA_ASSERT(pContext != NULL);
  20180. MA_ASSERT(pDirectSoundCapture != NULL);
  20181. if (pChannels) {
  20182. *pChannels = 0;
  20183. }
  20184. if (pBitsPerSample) {
  20185. *pBitsPerSample = 0;
  20186. }
  20187. if (pSampleRate) {
  20188. *pSampleRate = 0;
  20189. }
  20190. MA_ZERO_OBJECT(&caps);
  20191. caps.dwSize = sizeof(caps);
  20192. hr = ma_IDirectSoundCapture_GetCaps(pDirectSoundCapture, &caps);
  20193. if (FAILED(hr)) {
  20194. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_GetCaps() failed for capture device.");
  20195. return ma_result_from_HRESULT(hr);
  20196. }
  20197. if (pChannels) {
  20198. *pChannels = (WORD)caps.dwChannels;
  20199. }
  20200. /* The device can support multiple formats. We just go through the different formats in order of priority and pick the first one. This the same type of system as the WinMM backend. */
  20201. bitsPerSample = 16;
  20202. sampleRate = 48000;
  20203. if (caps.dwChannels == 1) {
  20204. if ((caps.dwFormats & WAVE_FORMAT_48M16) != 0) {
  20205. sampleRate = 48000;
  20206. } else if ((caps.dwFormats & WAVE_FORMAT_44M16) != 0) {
  20207. sampleRate = 44100;
  20208. } else if ((caps.dwFormats & WAVE_FORMAT_2M16) != 0) {
  20209. sampleRate = 22050;
  20210. } else if ((caps.dwFormats & WAVE_FORMAT_1M16) != 0) {
  20211. sampleRate = 11025;
  20212. } else if ((caps.dwFormats & WAVE_FORMAT_96M16) != 0) {
  20213. sampleRate = 96000;
  20214. } else {
  20215. bitsPerSample = 8;
  20216. if ((caps.dwFormats & WAVE_FORMAT_48M08) != 0) {
  20217. sampleRate = 48000;
  20218. } else if ((caps.dwFormats & WAVE_FORMAT_44M08) != 0) {
  20219. sampleRate = 44100;
  20220. } else if ((caps.dwFormats & WAVE_FORMAT_2M08) != 0) {
  20221. sampleRate = 22050;
  20222. } else if ((caps.dwFormats & WAVE_FORMAT_1M08) != 0) {
  20223. sampleRate = 11025;
  20224. } else if ((caps.dwFormats & WAVE_FORMAT_96M08) != 0) {
  20225. sampleRate = 96000;
  20226. } else {
  20227. bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */
  20228. }
  20229. }
  20230. } else if (caps.dwChannels == 2) {
  20231. if ((caps.dwFormats & WAVE_FORMAT_48S16) != 0) {
  20232. sampleRate = 48000;
  20233. } else if ((caps.dwFormats & WAVE_FORMAT_44S16) != 0) {
  20234. sampleRate = 44100;
  20235. } else if ((caps.dwFormats & WAVE_FORMAT_2S16) != 0) {
  20236. sampleRate = 22050;
  20237. } else if ((caps.dwFormats & WAVE_FORMAT_1S16) != 0) {
  20238. sampleRate = 11025;
  20239. } else if ((caps.dwFormats & WAVE_FORMAT_96S16) != 0) {
  20240. sampleRate = 96000;
  20241. } else {
  20242. bitsPerSample = 8;
  20243. if ((caps.dwFormats & WAVE_FORMAT_48S08) != 0) {
  20244. sampleRate = 48000;
  20245. } else if ((caps.dwFormats & WAVE_FORMAT_44S08) != 0) {
  20246. sampleRate = 44100;
  20247. } else if ((caps.dwFormats & WAVE_FORMAT_2S08) != 0) {
  20248. sampleRate = 22050;
  20249. } else if ((caps.dwFormats & WAVE_FORMAT_1S08) != 0) {
  20250. sampleRate = 11025;
  20251. } else if ((caps.dwFormats & WAVE_FORMAT_96S08) != 0) {
  20252. sampleRate = 96000;
  20253. } else {
  20254. bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */
  20255. }
  20256. }
  20257. }
  20258. if (pBitsPerSample) {
  20259. *pBitsPerSample = bitsPerSample;
  20260. }
  20261. if (pSampleRate) {
  20262. *pSampleRate = sampleRate;
  20263. }
  20264. return MA_SUCCESS;
  20265. }
  20266. typedef struct
  20267. {
  20268. ma_context* pContext;
  20269. ma_device_type deviceType;
  20270. ma_enum_devices_callback_proc callback;
  20271. void* pUserData;
  20272. ma_bool32 terminated;
  20273. } ma_context_enumerate_devices_callback_data__dsound;
  20274. static BOOL CALLBACK ma_context_enumerate_devices_callback__dsound(GUID* lpGuid, const char* lpcstrDescription, const char* lpcstrModule, void* lpContext)
  20275. {
  20276. ma_context_enumerate_devices_callback_data__dsound* pData = (ma_context_enumerate_devices_callback_data__dsound*)lpContext;
  20277. ma_device_info deviceInfo;
  20278. (void)lpcstrModule;
  20279. MA_ZERO_OBJECT(&deviceInfo);
  20280. /* ID. */
  20281. if (lpGuid != NULL) {
  20282. MA_COPY_MEMORY(deviceInfo.id.dsound, lpGuid, 16);
  20283. } else {
  20284. MA_ZERO_MEMORY(deviceInfo.id.dsound, 16);
  20285. deviceInfo.isDefault = MA_TRUE;
  20286. }
  20287. /* Name / Description */
  20288. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), lpcstrDescription, (size_t)-1);
  20289. /* Call the callback function, but make sure we stop enumerating if the callee requested so. */
  20290. MA_ASSERT(pData != NULL);
  20291. pData->terminated = !pData->callback(pData->pContext, pData->deviceType, &deviceInfo, pData->pUserData);
  20292. if (pData->terminated) {
  20293. return FALSE; /* Stop enumeration. */
  20294. } else {
  20295. return TRUE; /* Continue enumeration. */
  20296. }
  20297. }
  20298. static ma_result ma_context_enumerate_devices__dsound(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  20299. {
  20300. ma_context_enumerate_devices_callback_data__dsound data;
  20301. MA_ASSERT(pContext != NULL);
  20302. MA_ASSERT(callback != NULL);
  20303. data.pContext = pContext;
  20304. data.callback = callback;
  20305. data.pUserData = pUserData;
  20306. data.terminated = MA_FALSE;
  20307. /* Playback. */
  20308. if (!data.terminated) {
  20309. data.deviceType = ma_device_type_playback;
  20310. ((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data);
  20311. }
  20312. /* Capture. */
  20313. if (!data.terminated) {
  20314. data.deviceType = ma_device_type_capture;
  20315. ((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data);
  20316. }
  20317. return MA_SUCCESS;
  20318. }
  20319. typedef struct
  20320. {
  20321. const ma_device_id* pDeviceID;
  20322. ma_device_info* pDeviceInfo;
  20323. ma_bool32 found;
  20324. } ma_context_get_device_info_callback_data__dsound;
  20325. static BOOL CALLBACK ma_context_get_device_info_callback__dsound(GUID* lpGuid, const char* lpcstrDescription, const char* lpcstrModule, void* lpContext)
  20326. {
  20327. ma_context_get_device_info_callback_data__dsound* pData = (ma_context_get_device_info_callback_data__dsound*)lpContext;
  20328. MA_ASSERT(pData != NULL);
  20329. if ((pData->pDeviceID == NULL || ma_is_guid_null(pData->pDeviceID->dsound)) && (lpGuid == NULL || ma_is_guid_null(lpGuid))) {
  20330. /* Default device. */
  20331. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1);
  20332. pData->pDeviceInfo->isDefault = MA_TRUE;
  20333. pData->found = MA_TRUE;
  20334. return FALSE; /* Stop enumeration. */
  20335. } else {
  20336. /* Not the default device. */
  20337. if (lpGuid != NULL && pData->pDeviceID != NULL) {
  20338. if (memcmp(pData->pDeviceID->dsound, lpGuid, sizeof(pData->pDeviceID->dsound)) == 0) {
  20339. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1);
  20340. pData->found = MA_TRUE;
  20341. return FALSE; /* Stop enumeration. */
  20342. }
  20343. }
  20344. }
  20345. (void)lpcstrModule;
  20346. return TRUE;
  20347. }
  20348. static ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  20349. {
  20350. ma_result result;
  20351. HRESULT hr;
  20352. if (pDeviceID != NULL) {
  20353. ma_context_get_device_info_callback_data__dsound data;
  20354. /* ID. */
  20355. MA_COPY_MEMORY(pDeviceInfo->id.dsound, pDeviceID->dsound, 16);
  20356. /* Name / Description. This is retrieved by enumerating over each device until we find that one that matches the input ID. */
  20357. data.pDeviceID = pDeviceID;
  20358. data.pDeviceInfo = pDeviceInfo;
  20359. data.found = MA_FALSE;
  20360. if (deviceType == ma_device_type_playback) {
  20361. ((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_get_device_info_callback__dsound, &data);
  20362. } else {
  20363. ((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_get_device_info_callback__dsound, &data);
  20364. }
  20365. if (!data.found) {
  20366. return MA_NO_DEVICE;
  20367. }
  20368. } else {
  20369. /* I don't think there's a way to get the name of the default device with DirectSound. In this case we just need to use defaults. */
  20370. /* ID */
  20371. MA_ZERO_MEMORY(pDeviceInfo->id.dsound, 16);
  20372. /* Name / Description */
  20373. if (deviceType == ma_device_type_playback) {
  20374. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  20375. } else {
  20376. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  20377. }
  20378. pDeviceInfo->isDefault = MA_TRUE;
  20379. }
  20380. /* Retrieving detailed information is slightly different depending on the device type. */
  20381. if (deviceType == ma_device_type_playback) {
  20382. /* Playback. */
  20383. ma_IDirectSound* pDirectSound;
  20384. MA_DSCAPS caps;
  20385. WORD channels;
  20386. result = ma_context_create_IDirectSound__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSound);
  20387. if (result != MA_SUCCESS) {
  20388. return result;
  20389. }
  20390. MA_ZERO_OBJECT(&caps);
  20391. caps.dwSize = sizeof(caps);
  20392. hr = ma_IDirectSound_GetCaps(pDirectSound, &caps);
  20393. if (FAILED(hr)) {
  20394. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.");
  20395. return ma_result_from_HRESULT(hr);
  20396. }
  20397. /* Channels. Only a single channel count is reported for DirectSound. */
  20398. if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) {
  20399. /* It supports at least stereo, but could support more. */
  20400. DWORD speakerConfig;
  20401. channels = 2;
  20402. /* Look at the speaker configuration to get a better idea on the channel count. */
  20403. hr = ma_IDirectSound_GetSpeakerConfig(pDirectSound, &speakerConfig);
  20404. if (SUCCEEDED(hr)) {
  20405. ma_get_channels_from_speaker_config__dsound(speakerConfig, &channels, NULL);
  20406. }
  20407. } else {
  20408. /* It does not support stereo, which means we are stuck with mono. */
  20409. channels = 1;
  20410. }
  20411. /*
  20412. In DirectSound, our native formats are centered around sample rates. All formats are supported, and we're only reporting a single channel
  20413. count. However, DirectSound can report a range of supported sample rates. We're only going to include standard rates known by miniaudio
  20414. in order to keep the size of this within reason.
  20415. */
  20416. if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) {
  20417. /* Multiple sample rates are supported. We'll report in order of our preferred sample rates. */
  20418. size_t iStandardSampleRate;
  20419. for (iStandardSampleRate = 0; iStandardSampleRate < ma_countof(g_maStandardSampleRatePriorities); iStandardSampleRate += 1) {
  20420. ma_uint32 sampleRate = g_maStandardSampleRatePriorities[iStandardSampleRate];
  20421. if (sampleRate >= caps.dwMinSecondarySampleRate && sampleRate <= caps.dwMaxSecondarySampleRate) {
  20422. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown;
  20423. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  20424. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  20425. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  20426. pDeviceInfo->nativeDataFormatCount += 1;
  20427. }
  20428. }
  20429. } else {
  20430. /* Only a single sample rate is supported. */
  20431. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown;
  20432. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  20433. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = caps.dwMaxSecondarySampleRate;
  20434. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  20435. pDeviceInfo->nativeDataFormatCount += 1;
  20436. }
  20437. ma_IDirectSound_Release(pDirectSound);
  20438. } else {
  20439. /*
  20440. Capture. This is a little different to playback due to the say the supported formats are reported. Technically capture
  20441. devices can support a number of different formats, but for simplicity and consistency with ma_device_init() I'm just
  20442. reporting the best format.
  20443. */
  20444. ma_IDirectSoundCapture* pDirectSoundCapture;
  20445. WORD channels;
  20446. WORD bitsPerSample;
  20447. DWORD sampleRate;
  20448. result = ma_context_create_IDirectSoundCapture__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSoundCapture);
  20449. if (result != MA_SUCCESS) {
  20450. return result;
  20451. }
  20452. result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, pDirectSoundCapture, &channels, &bitsPerSample, &sampleRate);
  20453. if (result != MA_SUCCESS) {
  20454. ma_IDirectSoundCapture_Release(pDirectSoundCapture);
  20455. return result;
  20456. }
  20457. ma_IDirectSoundCapture_Release(pDirectSoundCapture);
  20458. /* The format is always an integer format and is based on the bits per sample. */
  20459. if (bitsPerSample == 8) {
  20460. pDeviceInfo->nativeDataFormats[0].format = ma_format_u8;
  20461. } else if (bitsPerSample == 16) {
  20462. pDeviceInfo->nativeDataFormats[0].format = ma_format_s16;
  20463. } else if (bitsPerSample == 24) {
  20464. pDeviceInfo->nativeDataFormats[0].format = ma_format_s24;
  20465. } else if (bitsPerSample == 32) {
  20466. pDeviceInfo->nativeDataFormats[0].format = ma_format_s32;
  20467. } else {
  20468. return MA_FORMAT_NOT_SUPPORTED;
  20469. }
  20470. pDeviceInfo->nativeDataFormats[0].channels = channels;
  20471. pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate;
  20472. pDeviceInfo->nativeDataFormats[0].flags = 0;
  20473. pDeviceInfo->nativeDataFormatCount = 1;
  20474. }
  20475. return MA_SUCCESS;
  20476. }
  20477. static ma_result ma_device_uninit__dsound(ma_device* pDevice)
  20478. {
  20479. MA_ASSERT(pDevice != NULL);
  20480. if (pDevice->dsound.pCaptureBuffer != NULL) {
  20481. ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  20482. }
  20483. if (pDevice->dsound.pCapture != NULL) {
  20484. ma_IDirectSoundCapture_Release((ma_IDirectSoundCapture*)pDevice->dsound.pCapture);
  20485. }
  20486. if (pDevice->dsound.pPlaybackBuffer != NULL) {
  20487. ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer);
  20488. }
  20489. if (pDevice->dsound.pPlaybackPrimaryBuffer != NULL) {
  20490. ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer);
  20491. }
  20492. if (pDevice->dsound.pPlayback != NULL) {
  20493. ma_IDirectSound_Release((ma_IDirectSound*)pDevice->dsound.pPlayback);
  20494. }
  20495. return MA_SUCCESS;
  20496. }
  20497. static ma_result ma_config_to_WAVEFORMATEXTENSIBLE(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* pChannelMap, MA_WAVEFORMATEXTENSIBLE* pWF)
  20498. {
  20499. GUID subformat;
  20500. if (format == ma_format_unknown) {
  20501. format = MA_DEFAULT_FORMAT;
  20502. }
  20503. if (channels == 0) {
  20504. channels = MA_DEFAULT_CHANNELS;
  20505. }
  20506. if (sampleRate == 0) {
  20507. sampleRate = MA_DEFAULT_SAMPLE_RATE;
  20508. }
  20509. switch (format)
  20510. {
  20511. case ma_format_u8:
  20512. case ma_format_s16:
  20513. case ma_format_s24:
  20514. /*case ma_format_s24_32:*/
  20515. case ma_format_s32:
  20516. {
  20517. subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
  20518. } break;
  20519. case ma_format_f32:
  20520. {
  20521. subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  20522. } break;
  20523. default:
  20524. return MA_FORMAT_NOT_SUPPORTED;
  20525. }
  20526. MA_ZERO_OBJECT(pWF);
  20527. pWF->cbSize = sizeof(*pWF);
  20528. pWF->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  20529. pWF->nChannels = (WORD)channels;
  20530. pWF->nSamplesPerSec = (DWORD)sampleRate;
  20531. pWF->wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8);
  20532. pWF->nBlockAlign = (WORD)(pWF->nChannels * pWF->wBitsPerSample / 8);
  20533. pWF->nAvgBytesPerSec = pWF->nBlockAlign * pWF->nSamplesPerSec;
  20534. pWF->Samples.wValidBitsPerSample = pWF->wBitsPerSample;
  20535. pWF->dwChannelMask = ma_channel_map_to_channel_mask__win32(pChannelMap, channels);
  20536. pWF->SubFormat = subformat;
  20537. return MA_SUCCESS;
  20538. }
  20539. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__dsound(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  20540. {
  20541. /*
  20542. DirectSound has a minimum period size of 20ms. In practice, this doesn't seem to be enough for
  20543. reliable glitch-free processing so going to use 30ms instead.
  20544. */
  20545. ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(30, nativeSampleRate);
  20546. ma_uint32 periodSizeInFrames;
  20547. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, nativeSampleRate, performanceProfile);
  20548. if (periodSizeInFrames < minPeriodSizeInFrames) {
  20549. periodSizeInFrames = minPeriodSizeInFrames;
  20550. }
  20551. return periodSizeInFrames;
  20552. }
  20553. static ma_result ma_device_init__dsound(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  20554. {
  20555. ma_result result;
  20556. HRESULT hr;
  20557. MA_ASSERT(pDevice != NULL);
  20558. MA_ZERO_OBJECT(&pDevice->dsound);
  20559. if (pConfig->deviceType == ma_device_type_loopback) {
  20560. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  20561. }
  20562. /*
  20563. Unfortunately DirectSound uses different APIs and data structures for playback and catpure devices. We need to initialize
  20564. the capture device first because we'll want to match it's buffer size and period count on the playback side if we're using
  20565. full-duplex mode.
  20566. */
  20567. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  20568. MA_WAVEFORMATEXTENSIBLE wf;
  20569. MA_DSCBUFFERDESC descDS;
  20570. ma_uint32 periodSizeInFrames;
  20571. ma_uint32 periodCount;
  20572. char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */
  20573. MA_WAVEFORMATEXTENSIBLE* pActualFormat;
  20574. result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorCapture->format, pDescriptorCapture->channels, pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, &wf);
  20575. if (result != MA_SUCCESS) {
  20576. return result;
  20577. }
  20578. result = ma_context_create_IDirectSoundCapture__dsound(pDevice->pContext, pDescriptorCapture->shareMode, pDescriptorCapture->pDeviceID, (ma_IDirectSoundCapture**)&pDevice->dsound.pCapture);
  20579. if (result != MA_SUCCESS) {
  20580. ma_device_uninit__dsound(pDevice);
  20581. return result;
  20582. }
  20583. result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pDevice->pContext, (ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &wf.nChannels, &wf.wBitsPerSample, &wf.nSamplesPerSec);
  20584. if (result != MA_SUCCESS) {
  20585. ma_device_uninit__dsound(pDevice);
  20586. return result;
  20587. }
  20588. wf.nBlockAlign = (WORD)(wf.nChannels * wf.wBitsPerSample / 8);
  20589. wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
  20590. wf.Samples.wValidBitsPerSample = wf.wBitsPerSample;
  20591. wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
  20592. /* The size of the buffer must be a clean multiple of the period count. */
  20593. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__dsound(pDescriptorCapture, wf.nSamplesPerSec, pConfig->performanceProfile);
  20594. periodCount = (pDescriptorCapture->periodCount > 0) ? pDescriptorCapture->periodCount : MA_DEFAULT_PERIODS;
  20595. MA_ZERO_OBJECT(&descDS);
  20596. descDS.dwSize = sizeof(descDS);
  20597. descDS.dwFlags = 0;
  20598. descDS.dwBufferBytes = periodSizeInFrames * periodCount * wf.nBlockAlign;
  20599. descDS.lpwfxFormat = (MA_WAVEFORMATEX*)&wf;
  20600. hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL);
  20601. if (FAILED(hr)) {
  20602. ma_device_uninit__dsound(pDevice);
  20603. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.");
  20604. return ma_result_from_HRESULT(hr);
  20605. }
  20606. /* Get the _actual_ properties of the buffer. */
  20607. pActualFormat = (MA_WAVEFORMATEXTENSIBLE*)rawdata;
  20608. hr = ma_IDirectSoundCaptureBuffer_GetFormat((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, (MA_WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL);
  20609. if (FAILED(hr)) {
  20610. ma_device_uninit__dsound(pDevice);
  20611. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the capture device's buffer.");
  20612. return ma_result_from_HRESULT(hr);
  20613. }
  20614. /* We can now start setting the output data formats. */
  20615. pDescriptorCapture->format = ma_format_from_WAVEFORMATEX((MA_WAVEFORMATEX*)pActualFormat);
  20616. pDescriptorCapture->channels = pActualFormat->nChannels;
  20617. pDescriptorCapture->sampleRate = pActualFormat->nSamplesPerSec;
  20618. /* Get the native channel map based on the channel mask. */
  20619. if (pActualFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  20620. ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
  20621. } else {
  20622. ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
  20623. }
  20624. /*
  20625. After getting the actual format the size of the buffer in frames may have actually changed. However, we want this to be as close to what the
  20626. user has asked for as possible, so let's go ahead and release the old capture buffer and create a new one in this case.
  20627. */
  20628. if (periodSizeInFrames != (descDS.dwBufferBytes / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / periodCount)) {
  20629. descDS.dwBufferBytes = periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) * periodCount;
  20630. ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  20631. hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL);
  20632. if (FAILED(hr)) {
  20633. ma_device_uninit__dsound(pDevice);
  20634. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Second attempt at IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.");
  20635. return ma_result_from_HRESULT(hr);
  20636. }
  20637. }
  20638. /* DirectSound should give us a buffer exactly the size we asked for. */
  20639. pDescriptorCapture->periodSizeInFrames = periodSizeInFrames;
  20640. pDescriptorCapture->periodCount = periodCount;
  20641. }
  20642. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  20643. MA_WAVEFORMATEXTENSIBLE wf;
  20644. MA_DSBUFFERDESC descDSPrimary;
  20645. MA_DSCAPS caps;
  20646. char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */
  20647. MA_WAVEFORMATEXTENSIBLE* pActualFormat;
  20648. ma_uint32 periodSizeInFrames;
  20649. ma_uint32 periodCount;
  20650. MA_DSBUFFERDESC descDS;
  20651. WORD nativeChannelCount;
  20652. DWORD nativeChannelMask = 0;
  20653. result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorPlayback->format, pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, &wf);
  20654. if (result != MA_SUCCESS) {
  20655. return result;
  20656. }
  20657. result = ma_context_create_IDirectSound__dsound(pDevice->pContext, pDescriptorPlayback->shareMode, pDescriptorPlayback->pDeviceID, (ma_IDirectSound**)&pDevice->dsound.pPlayback);
  20658. if (result != MA_SUCCESS) {
  20659. ma_device_uninit__dsound(pDevice);
  20660. return result;
  20661. }
  20662. MA_ZERO_OBJECT(&descDSPrimary);
  20663. descDSPrimary.dwSize = sizeof(MA_DSBUFFERDESC);
  20664. descDSPrimary.dwFlags = MA_DSBCAPS_PRIMARYBUFFER | MA_DSBCAPS_CTRLVOLUME;
  20665. hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDSPrimary, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackPrimaryBuffer, NULL);
  20666. if (FAILED(hr)) {
  20667. ma_device_uninit__dsound(pDevice);
  20668. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's primary buffer.");
  20669. return ma_result_from_HRESULT(hr);
  20670. }
  20671. /* We may want to make some adjustments to the format if we are using defaults. */
  20672. MA_ZERO_OBJECT(&caps);
  20673. caps.dwSize = sizeof(caps);
  20674. hr = ma_IDirectSound_GetCaps((ma_IDirectSound*)pDevice->dsound.pPlayback, &caps);
  20675. if (FAILED(hr)) {
  20676. ma_device_uninit__dsound(pDevice);
  20677. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.");
  20678. return ma_result_from_HRESULT(hr);
  20679. }
  20680. if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) {
  20681. DWORD speakerConfig;
  20682. /* It supports at least stereo, but could support more. */
  20683. nativeChannelCount = 2;
  20684. /* Look at the speaker configuration to get a better idea on the channel count. */
  20685. if (SUCCEEDED(ma_IDirectSound_GetSpeakerConfig((ma_IDirectSound*)pDevice->dsound.pPlayback, &speakerConfig))) {
  20686. ma_get_channels_from_speaker_config__dsound(speakerConfig, &nativeChannelCount, &nativeChannelMask);
  20687. }
  20688. } else {
  20689. /* It does not support stereo, which means we are stuck with mono. */
  20690. nativeChannelCount = 1;
  20691. nativeChannelMask = 0x00000001;
  20692. }
  20693. if (pDescriptorPlayback->channels == 0) {
  20694. wf.nChannels = nativeChannelCount;
  20695. wf.dwChannelMask = nativeChannelMask;
  20696. }
  20697. if (pDescriptorPlayback->sampleRate == 0) {
  20698. /* We base the sample rate on the values returned by GetCaps(). */
  20699. if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) {
  20700. wf.nSamplesPerSec = ma_get_best_sample_rate_within_range(caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate);
  20701. } else {
  20702. wf.nSamplesPerSec = caps.dwMaxSecondarySampleRate;
  20703. }
  20704. }
  20705. wf.nBlockAlign = (WORD)(wf.nChannels * wf.wBitsPerSample / 8);
  20706. wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
  20707. /*
  20708. From MSDN:
  20709. The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest
  20710. supported format. To determine whether this has happened, an application can call the GetFormat method for the primary buffer
  20711. and compare the result with the format that was requested with the SetFormat method.
  20712. */
  20713. hr = ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (MA_WAVEFORMATEX*)&wf);
  20714. if (FAILED(hr)) {
  20715. /*
  20716. If setting of the format failed we'll try again with some fallback settings. On Windows 98 I have
  20717. observed that IEEE_FLOAT does not work. We'll therefore enforce PCM. I also had issues where a
  20718. sample rate of 48000 did not work correctly. Not sure if it was a driver issue or not, but will
  20719. use 44100 for the sample rate.
  20720. */
  20721. wf.cbSize = 18; /* NOTE: Don't use sizeof(MA_WAVEFORMATEX) here because it's got an extra 2 bytes due to padding. */
  20722. wf.wFormatTag = WAVE_FORMAT_PCM;
  20723. wf.wBitsPerSample = 16;
  20724. wf.nChannels = nativeChannelCount;
  20725. wf.nSamplesPerSec = 44100;
  20726. wf.nBlockAlign = wf.nChannels * (wf.wBitsPerSample / 8);
  20727. wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
  20728. hr = ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (MA_WAVEFORMATEX*)&wf);
  20729. if (FAILED(hr)) {
  20730. ma_device_uninit__dsound(pDevice);
  20731. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to set format of playback device's primary buffer.");
  20732. return ma_result_from_HRESULT(hr);
  20733. }
  20734. }
  20735. /* Get the _actual_ properties of the buffer. */
  20736. pActualFormat = (MA_WAVEFORMATEXTENSIBLE*)rawdata;
  20737. hr = ma_IDirectSoundBuffer_GetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (MA_WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL);
  20738. if (FAILED(hr)) {
  20739. ma_device_uninit__dsound(pDevice);
  20740. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the playback device's primary buffer.");
  20741. return ma_result_from_HRESULT(hr);
  20742. }
  20743. /* We now have enough information to start setting some output properties. */
  20744. pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX((MA_WAVEFORMATEX*)pActualFormat);
  20745. pDescriptorPlayback->channels = pActualFormat->nChannels;
  20746. pDescriptorPlayback->sampleRate = pActualFormat->nSamplesPerSec;
  20747. /* Get the internal channel map based on the channel mask. */
  20748. if (pActualFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  20749. ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
  20750. } else {
  20751. ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
  20752. }
  20753. /* The size of the buffer must be a clean multiple of the period count. */
  20754. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__dsound(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  20755. periodCount = (pDescriptorPlayback->periodCount > 0) ? pDescriptorPlayback->periodCount : MA_DEFAULT_PERIODS;
  20756. /*
  20757. Meaning of dwFlags (from MSDN):
  20758. DSBCAPS_CTRLPOSITIONNOTIFY
  20759. The buffer has position notification capability.
  20760. DSBCAPS_GLOBALFOCUS
  20761. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to
  20762. another application, even if the new application uses DirectSound.
  20763. DSBCAPS_GETCURRENTPOSITION2
  20764. In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated
  20765. sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the
  20766. application can get a more accurate play cursor.
  20767. */
  20768. MA_ZERO_OBJECT(&descDS);
  20769. descDS.dwSize = sizeof(descDS);
  20770. descDS.dwFlags = MA_DSBCAPS_CTRLPOSITIONNOTIFY | MA_DSBCAPS_GLOBALFOCUS | MA_DSBCAPS_GETCURRENTPOSITION2;
  20771. descDS.dwBufferBytes = periodSizeInFrames * periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels);
  20772. descDS.lpwfxFormat = (MA_WAVEFORMATEX*)pActualFormat;
  20773. hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDS, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackBuffer, NULL);
  20774. if (FAILED(hr)) {
  20775. ma_device_uninit__dsound(pDevice);
  20776. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's secondary buffer.");
  20777. return ma_result_from_HRESULT(hr);
  20778. }
  20779. /* DirectSound should give us a buffer exactly the size we asked for. */
  20780. pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames;
  20781. pDescriptorPlayback->periodCount = periodCount;
  20782. }
  20783. return MA_SUCCESS;
  20784. }
  20785. static ma_result ma_device_data_loop__dsound(ma_device* pDevice)
  20786. {
  20787. ma_result result = MA_SUCCESS;
  20788. ma_uint32 bpfDeviceCapture = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  20789. ma_uint32 bpfDevicePlayback = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  20790. HRESULT hr;
  20791. DWORD lockOffsetInBytesCapture;
  20792. DWORD lockSizeInBytesCapture;
  20793. DWORD mappedSizeInBytesCapture;
  20794. DWORD mappedDeviceFramesProcessedCapture;
  20795. void* pMappedDeviceBufferCapture;
  20796. DWORD lockOffsetInBytesPlayback;
  20797. DWORD lockSizeInBytesPlayback;
  20798. DWORD mappedSizeInBytesPlayback;
  20799. void* pMappedDeviceBufferPlayback;
  20800. DWORD prevReadCursorInBytesCapture = 0;
  20801. DWORD prevPlayCursorInBytesPlayback = 0;
  20802. ma_bool32 physicalPlayCursorLoopFlagPlayback = 0;
  20803. DWORD virtualWriteCursorInBytesPlayback = 0;
  20804. ma_bool32 virtualWriteCursorLoopFlagPlayback = 0;
  20805. ma_bool32 isPlaybackDeviceStarted = MA_FALSE;
  20806. ma_uint32 framesWrittenToPlaybackDevice = 0; /* For knowing whether or not the playback device needs to be started. */
  20807. ma_uint32 waitTimeInMilliseconds = 1;
  20808. MA_ASSERT(pDevice != NULL);
  20809. /* The first thing to do is start the capture device. The playback device is only started after the first period is written. */
  20810. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  20811. hr = ma_IDirectSoundCaptureBuffer_Start((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, MA_DSCBSTART_LOOPING);
  20812. if (FAILED(hr)) {
  20813. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Start() failed.");
  20814. return ma_result_from_HRESULT(hr);
  20815. }
  20816. }
  20817. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  20818. switch (pDevice->type)
  20819. {
  20820. case ma_device_type_duplex:
  20821. {
  20822. DWORD physicalCaptureCursorInBytes;
  20823. DWORD physicalReadCursorInBytes;
  20824. hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes);
  20825. if (FAILED(hr)) {
  20826. return ma_result_from_HRESULT(hr);
  20827. }
  20828. /* If nothing is available we just sleep for a bit and return from this iteration. */
  20829. if (physicalReadCursorInBytes == prevReadCursorInBytesCapture) {
  20830. ma_sleep(waitTimeInMilliseconds);
  20831. continue; /* Nothing is available in the capture buffer. */
  20832. }
  20833. /*
  20834. The current position has moved. We need to map all of the captured samples and write them to the playback device, making sure
  20835. we don't return until every frame has been copied over.
  20836. */
  20837. if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) {
  20838. /* The capture position has not looped. This is the simple case. */
  20839. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  20840. lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture);
  20841. } else {
  20842. /*
  20843. The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything,
  20844. do it again from the start.
  20845. */
  20846. if (prevReadCursorInBytesCapture < pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) {
  20847. /* Lock up to the end of the buffer. */
  20848. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  20849. lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - prevReadCursorInBytesCapture;
  20850. } else {
  20851. /* Lock starting from the start of the buffer. */
  20852. lockOffsetInBytesCapture = 0;
  20853. lockSizeInBytesCapture = physicalReadCursorInBytes;
  20854. }
  20855. }
  20856. if (lockSizeInBytesCapture == 0) {
  20857. ma_sleep(waitTimeInMilliseconds);
  20858. continue; /* Nothing is available in the capture buffer. */
  20859. }
  20860. hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0);
  20861. if (FAILED(hr)) {
  20862. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from capture device in preparation for writing to the device.");
  20863. return ma_result_from_HRESULT(hr);
  20864. }
  20865. /* At this point we have some input data that we need to output. We do not return until every mapped frame of the input data is written to the playback device. */
  20866. mappedDeviceFramesProcessedCapture = 0;
  20867. for (;;) { /* Keep writing to the playback device. */
  20868. ma_uint8 inputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  20869. ma_uint32 inputFramesInClientFormatCap = sizeof(inputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  20870. ma_uint8 outputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  20871. ma_uint32 outputFramesInClientFormatCap = sizeof(outputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  20872. ma_uint32 outputFramesInClientFormatCount;
  20873. ma_uint32 outputFramesInClientFormatConsumed = 0;
  20874. ma_uint64 clientCapturedFramesToProcess = ma_min(inputFramesInClientFormatCap, outputFramesInClientFormatCap);
  20875. ma_uint64 deviceCapturedFramesToProcess = (mappedSizeInBytesCapture / bpfDeviceCapture) - mappedDeviceFramesProcessedCapture;
  20876. void* pRunningMappedDeviceBufferCapture = ma_offset_ptr(pMappedDeviceBufferCapture, mappedDeviceFramesProcessedCapture * bpfDeviceCapture);
  20877. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningMappedDeviceBufferCapture, &deviceCapturedFramesToProcess, inputFramesInClientFormat, &clientCapturedFramesToProcess);
  20878. if (result != MA_SUCCESS) {
  20879. break;
  20880. }
  20881. outputFramesInClientFormatCount = (ma_uint32)clientCapturedFramesToProcess;
  20882. mappedDeviceFramesProcessedCapture += (ma_uint32)deviceCapturedFramesToProcess;
  20883. ma_device__handle_data_callback(pDevice, outputFramesInClientFormat, inputFramesInClientFormat, (ma_uint32)clientCapturedFramesToProcess);
  20884. /* At this point we have input and output data in client format. All we need to do now is convert it to the output device format. This may take a few passes. */
  20885. for (;;) {
  20886. ma_uint32 framesWrittenThisIteration;
  20887. DWORD physicalPlayCursorInBytes;
  20888. DWORD physicalWriteCursorInBytes;
  20889. DWORD availableBytesPlayback;
  20890. DWORD silentPaddingInBytes = 0; /* <-- Must be initialized to 0. */
  20891. /* We need the physical play and write cursors. */
  20892. if (FAILED(ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes))) {
  20893. break;
  20894. }
  20895. if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
  20896. physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
  20897. }
  20898. prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
  20899. /* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */
  20900. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  20901. /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
  20902. if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
  20903. availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  20904. availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
  20905. } else {
  20906. /* This is an error. */
  20907. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Duplex/Playback): Play cursor has moved in front of the write cursor (same loop iteration). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback);
  20908. availableBytesPlayback = 0;
  20909. }
  20910. } else {
  20911. /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
  20912. if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
  20913. availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  20914. } else {
  20915. /* This is an error. */
  20916. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Duplex/Playback): Write cursor has moved behind the play cursor (different loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback);
  20917. availableBytesPlayback = 0;
  20918. }
  20919. }
  20920. /* If there's no room available for writing we need to wait for more. */
  20921. if (availableBytesPlayback == 0) {
  20922. /* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */
  20923. if (!isPlaybackDeviceStarted) {
  20924. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  20925. if (FAILED(hr)) {
  20926. ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  20927. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  20928. return ma_result_from_HRESULT(hr);
  20929. }
  20930. isPlaybackDeviceStarted = MA_TRUE;
  20931. } else {
  20932. ma_sleep(waitTimeInMilliseconds);
  20933. continue;
  20934. }
  20935. }
  20936. /* Getting here means there room available somewhere. We limit this to either the end of the buffer or the physical play cursor, whichever is closest. */
  20937. lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback;
  20938. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  20939. /* Same loop iteration. Go up to the end of the buffer. */
  20940. lockSizeInBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  20941. } else {
  20942. /* Different loop iterations. Go up to the physical play cursor. */
  20943. lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  20944. }
  20945. hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0);
  20946. if (FAILED(hr)) {
  20947. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from playback device in preparation for writing to the device.");
  20948. result = ma_result_from_HRESULT(hr);
  20949. break;
  20950. }
  20951. /*
  20952. Experiment: If the playback buffer is being starved, pad it with some silence to get it back in sync. This will cause a glitch, but it may prevent
  20953. endless glitching due to it constantly running out of data.
  20954. */
  20955. if (isPlaybackDeviceStarted) {
  20956. DWORD bytesQueuedForPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - availableBytesPlayback;
  20957. if (bytesQueuedForPlayback < (pDevice->playback.internalPeriodSizeInFrames*bpfDevicePlayback)) {
  20958. silentPaddingInBytes = (pDevice->playback.internalPeriodSizeInFrames*2*bpfDevicePlayback) - bytesQueuedForPlayback;
  20959. if (silentPaddingInBytes > lockSizeInBytesPlayback) {
  20960. silentPaddingInBytes = lockSizeInBytesPlayback;
  20961. }
  20962. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Duplex/Playback) Playback buffer starved. availableBytesPlayback=%ld, silentPaddingInBytes=%ld\n", availableBytesPlayback, silentPaddingInBytes);
  20963. }
  20964. }
  20965. /* At this point we have a buffer for output. */
  20966. if (silentPaddingInBytes > 0) {
  20967. MA_ZERO_MEMORY(pMappedDeviceBufferPlayback, silentPaddingInBytes);
  20968. framesWrittenThisIteration = silentPaddingInBytes/bpfDevicePlayback;
  20969. } else {
  20970. ma_uint64 convertedFrameCountIn = (outputFramesInClientFormatCount - outputFramesInClientFormatConsumed);
  20971. ma_uint64 convertedFrameCountOut = mappedSizeInBytesPlayback/bpfDevicePlayback;
  20972. void* pConvertedFramesIn = ma_offset_ptr(outputFramesInClientFormat, outputFramesInClientFormatConsumed * bpfDevicePlayback);
  20973. void* pConvertedFramesOut = pMappedDeviceBufferPlayback;
  20974. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pConvertedFramesIn, &convertedFrameCountIn, pConvertedFramesOut, &convertedFrameCountOut);
  20975. if (result != MA_SUCCESS) {
  20976. break;
  20977. }
  20978. outputFramesInClientFormatConsumed += (ma_uint32)convertedFrameCountOut;
  20979. framesWrittenThisIteration = (ma_uint32)convertedFrameCountOut;
  20980. }
  20981. hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, framesWrittenThisIteration*bpfDevicePlayback, NULL, 0);
  20982. if (FAILED(hr)) {
  20983. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from playback device after writing to the device.");
  20984. result = ma_result_from_HRESULT(hr);
  20985. break;
  20986. }
  20987. virtualWriteCursorInBytesPlayback += framesWrittenThisIteration*bpfDevicePlayback;
  20988. if ((virtualWriteCursorInBytesPlayback/bpfDevicePlayback) == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods) {
  20989. virtualWriteCursorInBytesPlayback = 0;
  20990. virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback;
  20991. }
  20992. /*
  20993. We may need to start the device. We want two full periods to be written before starting the playback device. Having an extra period adds
  20994. a bit of a buffer to prevent the playback buffer from getting starved.
  20995. */
  20996. framesWrittenToPlaybackDevice += framesWrittenThisIteration;
  20997. if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= (pDevice->playback.internalPeriodSizeInFrames*2)) {
  20998. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  20999. if (FAILED(hr)) {
  21000. ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  21001. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  21002. return ma_result_from_HRESULT(hr);
  21003. }
  21004. isPlaybackDeviceStarted = MA_TRUE;
  21005. }
  21006. if (framesWrittenThisIteration < mappedSizeInBytesPlayback/bpfDevicePlayback) {
  21007. break; /* We're finished with the output data.*/
  21008. }
  21009. }
  21010. if (clientCapturedFramesToProcess == 0) {
  21011. break; /* We just consumed every input sample. */
  21012. }
  21013. }
  21014. /* At this point we're done with the mapped portion of the capture buffer. */
  21015. hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0);
  21016. if (FAILED(hr)) {
  21017. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from capture device after reading from the device.");
  21018. return ma_result_from_HRESULT(hr);
  21019. }
  21020. prevReadCursorInBytesCapture = (lockOffsetInBytesCapture + mappedSizeInBytesCapture);
  21021. } break;
  21022. case ma_device_type_capture:
  21023. {
  21024. DWORD physicalCaptureCursorInBytes;
  21025. DWORD physicalReadCursorInBytes;
  21026. hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes);
  21027. if (FAILED(hr)) {
  21028. return MA_ERROR;
  21029. }
  21030. /* If the previous capture position is the same as the current position we need to wait a bit longer. */
  21031. if (prevReadCursorInBytesCapture == physicalReadCursorInBytes) {
  21032. ma_sleep(waitTimeInMilliseconds);
  21033. continue;
  21034. }
  21035. /* Getting here means we have capture data available. */
  21036. if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) {
  21037. /* The capture position has not looped. This is the simple case. */
  21038. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  21039. lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture);
  21040. } else {
  21041. /*
  21042. The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything,
  21043. do it again from the start.
  21044. */
  21045. if (prevReadCursorInBytesCapture < pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) {
  21046. /* Lock up to the end of the buffer. */
  21047. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  21048. lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - prevReadCursorInBytesCapture;
  21049. } else {
  21050. /* Lock starting from the start of the buffer. */
  21051. lockOffsetInBytesCapture = 0;
  21052. lockSizeInBytesCapture = physicalReadCursorInBytes;
  21053. }
  21054. }
  21055. if (lockSizeInBytesCapture < pDevice->capture.internalPeriodSizeInFrames) {
  21056. ma_sleep(waitTimeInMilliseconds);
  21057. continue; /* Nothing is available in the capture buffer. */
  21058. }
  21059. hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0);
  21060. if (FAILED(hr)) {
  21061. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from capture device in preparation for writing to the device.");
  21062. result = ma_result_from_HRESULT(hr);
  21063. }
  21064. if (lockSizeInBytesCapture != mappedSizeInBytesCapture) {
  21065. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[DirectSound] (Capture) lockSizeInBytesCapture=%ld != mappedSizeInBytesCapture=%ld\n", lockSizeInBytesCapture, mappedSizeInBytesCapture);
  21066. }
  21067. ma_device__send_frames_to_client(pDevice, mappedSizeInBytesCapture/bpfDeviceCapture, pMappedDeviceBufferCapture);
  21068. hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0);
  21069. if (FAILED(hr)) {
  21070. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from capture device after reading from the device.");
  21071. return ma_result_from_HRESULT(hr);
  21072. }
  21073. prevReadCursorInBytesCapture = lockOffsetInBytesCapture + mappedSizeInBytesCapture;
  21074. if (prevReadCursorInBytesCapture == (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture)) {
  21075. prevReadCursorInBytesCapture = 0;
  21076. }
  21077. } break;
  21078. case ma_device_type_playback:
  21079. {
  21080. DWORD availableBytesPlayback;
  21081. DWORD physicalPlayCursorInBytes;
  21082. DWORD physicalWriteCursorInBytes;
  21083. hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes);
  21084. if (FAILED(hr)) {
  21085. break;
  21086. }
  21087. if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
  21088. physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
  21089. }
  21090. prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
  21091. /* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */
  21092. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  21093. /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
  21094. if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
  21095. availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  21096. availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
  21097. } else {
  21098. /* This is an error. */
  21099. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Playback): Play cursor has moved in front of the write cursor (same loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback);
  21100. availableBytesPlayback = 0;
  21101. }
  21102. } else {
  21103. /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
  21104. if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
  21105. availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  21106. } else {
  21107. /* This is an error. */
  21108. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[DirectSound] (Playback): Write cursor has moved behind the play cursor (different loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback);
  21109. availableBytesPlayback = 0;
  21110. }
  21111. }
  21112. /* If there's no room available for writing we need to wait for more. */
  21113. if (availableBytesPlayback < pDevice->playback.internalPeriodSizeInFrames) {
  21114. /* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */
  21115. if (availableBytesPlayback == 0 && !isPlaybackDeviceStarted) {
  21116. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  21117. if (FAILED(hr)) {
  21118. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  21119. return ma_result_from_HRESULT(hr);
  21120. }
  21121. isPlaybackDeviceStarted = MA_TRUE;
  21122. } else {
  21123. ma_sleep(waitTimeInMilliseconds);
  21124. continue;
  21125. }
  21126. }
  21127. /* Getting here means there room available somewhere. We limit this to either the end of the buffer or the physical play cursor, whichever is closest. */
  21128. lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback;
  21129. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  21130. /* Same loop iteration. Go up to the end of the buffer. */
  21131. lockSizeInBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  21132. } else {
  21133. /* Different loop iterations. Go up to the physical play cursor. */
  21134. lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  21135. }
  21136. hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0);
  21137. if (FAILED(hr)) {
  21138. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from playback device in preparation for writing to the device.");
  21139. result = ma_result_from_HRESULT(hr);
  21140. break;
  21141. }
  21142. /* At this point we have a buffer for output. */
  21143. ma_device__read_frames_from_client(pDevice, (mappedSizeInBytesPlayback/bpfDevicePlayback), pMappedDeviceBufferPlayback);
  21144. hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, mappedSizeInBytesPlayback, NULL, 0);
  21145. if (FAILED(hr)) {
  21146. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from playback device after writing to the device.");
  21147. result = ma_result_from_HRESULT(hr);
  21148. break;
  21149. }
  21150. virtualWriteCursorInBytesPlayback += mappedSizeInBytesPlayback;
  21151. if (virtualWriteCursorInBytesPlayback == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) {
  21152. virtualWriteCursorInBytesPlayback = 0;
  21153. virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback;
  21154. }
  21155. /*
  21156. We may need to start the device. We want two full periods to be written before starting the playback device. Having an extra period adds
  21157. a bit of a buffer to prevent the playback buffer from getting starved.
  21158. */
  21159. framesWrittenToPlaybackDevice += mappedSizeInBytesPlayback/bpfDevicePlayback;
  21160. if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= pDevice->playback.internalPeriodSizeInFrames) {
  21161. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  21162. if (FAILED(hr)) {
  21163. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  21164. return ma_result_from_HRESULT(hr);
  21165. }
  21166. isPlaybackDeviceStarted = MA_TRUE;
  21167. }
  21168. } break;
  21169. default: return MA_INVALID_ARGS; /* Invalid device type. */
  21170. }
  21171. if (result != MA_SUCCESS) {
  21172. return result;
  21173. }
  21174. }
  21175. /* Getting here means the device is being stopped. */
  21176. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21177. hr = ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  21178. if (FAILED(hr)) {
  21179. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Stop() failed.");
  21180. return ma_result_from_HRESULT(hr);
  21181. }
  21182. }
  21183. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21184. /* The playback device should be drained before stopping. All we do is wait until the available bytes is equal to the size of the buffer. */
  21185. if (isPlaybackDeviceStarted) {
  21186. for (;;) {
  21187. DWORD availableBytesPlayback = 0;
  21188. DWORD physicalPlayCursorInBytes;
  21189. DWORD physicalWriteCursorInBytes;
  21190. hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes);
  21191. if (FAILED(hr)) {
  21192. break;
  21193. }
  21194. if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
  21195. physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
  21196. }
  21197. prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
  21198. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  21199. /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
  21200. if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
  21201. availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  21202. availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
  21203. } else {
  21204. break;
  21205. }
  21206. } else {
  21207. /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
  21208. if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
  21209. availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  21210. } else {
  21211. break;
  21212. }
  21213. }
  21214. if (availableBytesPlayback >= (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback)) {
  21215. break;
  21216. }
  21217. ma_sleep(waitTimeInMilliseconds);
  21218. }
  21219. }
  21220. hr = ma_IDirectSoundBuffer_Stop((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer);
  21221. if (FAILED(hr)) {
  21222. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Stop() failed.");
  21223. return ma_result_from_HRESULT(hr);
  21224. }
  21225. ma_IDirectSoundBuffer_SetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0);
  21226. }
  21227. return MA_SUCCESS;
  21228. }
  21229. static ma_result ma_context_uninit__dsound(ma_context* pContext)
  21230. {
  21231. MA_ASSERT(pContext != NULL);
  21232. MA_ASSERT(pContext->backend == ma_backend_dsound);
  21233. ma_dlclose(pContext, pContext->dsound.hDSoundDLL);
  21234. return MA_SUCCESS;
  21235. }
  21236. static ma_result ma_context_init__dsound(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  21237. {
  21238. MA_ASSERT(pContext != NULL);
  21239. (void)pConfig;
  21240. pContext->dsound.hDSoundDLL = ma_dlopen(pContext, "dsound.dll");
  21241. if (pContext->dsound.hDSoundDLL == NULL) {
  21242. return MA_API_NOT_FOUND;
  21243. }
  21244. pContext->dsound.DirectSoundCreate = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundCreate");
  21245. pContext->dsound.DirectSoundEnumerateA = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundEnumerateA");
  21246. pContext->dsound.DirectSoundCaptureCreate = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundCaptureCreate");
  21247. pContext->dsound.DirectSoundCaptureEnumerateA = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundCaptureEnumerateA");
  21248. /*
  21249. We need to support all functions or nothing. DirectSound with Windows 95 seems to not work too
  21250. well in my testing. For example, it's missing DirectSoundCaptureEnumerateA(). This is a convenient
  21251. place to just disable the DirectSound backend for Windows 95.
  21252. */
  21253. if (pContext->dsound.DirectSoundCreate == NULL ||
  21254. pContext->dsound.DirectSoundEnumerateA == NULL ||
  21255. pContext->dsound.DirectSoundCaptureCreate == NULL ||
  21256. pContext->dsound.DirectSoundCaptureEnumerateA == NULL) {
  21257. return MA_API_NOT_FOUND;
  21258. }
  21259. pCallbacks->onContextInit = ma_context_init__dsound;
  21260. pCallbacks->onContextUninit = ma_context_uninit__dsound;
  21261. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__dsound;
  21262. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__dsound;
  21263. pCallbacks->onDeviceInit = ma_device_init__dsound;
  21264. pCallbacks->onDeviceUninit = ma_device_uninit__dsound;
  21265. pCallbacks->onDeviceStart = NULL; /* Not used. Started in onDeviceDataLoop. */
  21266. pCallbacks->onDeviceStop = NULL; /* Not used. Stopped in onDeviceDataLoop. */
  21267. pCallbacks->onDeviceRead = NULL; /* Not used. Data is read directly in onDeviceDataLoop. */
  21268. pCallbacks->onDeviceWrite = NULL; /* Not used. Data is written directly in onDeviceDataLoop. */
  21269. pCallbacks->onDeviceDataLoop = ma_device_data_loop__dsound;
  21270. return MA_SUCCESS;
  21271. }
  21272. #endif
  21273. /******************************************************************************
  21274. WinMM Backend
  21275. ******************************************************************************/
  21276. #ifdef MA_HAS_WINMM
  21277. /*
  21278. Some build configurations will exclude the WinMM API. An example is when WIN32_LEAN_AND_MEAN
  21279. is defined. We need to define the types and functions we need manually.
  21280. */
  21281. #define MA_MMSYSERR_NOERROR 0
  21282. #define MA_MMSYSERR_ERROR 1
  21283. #define MA_MMSYSERR_BADDEVICEID 2
  21284. #define MA_MMSYSERR_INVALHANDLE 5
  21285. #define MA_MMSYSERR_NOMEM 7
  21286. #define MA_MMSYSERR_INVALFLAG 10
  21287. #define MA_MMSYSERR_INVALPARAM 11
  21288. #define MA_MMSYSERR_HANDLEBUSY 12
  21289. #define MA_CALLBACK_EVENT 0x00050000
  21290. #define MA_WAVE_ALLOWSYNC 0x0002
  21291. #define MA_WHDR_DONE 0x00000001
  21292. #define MA_WHDR_PREPARED 0x00000002
  21293. #define MA_WHDR_BEGINLOOP 0x00000004
  21294. #define MA_WHDR_ENDLOOP 0x00000008
  21295. #define MA_WHDR_INQUEUE 0x00000010
  21296. #define MA_MAXPNAMELEN 32
  21297. typedef void* MA_HWAVEIN;
  21298. typedef void* MA_HWAVEOUT;
  21299. typedef UINT MA_MMRESULT;
  21300. typedef UINT MA_MMVERSION;
  21301. typedef struct
  21302. {
  21303. WORD wMid;
  21304. WORD wPid;
  21305. MA_MMVERSION vDriverVersion;
  21306. CHAR szPname[MA_MAXPNAMELEN];
  21307. DWORD dwFormats;
  21308. WORD wChannels;
  21309. WORD wReserved1;
  21310. } MA_WAVEINCAPSA;
  21311. typedef struct
  21312. {
  21313. WORD wMid;
  21314. WORD wPid;
  21315. MA_MMVERSION vDriverVersion;
  21316. CHAR szPname[MA_MAXPNAMELEN];
  21317. DWORD dwFormats;
  21318. WORD wChannels;
  21319. WORD wReserved1;
  21320. DWORD dwSupport;
  21321. } MA_WAVEOUTCAPSA;
  21322. typedef struct tagWAVEHDR
  21323. {
  21324. char* lpData;
  21325. DWORD dwBufferLength;
  21326. DWORD dwBytesRecorded;
  21327. DWORD_PTR dwUser;
  21328. DWORD dwFlags;
  21329. DWORD dwLoops;
  21330. struct tagWAVEHDR* lpNext;
  21331. DWORD_PTR reserved;
  21332. } MA_WAVEHDR;
  21333. typedef struct
  21334. {
  21335. WORD wMid;
  21336. WORD wPid;
  21337. MA_MMVERSION vDriverVersion;
  21338. CHAR szPname[MA_MAXPNAMELEN];
  21339. DWORD dwFormats;
  21340. WORD wChannels;
  21341. WORD wReserved1;
  21342. DWORD dwSupport;
  21343. GUID ManufacturerGuid;
  21344. GUID ProductGuid;
  21345. GUID NameGuid;
  21346. } MA_WAVEOUTCAPS2A;
  21347. typedef struct
  21348. {
  21349. WORD wMid;
  21350. WORD wPid;
  21351. MA_MMVERSION vDriverVersion;
  21352. CHAR szPname[MA_MAXPNAMELEN];
  21353. DWORD dwFormats;
  21354. WORD wChannels;
  21355. WORD wReserved1;
  21356. GUID ManufacturerGuid;
  21357. GUID ProductGuid;
  21358. GUID NameGuid;
  21359. } MA_WAVEINCAPS2A;
  21360. typedef UINT (WINAPI * MA_PFN_waveOutGetNumDevs)(void);
  21361. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutGetDevCapsA)(ma_uintptr uDeviceID, MA_WAVEOUTCAPSA* pwoc, UINT cbwoc);
  21362. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutOpen)(MA_HWAVEOUT* phwo, UINT uDeviceID, const MA_WAVEFORMATEX* pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen);
  21363. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutClose)(MA_HWAVEOUT hwo);
  21364. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutPrepareHeader)(MA_HWAVEOUT hwo, MA_WAVEHDR* pwh, UINT cbwh);
  21365. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutUnprepareHeader)(MA_HWAVEOUT hwo, MA_WAVEHDR* pwh, UINT cbwh);
  21366. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutWrite)(MA_HWAVEOUT hwo, MA_WAVEHDR* pwh, UINT cbwh);
  21367. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutReset)(MA_HWAVEOUT hwo);
  21368. typedef UINT (WINAPI * MA_PFN_waveInGetNumDevs)(void);
  21369. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInGetDevCapsA)(ma_uintptr uDeviceID, MA_WAVEINCAPSA* pwic, UINT cbwic);
  21370. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInOpen)(MA_HWAVEIN* phwi, UINT uDeviceID, const MA_WAVEFORMATEX* pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen);
  21371. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInClose)(MA_HWAVEIN hwi);
  21372. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInPrepareHeader)(MA_HWAVEIN hwi, MA_WAVEHDR* pwh, UINT cbwh);
  21373. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInUnprepareHeader)(MA_HWAVEIN hwi, MA_WAVEHDR* pwh, UINT cbwh);
  21374. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInAddBuffer)(MA_HWAVEIN hwi, MA_WAVEHDR* pwh, UINT cbwh);
  21375. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInStart)(MA_HWAVEIN hwi);
  21376. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInReset)(MA_HWAVEIN hwi);
  21377. static ma_result ma_result_from_MMRESULT(MA_MMRESULT resultMM)
  21378. {
  21379. switch (resultMM)
  21380. {
  21381. case MA_MMSYSERR_NOERROR: return MA_SUCCESS;
  21382. case MA_MMSYSERR_BADDEVICEID: return MA_INVALID_ARGS;
  21383. case MA_MMSYSERR_INVALHANDLE: return MA_INVALID_ARGS;
  21384. case MA_MMSYSERR_NOMEM: return MA_OUT_OF_MEMORY;
  21385. case MA_MMSYSERR_INVALFLAG: return MA_INVALID_ARGS;
  21386. case MA_MMSYSERR_INVALPARAM: return MA_INVALID_ARGS;
  21387. case MA_MMSYSERR_HANDLEBUSY: return MA_BUSY;
  21388. case MA_MMSYSERR_ERROR: return MA_ERROR;
  21389. default: return MA_ERROR;
  21390. }
  21391. }
  21392. static char* ma_find_last_character(char* str, char ch)
  21393. {
  21394. char* last;
  21395. if (str == NULL) {
  21396. return NULL;
  21397. }
  21398. last = NULL;
  21399. while (*str != '\0') {
  21400. if (*str == ch) {
  21401. last = str;
  21402. }
  21403. str += 1;
  21404. }
  21405. return last;
  21406. }
  21407. static ma_uint32 ma_get_period_size_in_bytes(ma_uint32 periodSizeInFrames, ma_format format, ma_uint32 channels)
  21408. {
  21409. return periodSizeInFrames * ma_get_bytes_per_frame(format, channels);
  21410. }
  21411. /*
  21412. Our own "WAVECAPS" structure that contains generic information shared between WAVEOUTCAPS2 and WAVEINCAPS2 so
  21413. we can do things generically and typesafely. Names are being kept the same for consistency.
  21414. */
  21415. typedef struct
  21416. {
  21417. CHAR szPname[MA_MAXPNAMELEN];
  21418. DWORD dwFormats;
  21419. WORD wChannels;
  21420. GUID NameGuid;
  21421. } MA_WAVECAPSA;
  21422. static ma_result ma_get_best_info_from_formats_flags__winmm(DWORD dwFormats, WORD channels, WORD* pBitsPerSample, DWORD* pSampleRate)
  21423. {
  21424. WORD bitsPerSample = 0;
  21425. DWORD sampleRate = 0;
  21426. if (pBitsPerSample) {
  21427. *pBitsPerSample = 0;
  21428. }
  21429. if (pSampleRate) {
  21430. *pSampleRate = 0;
  21431. }
  21432. if (channels == 1) {
  21433. bitsPerSample = 16;
  21434. if ((dwFormats & WAVE_FORMAT_48M16) != 0) {
  21435. sampleRate = 48000;
  21436. } else if ((dwFormats & WAVE_FORMAT_44M16) != 0) {
  21437. sampleRate = 44100;
  21438. } else if ((dwFormats & WAVE_FORMAT_2M16) != 0) {
  21439. sampleRate = 22050;
  21440. } else if ((dwFormats & WAVE_FORMAT_1M16) != 0) {
  21441. sampleRate = 11025;
  21442. } else if ((dwFormats & WAVE_FORMAT_96M16) != 0) {
  21443. sampleRate = 96000;
  21444. } else {
  21445. bitsPerSample = 8;
  21446. if ((dwFormats & WAVE_FORMAT_48M08) != 0) {
  21447. sampleRate = 48000;
  21448. } else if ((dwFormats & WAVE_FORMAT_44M08) != 0) {
  21449. sampleRate = 44100;
  21450. } else if ((dwFormats & WAVE_FORMAT_2M08) != 0) {
  21451. sampleRate = 22050;
  21452. } else if ((dwFormats & WAVE_FORMAT_1M08) != 0) {
  21453. sampleRate = 11025;
  21454. } else if ((dwFormats & WAVE_FORMAT_96M08) != 0) {
  21455. sampleRate = 96000;
  21456. } else {
  21457. return MA_FORMAT_NOT_SUPPORTED;
  21458. }
  21459. }
  21460. } else {
  21461. bitsPerSample = 16;
  21462. if ((dwFormats & WAVE_FORMAT_48S16) != 0) {
  21463. sampleRate = 48000;
  21464. } else if ((dwFormats & WAVE_FORMAT_44S16) != 0) {
  21465. sampleRate = 44100;
  21466. } else if ((dwFormats & WAVE_FORMAT_2S16) != 0) {
  21467. sampleRate = 22050;
  21468. } else if ((dwFormats & WAVE_FORMAT_1S16) != 0) {
  21469. sampleRate = 11025;
  21470. } else if ((dwFormats & WAVE_FORMAT_96S16) != 0) {
  21471. sampleRate = 96000;
  21472. } else {
  21473. bitsPerSample = 8;
  21474. if ((dwFormats & WAVE_FORMAT_48S08) != 0) {
  21475. sampleRate = 48000;
  21476. } else if ((dwFormats & WAVE_FORMAT_44S08) != 0) {
  21477. sampleRate = 44100;
  21478. } else if ((dwFormats & WAVE_FORMAT_2S08) != 0) {
  21479. sampleRate = 22050;
  21480. } else if ((dwFormats & WAVE_FORMAT_1S08) != 0) {
  21481. sampleRate = 11025;
  21482. } else if ((dwFormats & WAVE_FORMAT_96S08) != 0) {
  21483. sampleRate = 96000;
  21484. } else {
  21485. return MA_FORMAT_NOT_SUPPORTED;
  21486. }
  21487. }
  21488. }
  21489. if (pBitsPerSample) {
  21490. *pBitsPerSample = bitsPerSample;
  21491. }
  21492. if (pSampleRate) {
  21493. *pSampleRate = sampleRate;
  21494. }
  21495. return MA_SUCCESS;
  21496. }
  21497. static ma_result ma_formats_flags_to_WAVEFORMATEX__winmm(DWORD dwFormats, WORD channels, MA_WAVEFORMATEX* pWF)
  21498. {
  21499. ma_result result;
  21500. MA_ASSERT(pWF != NULL);
  21501. MA_ZERO_OBJECT(pWF);
  21502. pWF->cbSize = sizeof(*pWF);
  21503. pWF->wFormatTag = WAVE_FORMAT_PCM;
  21504. pWF->nChannels = (WORD)channels;
  21505. if (pWF->nChannels > 2) {
  21506. pWF->nChannels = 2;
  21507. }
  21508. result = ma_get_best_info_from_formats_flags__winmm(dwFormats, channels, &pWF->wBitsPerSample, &pWF->nSamplesPerSec);
  21509. if (result != MA_SUCCESS) {
  21510. return result;
  21511. }
  21512. pWF->nBlockAlign = (WORD)(pWF->nChannels * pWF->wBitsPerSample / 8);
  21513. pWF->nAvgBytesPerSec = pWF->nBlockAlign * pWF->nSamplesPerSec;
  21514. return MA_SUCCESS;
  21515. }
  21516. static ma_result ma_context_get_device_info_from_WAVECAPS(ma_context* pContext, MA_WAVECAPSA* pCaps, ma_device_info* pDeviceInfo)
  21517. {
  21518. WORD bitsPerSample;
  21519. DWORD sampleRate;
  21520. ma_result result;
  21521. MA_ASSERT(pContext != NULL);
  21522. MA_ASSERT(pCaps != NULL);
  21523. MA_ASSERT(pDeviceInfo != NULL);
  21524. /*
  21525. Name / Description
  21526. Unfortunately the name specified in WAVE(OUT/IN)CAPS2 is limited to 31 characters. This results in an unprofessional looking
  21527. situation where the names of the devices are truncated. To help work around this, we need to look at the name GUID and try
  21528. looking in the registry for the full name. If we can't find it there, we need to just fall back to the default name.
  21529. */
  21530. /* Set the default to begin with. */
  21531. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), pCaps->szPname, (size_t)-1);
  21532. /*
  21533. Now try the registry. There's a few things to consider here:
  21534. - The name GUID can be null, in which we case we just need to stick to the original 31 characters.
  21535. - If the name GUID is not present in the registry we'll also need to stick to the original 31 characters.
  21536. - I like consistency, so I want the returned device names to be consistent with those returned by WASAPI and DirectSound. The
  21537. problem, however is that WASAPI and DirectSound use "<component> (<name>)" format (such as "Speakers (High Definition Audio)"),
  21538. but WinMM does not specificy the component name. From my admittedly limited testing, I've notice the component name seems to
  21539. usually fit within the 31 characters of the fixed sized buffer, so what I'm going to do is parse that string for the component
  21540. name, and then concatenate the name from the registry.
  21541. */
  21542. if (!ma_is_guid_null(&pCaps->NameGuid)) {
  21543. WCHAR guidStrW[256];
  21544. if (((MA_PFN_StringFromGUID2)pContext->win32.StringFromGUID2)(&pCaps->NameGuid, guidStrW, ma_countof(guidStrW)) > 0) {
  21545. char guidStr[256];
  21546. char keyStr[1024];
  21547. HKEY hKey;
  21548. WideCharToMultiByte(CP_UTF8, 0, guidStrW, -1, guidStr, sizeof(guidStr), 0, FALSE);
  21549. ma_strcpy_s(keyStr, sizeof(keyStr), "SYSTEM\\CurrentControlSet\\Control\\MediaCategories\\");
  21550. ma_strcat_s(keyStr, sizeof(keyStr), guidStr);
  21551. if (((MA_PFN_RegOpenKeyExA)pContext->win32.RegOpenKeyExA)(HKEY_LOCAL_MACHINE, keyStr, 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
  21552. BYTE nameFromReg[512];
  21553. DWORD nameFromRegSize = sizeof(nameFromReg);
  21554. LONG resultWin32 = ((MA_PFN_RegQueryValueExA)pContext->win32.RegQueryValueExA)(hKey, "Name", 0, NULL, (BYTE*)nameFromReg, (DWORD*)&nameFromRegSize);
  21555. ((MA_PFN_RegCloseKey)pContext->win32.RegCloseKey)(hKey);
  21556. if (resultWin32 == ERROR_SUCCESS) {
  21557. /* We have the value from the registry, so now we need to construct the name string. */
  21558. char name[1024];
  21559. if (ma_strcpy_s(name, sizeof(name), pDeviceInfo->name) == 0) {
  21560. char* nameBeg = ma_find_last_character(name, '(');
  21561. if (nameBeg != NULL) {
  21562. size_t leadingLen = (nameBeg - name);
  21563. ma_strncpy_s(nameBeg + 1, sizeof(name) - leadingLen, (const char*)nameFromReg, (size_t)-1);
  21564. /* The closing ")", if it can fit. */
  21565. if (leadingLen + nameFromRegSize < sizeof(name)-1) {
  21566. ma_strcat_s(name, sizeof(name), ")");
  21567. }
  21568. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), name, (size_t)-1);
  21569. }
  21570. }
  21571. }
  21572. }
  21573. }
  21574. }
  21575. result = ma_get_best_info_from_formats_flags__winmm(pCaps->dwFormats, pCaps->wChannels, &bitsPerSample, &sampleRate);
  21576. if (result != MA_SUCCESS) {
  21577. return result;
  21578. }
  21579. if (bitsPerSample == 8) {
  21580. pDeviceInfo->nativeDataFormats[0].format = ma_format_u8;
  21581. } else if (bitsPerSample == 16) {
  21582. pDeviceInfo->nativeDataFormats[0].format = ma_format_s16;
  21583. } else if (bitsPerSample == 24) {
  21584. pDeviceInfo->nativeDataFormats[0].format = ma_format_s24;
  21585. } else if (bitsPerSample == 32) {
  21586. pDeviceInfo->nativeDataFormats[0].format = ma_format_s32;
  21587. } else {
  21588. return MA_FORMAT_NOT_SUPPORTED;
  21589. }
  21590. pDeviceInfo->nativeDataFormats[0].channels = pCaps->wChannels;
  21591. pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate;
  21592. pDeviceInfo->nativeDataFormats[0].flags = 0;
  21593. pDeviceInfo->nativeDataFormatCount = 1;
  21594. return MA_SUCCESS;
  21595. }
  21596. static ma_result ma_context_get_device_info_from_WAVEOUTCAPS2(ma_context* pContext, MA_WAVEOUTCAPS2A* pCaps, ma_device_info* pDeviceInfo)
  21597. {
  21598. MA_WAVECAPSA caps;
  21599. MA_ASSERT(pContext != NULL);
  21600. MA_ASSERT(pCaps != NULL);
  21601. MA_ASSERT(pDeviceInfo != NULL);
  21602. MA_COPY_MEMORY(caps.szPname, pCaps->szPname, sizeof(caps.szPname));
  21603. caps.dwFormats = pCaps->dwFormats;
  21604. caps.wChannels = pCaps->wChannels;
  21605. caps.NameGuid = pCaps->NameGuid;
  21606. return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo);
  21607. }
  21608. static ma_result ma_context_get_device_info_from_WAVEINCAPS2(ma_context* pContext, MA_WAVEINCAPS2A* pCaps, ma_device_info* pDeviceInfo)
  21609. {
  21610. MA_WAVECAPSA caps;
  21611. MA_ASSERT(pContext != NULL);
  21612. MA_ASSERT(pCaps != NULL);
  21613. MA_ASSERT(pDeviceInfo != NULL);
  21614. MA_COPY_MEMORY(caps.szPname, pCaps->szPname, sizeof(caps.szPname));
  21615. caps.dwFormats = pCaps->dwFormats;
  21616. caps.wChannels = pCaps->wChannels;
  21617. caps.NameGuid = pCaps->NameGuid;
  21618. return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo);
  21619. }
  21620. static ma_result ma_context_enumerate_devices__winmm(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  21621. {
  21622. UINT playbackDeviceCount;
  21623. UINT captureDeviceCount;
  21624. UINT iPlaybackDevice;
  21625. UINT iCaptureDevice;
  21626. MA_ASSERT(pContext != NULL);
  21627. MA_ASSERT(callback != NULL);
  21628. /* Playback. */
  21629. playbackDeviceCount = ((MA_PFN_waveOutGetNumDevs)pContext->winmm.waveOutGetNumDevs)();
  21630. for (iPlaybackDevice = 0; iPlaybackDevice < playbackDeviceCount; ++iPlaybackDevice) {
  21631. MA_MMRESULT result;
  21632. MA_WAVEOUTCAPS2A caps;
  21633. MA_ZERO_OBJECT(&caps);
  21634. result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(iPlaybackDevice, (MA_WAVEOUTCAPSA*)&caps, sizeof(caps));
  21635. if (result == MA_MMSYSERR_NOERROR) {
  21636. ma_device_info deviceInfo;
  21637. MA_ZERO_OBJECT(&deviceInfo);
  21638. deviceInfo.id.winmm = iPlaybackDevice;
  21639. /* The first enumerated device is the default device. */
  21640. if (iPlaybackDevice == 0) {
  21641. deviceInfo.isDefault = MA_TRUE;
  21642. }
  21643. if (ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) {
  21644. ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  21645. if (cbResult == MA_FALSE) {
  21646. return MA_SUCCESS; /* Enumeration was stopped. */
  21647. }
  21648. }
  21649. }
  21650. }
  21651. /* Capture. */
  21652. captureDeviceCount = ((MA_PFN_waveInGetNumDevs)pContext->winmm.waveInGetNumDevs)();
  21653. for (iCaptureDevice = 0; iCaptureDevice < captureDeviceCount; ++iCaptureDevice) {
  21654. MA_MMRESULT result;
  21655. MA_WAVEINCAPS2A caps;
  21656. MA_ZERO_OBJECT(&caps);
  21657. result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(iCaptureDevice, (MA_WAVEINCAPSA*)&caps, sizeof(caps));
  21658. if (result == MA_MMSYSERR_NOERROR) {
  21659. ma_device_info deviceInfo;
  21660. MA_ZERO_OBJECT(&deviceInfo);
  21661. deviceInfo.id.winmm = iCaptureDevice;
  21662. /* The first enumerated device is the default device. */
  21663. if (iCaptureDevice == 0) {
  21664. deviceInfo.isDefault = MA_TRUE;
  21665. }
  21666. if (ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) {
  21667. ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  21668. if (cbResult == MA_FALSE) {
  21669. return MA_SUCCESS; /* Enumeration was stopped. */
  21670. }
  21671. }
  21672. }
  21673. }
  21674. return MA_SUCCESS;
  21675. }
  21676. static ma_result ma_context_get_device_info__winmm(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  21677. {
  21678. UINT winMMDeviceID;
  21679. MA_ASSERT(pContext != NULL);
  21680. winMMDeviceID = 0;
  21681. if (pDeviceID != NULL) {
  21682. winMMDeviceID = (UINT)pDeviceID->winmm;
  21683. }
  21684. pDeviceInfo->id.winmm = winMMDeviceID;
  21685. /* The first ID is the default device. */
  21686. if (winMMDeviceID == 0) {
  21687. pDeviceInfo->isDefault = MA_TRUE;
  21688. }
  21689. if (deviceType == ma_device_type_playback) {
  21690. MA_MMRESULT result;
  21691. MA_WAVEOUTCAPS2A caps;
  21692. MA_ZERO_OBJECT(&caps);
  21693. result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, (MA_WAVEOUTCAPSA*)&caps, sizeof(caps));
  21694. if (result == MA_MMSYSERR_NOERROR) {
  21695. return ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, pDeviceInfo);
  21696. }
  21697. } else {
  21698. MA_MMRESULT result;
  21699. MA_WAVEINCAPS2A caps;
  21700. MA_ZERO_OBJECT(&caps);
  21701. result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, (MA_WAVEINCAPSA*)&caps, sizeof(caps));
  21702. if (result == MA_MMSYSERR_NOERROR) {
  21703. return ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, pDeviceInfo);
  21704. }
  21705. }
  21706. return MA_NO_DEVICE;
  21707. }
  21708. static ma_result ma_device_uninit__winmm(ma_device* pDevice)
  21709. {
  21710. MA_ASSERT(pDevice != NULL);
  21711. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21712. ((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture);
  21713. CloseHandle((HANDLE)pDevice->winmm.hEventCapture);
  21714. }
  21715. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21716. ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21717. ((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21718. CloseHandle((HANDLE)pDevice->winmm.hEventPlayback);
  21719. }
  21720. ma_free(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks);
  21721. MA_ZERO_OBJECT(&pDevice->winmm); /* Safety. */
  21722. return MA_SUCCESS;
  21723. }
  21724. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__winmm(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  21725. {
  21726. /* WinMM has a minimum period size of 40ms. */
  21727. ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(40, nativeSampleRate);
  21728. ma_uint32 periodSizeInFrames;
  21729. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, nativeSampleRate, performanceProfile);
  21730. if (periodSizeInFrames < minPeriodSizeInFrames) {
  21731. periodSizeInFrames = minPeriodSizeInFrames;
  21732. }
  21733. return periodSizeInFrames;
  21734. }
  21735. static ma_result ma_device_init__winmm(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  21736. {
  21737. const char* errorMsg = "";
  21738. ma_result errorCode = MA_ERROR;
  21739. ma_result result = MA_SUCCESS;
  21740. ma_uint32 heapSize;
  21741. UINT winMMDeviceIDPlayback = 0;
  21742. UINT winMMDeviceIDCapture = 0;
  21743. MA_ASSERT(pDevice != NULL);
  21744. MA_ZERO_OBJECT(&pDevice->winmm);
  21745. if (pConfig->deviceType == ma_device_type_loopback) {
  21746. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  21747. }
  21748. /* No exlusive mode with WinMM. */
  21749. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  21750. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  21751. return MA_SHARE_MODE_NOT_SUPPORTED;
  21752. }
  21753. if (pDescriptorPlayback->pDeviceID != NULL) {
  21754. winMMDeviceIDPlayback = (UINT)pDescriptorPlayback->pDeviceID->winmm;
  21755. }
  21756. if (pDescriptorCapture->pDeviceID != NULL) {
  21757. winMMDeviceIDCapture = (UINT)pDescriptorCapture->pDeviceID->winmm;
  21758. }
  21759. /* The capture device needs to be initialized first. */
  21760. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  21761. MA_WAVEINCAPSA caps;
  21762. MA_WAVEFORMATEX wf;
  21763. MA_MMRESULT resultMM;
  21764. /* We use an event to know when a new fragment needs to be enqueued. */
  21765. pDevice->winmm.hEventCapture = (ma_handle)CreateEventA(NULL, TRUE, TRUE, NULL);
  21766. if (pDevice->winmm.hEventCapture == NULL) {
  21767. errorMsg = "[WinMM] Failed to create event for fragment enqueing for the capture device.", errorCode = ma_result_from_GetLastError(GetLastError());
  21768. goto on_error;
  21769. }
  21770. /* The format should be based on the device's actual format. */
  21771. if (((MA_PFN_waveInGetDevCapsA)pDevice->pContext->winmm.waveInGetDevCapsA)(winMMDeviceIDCapture, &caps, sizeof(caps)) != MA_MMSYSERR_NOERROR) {
  21772. errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
  21773. goto on_error;
  21774. }
  21775. result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
  21776. if (result != MA_SUCCESS) {
  21777. errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result;
  21778. goto on_error;
  21779. }
  21780. resultMM = ((MA_PFN_waveInOpen)pDevice->pContext->winmm.waveInOpen)((MA_HWAVEIN*)&pDevice->winmm.hDeviceCapture, winMMDeviceIDCapture, &wf, (DWORD_PTR)pDevice->winmm.hEventCapture, (DWORD_PTR)pDevice, MA_CALLBACK_EVENT | MA_WAVE_ALLOWSYNC);
  21781. if (resultMM != MA_MMSYSERR_NOERROR) {
  21782. errorMsg = "[WinMM] Failed to open capture device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  21783. goto on_error;
  21784. }
  21785. pDescriptorCapture->format = ma_format_from_WAVEFORMATEX(&wf);
  21786. pDescriptorCapture->channels = wf.nChannels;
  21787. pDescriptorCapture->sampleRate = wf.nSamplesPerSec;
  21788. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  21789. pDescriptorCapture->periodCount = pDescriptorCapture->periodCount;
  21790. pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__winmm(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
  21791. }
  21792. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  21793. MA_WAVEOUTCAPSA caps;
  21794. MA_WAVEFORMATEX wf;
  21795. MA_MMRESULT resultMM;
  21796. /* We use an event to know when a new fragment needs to be enqueued. */
  21797. pDevice->winmm.hEventPlayback = (ma_handle)CreateEventA(NULL, TRUE, TRUE, NULL);
  21798. if (pDevice->winmm.hEventPlayback == NULL) {
  21799. errorMsg = "[WinMM] Failed to create event for fragment enqueing for the playback device.", errorCode = ma_result_from_GetLastError(GetLastError());
  21800. goto on_error;
  21801. }
  21802. /* The format should be based on the device's actual format. */
  21803. if (((MA_PFN_waveOutGetDevCapsA)pDevice->pContext->winmm.waveOutGetDevCapsA)(winMMDeviceIDPlayback, &caps, sizeof(caps)) != MA_MMSYSERR_NOERROR) {
  21804. errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
  21805. goto on_error;
  21806. }
  21807. result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
  21808. if (result != MA_SUCCESS) {
  21809. errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result;
  21810. goto on_error;
  21811. }
  21812. resultMM = ((MA_PFN_waveOutOpen)pDevice->pContext->winmm.waveOutOpen)((MA_HWAVEOUT*)&pDevice->winmm.hDevicePlayback, winMMDeviceIDPlayback, &wf, (DWORD_PTR)pDevice->winmm.hEventPlayback, (DWORD_PTR)pDevice, MA_CALLBACK_EVENT | MA_WAVE_ALLOWSYNC);
  21813. if (resultMM != MA_MMSYSERR_NOERROR) {
  21814. errorMsg = "[WinMM] Failed to open playback device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  21815. goto on_error;
  21816. }
  21817. pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX(&wf);
  21818. pDescriptorPlayback->channels = wf.nChannels;
  21819. pDescriptorPlayback->sampleRate = wf.nSamplesPerSec;
  21820. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels);
  21821. pDescriptorPlayback->periodCount = pDescriptorPlayback->periodCount;
  21822. pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__winmm(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  21823. }
  21824. /*
  21825. The heap allocated data is allocated like so:
  21826. [Capture WAVEHDRs][Playback WAVEHDRs][Capture Intermediary Buffer][Playback Intermediary Buffer]
  21827. */
  21828. heapSize = 0;
  21829. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  21830. heapSize += sizeof(MA_WAVEHDR)*pDescriptorCapture->periodCount + (pDescriptorCapture->periodSizeInFrames * pDescriptorCapture->periodCount * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels));
  21831. }
  21832. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  21833. heapSize += sizeof(MA_WAVEHDR)*pDescriptorPlayback->periodCount + (pDescriptorPlayback->periodSizeInFrames * pDescriptorPlayback->periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels));
  21834. }
  21835. pDevice->winmm._pHeapData = (ma_uint8*)ma_calloc(heapSize, &pDevice->pContext->allocationCallbacks);
  21836. if (pDevice->winmm._pHeapData == NULL) {
  21837. errorMsg = "[WinMM] Failed to allocate memory for the intermediary buffer.", errorCode = MA_OUT_OF_MEMORY;
  21838. goto on_error;
  21839. }
  21840. MA_ZERO_MEMORY(pDevice->winmm._pHeapData, heapSize);
  21841. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  21842. ma_uint32 iPeriod;
  21843. if (pConfig->deviceType == ma_device_type_capture) {
  21844. pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData;
  21845. pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount));
  21846. } else {
  21847. pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData;
  21848. pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount + pDescriptorPlayback->periodCount));
  21849. }
  21850. /* Prepare headers. */
  21851. for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) {
  21852. ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->format, pDescriptorCapture->channels);
  21853. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].lpData = (char*)(pDevice->winmm.pIntermediaryBufferCapture + (periodSizeInBytes*iPeriod));
  21854. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwBufferLength = periodSizeInBytes;
  21855. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwFlags = 0L;
  21856. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwLoops = 0L;
  21857. ((MA_PFN_waveInPrepareHeader)pDevice->pContext->winmm.waveInPrepareHeader)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(MA_WAVEHDR));
  21858. /*
  21859. The user data of the MA_WAVEHDR structure is a single flag the controls whether or not it is ready for writing. Consider it to be named "isLocked". A value of 0 means
  21860. it's unlocked and available for writing. A value of 1 means it's locked.
  21861. */
  21862. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwUser = 0;
  21863. }
  21864. }
  21865. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  21866. ma_uint32 iPeriod;
  21867. if (pConfig->deviceType == ma_device_type_playback) {
  21868. pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData;
  21869. pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*pDescriptorPlayback->periodCount);
  21870. } else {
  21871. pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount));
  21872. pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount + pDescriptorPlayback->periodCount)) + (pDescriptorCapture->periodSizeInFrames*pDescriptorCapture->periodCount*ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels));
  21873. }
  21874. /* Prepare headers. */
  21875. for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) {
  21876. ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->format, pDescriptorPlayback->channels);
  21877. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].lpData = (char*)(pDevice->winmm.pIntermediaryBufferPlayback + (periodSizeInBytes*iPeriod));
  21878. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwBufferLength = periodSizeInBytes;
  21879. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwFlags = 0L;
  21880. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwLoops = 0L;
  21881. ((MA_PFN_waveOutPrepareHeader)pDevice->pContext->winmm.waveOutPrepareHeader)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(MA_WAVEHDR));
  21882. /*
  21883. The user data of the MA_WAVEHDR structure is a single flag the controls whether or not it is ready for writing. Consider it to be named "isLocked". A value of 0 means
  21884. it's unlocked and available for writing. A value of 1 means it's locked.
  21885. */
  21886. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwUser = 0;
  21887. }
  21888. }
  21889. return MA_SUCCESS;
  21890. on_error:
  21891. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21892. if (pDevice->winmm.pWAVEHDRCapture != NULL) {
  21893. ma_uint32 iPeriod;
  21894. for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) {
  21895. ((MA_PFN_waveInUnprepareHeader)pDevice->pContext->winmm.waveInUnprepareHeader)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(MA_WAVEHDR));
  21896. }
  21897. }
  21898. ((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture);
  21899. }
  21900. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21901. if (pDevice->winmm.pWAVEHDRCapture != NULL) {
  21902. ma_uint32 iPeriod;
  21903. for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) {
  21904. ((MA_PFN_waveOutUnprepareHeader)pDevice->pContext->winmm.waveOutUnprepareHeader)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(MA_WAVEHDR));
  21905. }
  21906. }
  21907. ((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21908. }
  21909. ma_free(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks);
  21910. if (errorMsg != NULL && errorMsg[0] != '\0') {
  21911. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "%s", errorMsg);
  21912. }
  21913. return errorCode;
  21914. }
  21915. static ma_result ma_device_start__winmm(ma_device* pDevice)
  21916. {
  21917. MA_ASSERT(pDevice != NULL);
  21918. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21919. MA_MMRESULT resultMM;
  21920. MA_WAVEHDR* pWAVEHDR;
  21921. ma_uint32 iPeriod;
  21922. pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture;
  21923. /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
  21924. ResetEvent((HANDLE)pDevice->winmm.hEventCapture);
  21925. /* To start the device we attach all of the buffers and then start it. As the buffers are filled with data we will get notifications. */
  21926. for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) {
  21927. resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(MA_WAVEHDR));
  21928. if (resultMM != MA_MMSYSERR_NOERROR) {
  21929. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] Failed to attach input buffers to capture device in preparation for capture.");
  21930. return ma_result_from_MMRESULT(resultMM);
  21931. }
  21932. /* Make sure all of the buffers start out locked. We don't want to access them until the backend tells us we can. */
  21933. pWAVEHDR[iPeriod].dwUser = 1; /* 1 = locked. */
  21934. }
  21935. /* Capture devices need to be explicitly started, unlike playback devices. */
  21936. resultMM = ((MA_PFN_waveInStart)pDevice->pContext->winmm.waveInStart)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture);
  21937. if (resultMM != MA_MMSYSERR_NOERROR) {
  21938. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] Failed to start backend device.");
  21939. return ma_result_from_MMRESULT(resultMM);
  21940. }
  21941. }
  21942. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21943. /* Don't need to do anything for playback. It'll be started automatically in ma_device_start__winmm(). */
  21944. }
  21945. return MA_SUCCESS;
  21946. }
  21947. static ma_result ma_device_stop__winmm(ma_device* pDevice)
  21948. {
  21949. MA_MMRESULT resultMM;
  21950. MA_ASSERT(pDevice != NULL);
  21951. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21952. if (pDevice->winmm.hDeviceCapture == NULL) {
  21953. return MA_INVALID_ARGS;
  21954. }
  21955. resultMM = ((MA_PFN_waveInReset)pDevice->pContext->winmm.waveInReset)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture);
  21956. if (resultMM != MA_MMSYSERR_NOERROR) {
  21957. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WinMM] WARNING: Failed to reset capture device.");
  21958. }
  21959. }
  21960. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21961. ma_uint32 iPeriod;
  21962. MA_WAVEHDR* pWAVEHDR;
  21963. if (pDevice->winmm.hDevicePlayback == NULL) {
  21964. return MA_INVALID_ARGS;
  21965. }
  21966. /* We need to drain the device. To do this we just loop over each header and if it's locked just wait for the event. */
  21967. pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback;
  21968. for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; iPeriod += 1) {
  21969. if (pWAVEHDR[iPeriod].dwUser == 1) { /* 1 = locked. */
  21970. if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
  21971. break; /* An error occurred so just abandon ship and stop the device without draining. */
  21972. }
  21973. pWAVEHDR[iPeriod].dwUser = 0;
  21974. }
  21975. }
  21976. resultMM = ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21977. if (resultMM != MA_MMSYSERR_NOERROR) {
  21978. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WinMM] WARNING: Failed to reset playback device.");
  21979. }
  21980. }
  21981. return MA_SUCCESS;
  21982. }
  21983. static ma_result ma_device_write__winmm(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  21984. {
  21985. ma_result result = MA_SUCCESS;
  21986. MA_MMRESULT resultMM;
  21987. ma_uint32 totalFramesWritten;
  21988. MA_WAVEHDR* pWAVEHDR;
  21989. MA_ASSERT(pDevice != NULL);
  21990. MA_ASSERT(pPCMFrames != NULL);
  21991. if (pFramesWritten != NULL) {
  21992. *pFramesWritten = 0;
  21993. }
  21994. pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback;
  21995. /* Keep processing as much data as possible. */
  21996. totalFramesWritten = 0;
  21997. while (totalFramesWritten < frameCount) {
  21998. /* If the current header has some space available we need to write part of it. */
  21999. if (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser == 0) { /* 0 = unlocked. */
  22000. /*
  22001. This header has room in it. We copy as much of it as we can. If we end up fully consuming the buffer we need to
  22002. write it out and move on to the next iteration.
  22003. */
  22004. ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  22005. ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedPlayback;
  22006. ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesWritten));
  22007. const void* pSrc = ma_offset_ptr(pPCMFrames, totalFramesWritten*bpf);
  22008. void* pDst = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].lpData, pDevice->winmm.headerFramesConsumedPlayback*bpf);
  22009. MA_COPY_MEMORY(pDst, pSrc, framesToCopy*bpf);
  22010. pDevice->winmm.headerFramesConsumedPlayback += framesToCopy;
  22011. totalFramesWritten += framesToCopy;
  22012. /* If we've consumed the buffer entirely we need to write it out to the device. */
  22013. if (pDevice->winmm.headerFramesConsumedPlayback == (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf)) {
  22014. pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 1; /* 1 = locked. */
  22015. pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags &= ~MA_WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */
  22016. /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
  22017. ResetEvent((HANDLE)pDevice->winmm.hEventPlayback);
  22018. /* The device will be started here. */
  22019. resultMM = ((MA_PFN_waveOutWrite)pDevice->pContext->winmm.waveOutWrite)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback, &pWAVEHDR[pDevice->winmm.iNextHeaderPlayback], sizeof(MA_WAVEHDR));
  22020. if (resultMM != MA_MMSYSERR_NOERROR) {
  22021. result = ma_result_from_MMRESULT(resultMM);
  22022. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] waveOutWrite() failed.");
  22023. break;
  22024. }
  22025. /* Make sure we move to the next header. */
  22026. pDevice->winmm.iNextHeaderPlayback = (pDevice->winmm.iNextHeaderPlayback + 1) % pDevice->playback.internalPeriods;
  22027. pDevice->winmm.headerFramesConsumedPlayback = 0;
  22028. }
  22029. /* If at this point we have consumed the entire input buffer we can return. */
  22030. MA_ASSERT(totalFramesWritten <= frameCount);
  22031. if (totalFramesWritten == frameCount) {
  22032. break;
  22033. }
  22034. /* Getting here means there's more to process. */
  22035. continue;
  22036. }
  22037. /* Getting here means there isn't enough room in the buffer and we need to wait for one to become available. */
  22038. if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
  22039. result = MA_ERROR;
  22040. break;
  22041. }
  22042. /* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */
  22043. if ((pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags & MA_WHDR_DONE) != 0) {
  22044. pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 0; /* 0 = unlocked (make it available for writing). */
  22045. pDevice->winmm.headerFramesConsumedPlayback = 0;
  22046. }
  22047. /* If the device has been stopped we need to break. */
  22048. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  22049. break;
  22050. }
  22051. }
  22052. if (pFramesWritten != NULL) {
  22053. *pFramesWritten = totalFramesWritten;
  22054. }
  22055. return result;
  22056. }
  22057. static ma_result ma_device_read__winmm(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  22058. {
  22059. ma_result result = MA_SUCCESS;
  22060. MA_MMRESULT resultMM;
  22061. ma_uint32 totalFramesRead;
  22062. MA_WAVEHDR* pWAVEHDR;
  22063. MA_ASSERT(pDevice != NULL);
  22064. MA_ASSERT(pPCMFrames != NULL);
  22065. if (pFramesRead != NULL) {
  22066. *pFramesRead = 0;
  22067. }
  22068. pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture;
  22069. /* Keep processing as much data as possible. */
  22070. totalFramesRead = 0;
  22071. while (totalFramesRead < frameCount) {
  22072. /* If the current header has some space available we need to write part of it. */
  22073. if (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser == 0) { /* 0 = unlocked. */
  22074. /* The buffer is available for reading. If we fully consume it we need to add it back to the buffer. */
  22075. ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  22076. ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedCapture;
  22077. ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesRead));
  22078. const void* pSrc = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderCapture].lpData, pDevice->winmm.headerFramesConsumedCapture*bpf);
  22079. void* pDst = ma_offset_ptr(pPCMFrames, totalFramesRead*bpf);
  22080. MA_COPY_MEMORY(pDst, pSrc, framesToCopy*bpf);
  22081. pDevice->winmm.headerFramesConsumedCapture += framesToCopy;
  22082. totalFramesRead += framesToCopy;
  22083. /* If we've consumed the buffer entirely we need to add it back to the device. */
  22084. if (pDevice->winmm.headerFramesConsumedCapture == (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf)) {
  22085. pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 1; /* 1 = locked. */
  22086. pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags &= ~MA_WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */
  22087. /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
  22088. ResetEvent((HANDLE)pDevice->winmm.hEventCapture);
  22089. /* The device will be started here. */
  22090. resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[pDevice->winmm.iNextHeaderCapture], sizeof(MA_WAVEHDR));
  22091. if (resultMM != MA_MMSYSERR_NOERROR) {
  22092. result = ma_result_from_MMRESULT(resultMM);
  22093. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] waveInAddBuffer() failed.");
  22094. break;
  22095. }
  22096. /* Make sure we move to the next header. */
  22097. pDevice->winmm.iNextHeaderCapture = (pDevice->winmm.iNextHeaderCapture + 1) % pDevice->capture.internalPeriods;
  22098. pDevice->winmm.headerFramesConsumedCapture = 0;
  22099. }
  22100. /* If at this point we have filled the entire input buffer we can return. */
  22101. MA_ASSERT(totalFramesRead <= frameCount);
  22102. if (totalFramesRead == frameCount) {
  22103. break;
  22104. }
  22105. /* Getting here means there's more to process. */
  22106. continue;
  22107. }
  22108. /* Getting here means there isn't enough any data left to send to the client which means we need to wait for more. */
  22109. if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventCapture, INFINITE) != WAIT_OBJECT_0) {
  22110. result = MA_ERROR;
  22111. break;
  22112. }
  22113. /* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */
  22114. if ((pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags & MA_WHDR_DONE) != 0) {
  22115. pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 0; /* 0 = unlocked (make it available for reading). */
  22116. pDevice->winmm.headerFramesConsumedCapture = 0;
  22117. }
  22118. /* If the device has been stopped we need to break. */
  22119. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  22120. break;
  22121. }
  22122. }
  22123. if (pFramesRead != NULL) {
  22124. *pFramesRead = totalFramesRead;
  22125. }
  22126. return result;
  22127. }
  22128. static ma_result ma_context_uninit__winmm(ma_context* pContext)
  22129. {
  22130. MA_ASSERT(pContext != NULL);
  22131. MA_ASSERT(pContext->backend == ma_backend_winmm);
  22132. ma_dlclose(pContext, pContext->winmm.hWinMM);
  22133. return MA_SUCCESS;
  22134. }
  22135. static ma_result ma_context_init__winmm(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  22136. {
  22137. MA_ASSERT(pContext != NULL);
  22138. (void)pConfig;
  22139. pContext->winmm.hWinMM = ma_dlopen(pContext, "winmm.dll");
  22140. if (pContext->winmm.hWinMM == NULL) {
  22141. return MA_NO_BACKEND;
  22142. }
  22143. pContext->winmm.waveOutGetNumDevs = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutGetNumDevs");
  22144. pContext->winmm.waveOutGetDevCapsA = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutGetDevCapsA");
  22145. pContext->winmm.waveOutOpen = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutOpen");
  22146. pContext->winmm.waveOutClose = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutClose");
  22147. pContext->winmm.waveOutPrepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutPrepareHeader");
  22148. pContext->winmm.waveOutUnprepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutUnprepareHeader");
  22149. pContext->winmm.waveOutWrite = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutWrite");
  22150. pContext->winmm.waveOutReset = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutReset");
  22151. pContext->winmm.waveInGetNumDevs = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInGetNumDevs");
  22152. pContext->winmm.waveInGetDevCapsA = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInGetDevCapsA");
  22153. pContext->winmm.waveInOpen = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInOpen");
  22154. pContext->winmm.waveInClose = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInClose");
  22155. pContext->winmm.waveInPrepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInPrepareHeader");
  22156. pContext->winmm.waveInUnprepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInUnprepareHeader");
  22157. pContext->winmm.waveInAddBuffer = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInAddBuffer");
  22158. pContext->winmm.waveInStart = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInStart");
  22159. pContext->winmm.waveInReset = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInReset");
  22160. pCallbacks->onContextInit = ma_context_init__winmm;
  22161. pCallbacks->onContextUninit = ma_context_uninit__winmm;
  22162. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__winmm;
  22163. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__winmm;
  22164. pCallbacks->onDeviceInit = ma_device_init__winmm;
  22165. pCallbacks->onDeviceUninit = ma_device_uninit__winmm;
  22166. pCallbacks->onDeviceStart = ma_device_start__winmm;
  22167. pCallbacks->onDeviceStop = ma_device_stop__winmm;
  22168. pCallbacks->onDeviceRead = ma_device_read__winmm;
  22169. pCallbacks->onDeviceWrite = ma_device_write__winmm;
  22170. pCallbacks->onDeviceDataLoop = NULL; /* This is a blocking read-write API, so this can be NULL since miniaudio will manage the audio thread for us. */
  22171. return MA_SUCCESS;
  22172. }
  22173. #endif
  22174. /******************************************************************************
  22175. ALSA Backend
  22176. ******************************************************************************/
  22177. #ifdef MA_HAS_ALSA
  22178. #include <poll.h> /* poll(), struct pollfd */
  22179. #include <sys/eventfd.h> /* eventfd() */
  22180. #ifdef MA_NO_RUNTIME_LINKING
  22181. /* asoundlib.h marks some functions with "inline" which isn't always supported. Need to emulate it. */
  22182. #if !defined(__cplusplus)
  22183. #if defined(__STRICT_ANSI__)
  22184. #if !defined(inline)
  22185. #define inline __inline__ __attribute__((always_inline))
  22186. #define MA_INLINE_DEFINED
  22187. #endif
  22188. #endif
  22189. #endif
  22190. #include <alsa/asoundlib.h>
  22191. #if defined(MA_INLINE_DEFINED)
  22192. #undef inline
  22193. #undef MA_INLINE_DEFINED
  22194. #endif
  22195. typedef snd_pcm_uframes_t ma_snd_pcm_uframes_t;
  22196. typedef snd_pcm_sframes_t ma_snd_pcm_sframes_t;
  22197. typedef snd_pcm_stream_t ma_snd_pcm_stream_t;
  22198. typedef snd_pcm_format_t ma_snd_pcm_format_t;
  22199. typedef snd_pcm_access_t ma_snd_pcm_access_t;
  22200. typedef snd_pcm_t ma_snd_pcm_t;
  22201. typedef snd_pcm_hw_params_t ma_snd_pcm_hw_params_t;
  22202. typedef snd_pcm_sw_params_t ma_snd_pcm_sw_params_t;
  22203. typedef snd_pcm_format_mask_t ma_snd_pcm_format_mask_t;
  22204. typedef snd_pcm_info_t ma_snd_pcm_info_t;
  22205. typedef snd_pcm_channel_area_t ma_snd_pcm_channel_area_t;
  22206. typedef snd_pcm_chmap_t ma_snd_pcm_chmap_t;
  22207. typedef snd_pcm_state_t ma_snd_pcm_state_t;
  22208. /* snd_pcm_stream_t */
  22209. #define MA_SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK
  22210. #define MA_SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE
  22211. /* snd_pcm_format_t */
  22212. #define MA_SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN
  22213. #define MA_SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8
  22214. #define MA_SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE
  22215. #define MA_SND_PCM_FORMAT_S16_BE SND_PCM_FORMAT_S16_BE
  22216. #define MA_SND_PCM_FORMAT_S24_LE SND_PCM_FORMAT_S24_LE
  22217. #define MA_SND_PCM_FORMAT_S24_BE SND_PCM_FORMAT_S24_BE
  22218. #define MA_SND_PCM_FORMAT_S32_LE SND_PCM_FORMAT_S32_LE
  22219. #define MA_SND_PCM_FORMAT_S32_BE SND_PCM_FORMAT_S32_BE
  22220. #define MA_SND_PCM_FORMAT_FLOAT_LE SND_PCM_FORMAT_FLOAT_LE
  22221. #define MA_SND_PCM_FORMAT_FLOAT_BE SND_PCM_FORMAT_FLOAT_BE
  22222. #define MA_SND_PCM_FORMAT_FLOAT64_LE SND_PCM_FORMAT_FLOAT64_LE
  22223. #define MA_SND_PCM_FORMAT_FLOAT64_BE SND_PCM_FORMAT_FLOAT64_BE
  22224. #define MA_SND_PCM_FORMAT_MU_LAW SND_PCM_FORMAT_MU_LAW
  22225. #define MA_SND_PCM_FORMAT_A_LAW SND_PCM_FORMAT_A_LAW
  22226. #define MA_SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE
  22227. #define MA_SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE
  22228. /* ma_snd_pcm_access_t */
  22229. #define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED SND_PCM_ACCESS_MMAP_INTERLEAVED
  22230. #define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED SND_PCM_ACCESS_MMAP_NONINTERLEAVED
  22231. #define MA_SND_PCM_ACCESS_MMAP_COMPLEX SND_PCM_ACCESS_MMAP_COMPLEX
  22232. #define MA_SND_PCM_ACCESS_RW_INTERLEAVED SND_PCM_ACCESS_RW_INTERLEAVED
  22233. #define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED SND_PCM_ACCESS_RW_NONINTERLEAVED
  22234. /* Channel positions. */
  22235. #define MA_SND_CHMAP_UNKNOWN SND_CHMAP_UNKNOWN
  22236. #define MA_SND_CHMAP_NA SND_CHMAP_NA
  22237. #define MA_SND_CHMAP_MONO SND_CHMAP_MONO
  22238. #define MA_SND_CHMAP_FL SND_CHMAP_FL
  22239. #define MA_SND_CHMAP_FR SND_CHMAP_FR
  22240. #define MA_SND_CHMAP_RL SND_CHMAP_RL
  22241. #define MA_SND_CHMAP_RR SND_CHMAP_RR
  22242. #define MA_SND_CHMAP_FC SND_CHMAP_FC
  22243. #define MA_SND_CHMAP_LFE SND_CHMAP_LFE
  22244. #define MA_SND_CHMAP_SL SND_CHMAP_SL
  22245. #define MA_SND_CHMAP_SR SND_CHMAP_SR
  22246. #define MA_SND_CHMAP_RC SND_CHMAP_RC
  22247. #define MA_SND_CHMAP_FLC SND_CHMAP_FLC
  22248. #define MA_SND_CHMAP_FRC SND_CHMAP_FRC
  22249. #define MA_SND_CHMAP_RLC SND_CHMAP_RLC
  22250. #define MA_SND_CHMAP_RRC SND_CHMAP_RRC
  22251. #define MA_SND_CHMAP_FLW SND_CHMAP_FLW
  22252. #define MA_SND_CHMAP_FRW SND_CHMAP_FRW
  22253. #define MA_SND_CHMAP_FLH SND_CHMAP_FLH
  22254. #define MA_SND_CHMAP_FCH SND_CHMAP_FCH
  22255. #define MA_SND_CHMAP_FRH SND_CHMAP_FRH
  22256. #define MA_SND_CHMAP_TC SND_CHMAP_TC
  22257. #define MA_SND_CHMAP_TFL SND_CHMAP_TFL
  22258. #define MA_SND_CHMAP_TFR SND_CHMAP_TFR
  22259. #define MA_SND_CHMAP_TFC SND_CHMAP_TFC
  22260. #define MA_SND_CHMAP_TRL SND_CHMAP_TRL
  22261. #define MA_SND_CHMAP_TRR SND_CHMAP_TRR
  22262. #define MA_SND_CHMAP_TRC SND_CHMAP_TRC
  22263. #define MA_SND_CHMAP_TFLC SND_CHMAP_TFLC
  22264. #define MA_SND_CHMAP_TFRC SND_CHMAP_TFRC
  22265. #define MA_SND_CHMAP_TSL SND_CHMAP_TSL
  22266. #define MA_SND_CHMAP_TSR SND_CHMAP_TSR
  22267. #define MA_SND_CHMAP_LLFE SND_CHMAP_LLFE
  22268. #define MA_SND_CHMAP_RLFE SND_CHMAP_RLFE
  22269. #define MA_SND_CHMAP_BC SND_CHMAP_BC
  22270. #define MA_SND_CHMAP_BLC SND_CHMAP_BLC
  22271. #define MA_SND_CHMAP_BRC SND_CHMAP_BRC
  22272. /* Open mode flags. */
  22273. #define MA_SND_PCM_NO_AUTO_RESAMPLE SND_PCM_NO_AUTO_RESAMPLE
  22274. #define MA_SND_PCM_NO_AUTO_CHANNELS SND_PCM_NO_AUTO_CHANNELS
  22275. #define MA_SND_PCM_NO_AUTO_FORMAT SND_PCM_NO_AUTO_FORMAT
  22276. #else
  22277. #include <errno.h> /* For EPIPE, etc. */
  22278. typedef unsigned long ma_snd_pcm_uframes_t;
  22279. typedef long ma_snd_pcm_sframes_t;
  22280. typedef int ma_snd_pcm_stream_t;
  22281. typedef int ma_snd_pcm_format_t;
  22282. typedef int ma_snd_pcm_access_t;
  22283. typedef int ma_snd_pcm_state_t;
  22284. typedef struct ma_snd_pcm_t ma_snd_pcm_t;
  22285. typedef struct ma_snd_pcm_hw_params_t ma_snd_pcm_hw_params_t;
  22286. typedef struct ma_snd_pcm_sw_params_t ma_snd_pcm_sw_params_t;
  22287. typedef struct ma_snd_pcm_format_mask_t ma_snd_pcm_format_mask_t;
  22288. typedef struct ma_snd_pcm_info_t ma_snd_pcm_info_t;
  22289. typedef struct
  22290. {
  22291. void* addr;
  22292. unsigned int first;
  22293. unsigned int step;
  22294. } ma_snd_pcm_channel_area_t;
  22295. typedef struct
  22296. {
  22297. unsigned int channels;
  22298. unsigned int pos[1];
  22299. } ma_snd_pcm_chmap_t;
  22300. /* snd_pcm_state_t */
  22301. #define MA_SND_PCM_STATE_OPEN 0
  22302. #define MA_SND_PCM_STATE_SETUP 1
  22303. #define MA_SND_PCM_STATE_PREPARED 2
  22304. #define MA_SND_PCM_STATE_RUNNING 3
  22305. #define MA_SND_PCM_STATE_XRUN 4
  22306. #define MA_SND_PCM_STATE_DRAINING 5
  22307. #define MA_SND_PCM_STATE_PAUSED 6
  22308. #define MA_SND_PCM_STATE_SUSPENDED 7
  22309. #define MA_SND_PCM_STATE_DISCONNECTED 8
  22310. /* snd_pcm_stream_t */
  22311. #define MA_SND_PCM_STREAM_PLAYBACK 0
  22312. #define MA_SND_PCM_STREAM_CAPTURE 1
  22313. /* snd_pcm_format_t */
  22314. #define MA_SND_PCM_FORMAT_UNKNOWN -1
  22315. #define MA_SND_PCM_FORMAT_U8 1
  22316. #define MA_SND_PCM_FORMAT_S16_LE 2
  22317. #define MA_SND_PCM_FORMAT_S16_BE 3
  22318. #define MA_SND_PCM_FORMAT_S24_LE 6
  22319. #define MA_SND_PCM_FORMAT_S24_BE 7
  22320. #define MA_SND_PCM_FORMAT_S32_LE 10
  22321. #define MA_SND_PCM_FORMAT_S32_BE 11
  22322. #define MA_SND_PCM_FORMAT_FLOAT_LE 14
  22323. #define MA_SND_PCM_FORMAT_FLOAT_BE 15
  22324. #define MA_SND_PCM_FORMAT_FLOAT64_LE 16
  22325. #define MA_SND_PCM_FORMAT_FLOAT64_BE 17
  22326. #define MA_SND_PCM_FORMAT_MU_LAW 20
  22327. #define MA_SND_PCM_FORMAT_A_LAW 21
  22328. #define MA_SND_PCM_FORMAT_S24_3LE 32
  22329. #define MA_SND_PCM_FORMAT_S24_3BE 33
  22330. /* snd_pcm_access_t */
  22331. #define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED 0
  22332. #define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED 1
  22333. #define MA_SND_PCM_ACCESS_MMAP_COMPLEX 2
  22334. #define MA_SND_PCM_ACCESS_RW_INTERLEAVED 3
  22335. #define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED 4
  22336. /* Channel positions. */
  22337. #define MA_SND_CHMAP_UNKNOWN 0
  22338. #define MA_SND_CHMAP_NA 1
  22339. #define MA_SND_CHMAP_MONO 2
  22340. #define MA_SND_CHMAP_FL 3
  22341. #define MA_SND_CHMAP_FR 4
  22342. #define MA_SND_CHMAP_RL 5
  22343. #define MA_SND_CHMAP_RR 6
  22344. #define MA_SND_CHMAP_FC 7
  22345. #define MA_SND_CHMAP_LFE 8
  22346. #define MA_SND_CHMAP_SL 9
  22347. #define MA_SND_CHMAP_SR 10
  22348. #define MA_SND_CHMAP_RC 11
  22349. #define MA_SND_CHMAP_FLC 12
  22350. #define MA_SND_CHMAP_FRC 13
  22351. #define MA_SND_CHMAP_RLC 14
  22352. #define MA_SND_CHMAP_RRC 15
  22353. #define MA_SND_CHMAP_FLW 16
  22354. #define MA_SND_CHMAP_FRW 17
  22355. #define MA_SND_CHMAP_FLH 18
  22356. #define MA_SND_CHMAP_FCH 19
  22357. #define MA_SND_CHMAP_FRH 20
  22358. #define MA_SND_CHMAP_TC 21
  22359. #define MA_SND_CHMAP_TFL 22
  22360. #define MA_SND_CHMAP_TFR 23
  22361. #define MA_SND_CHMAP_TFC 24
  22362. #define MA_SND_CHMAP_TRL 25
  22363. #define MA_SND_CHMAP_TRR 26
  22364. #define MA_SND_CHMAP_TRC 27
  22365. #define MA_SND_CHMAP_TFLC 28
  22366. #define MA_SND_CHMAP_TFRC 29
  22367. #define MA_SND_CHMAP_TSL 30
  22368. #define MA_SND_CHMAP_TSR 31
  22369. #define MA_SND_CHMAP_LLFE 32
  22370. #define MA_SND_CHMAP_RLFE 33
  22371. #define MA_SND_CHMAP_BC 34
  22372. #define MA_SND_CHMAP_BLC 35
  22373. #define MA_SND_CHMAP_BRC 36
  22374. /* Open mode flags. */
  22375. #define MA_SND_PCM_NO_AUTO_RESAMPLE 0x00010000
  22376. #define MA_SND_PCM_NO_AUTO_CHANNELS 0x00020000
  22377. #define MA_SND_PCM_NO_AUTO_FORMAT 0x00040000
  22378. #endif
  22379. typedef int (* ma_snd_pcm_open_proc) (ma_snd_pcm_t **pcm, const char *name, ma_snd_pcm_stream_t stream, int mode);
  22380. typedef int (* ma_snd_pcm_close_proc) (ma_snd_pcm_t *pcm);
  22381. typedef size_t (* ma_snd_pcm_hw_params_sizeof_proc) (void);
  22382. typedef int (* ma_snd_pcm_hw_params_any_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params);
  22383. typedef int (* ma_snd_pcm_hw_params_set_format_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t val);
  22384. typedef int (* ma_snd_pcm_hw_params_set_format_first_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format);
  22385. typedef void (* ma_snd_pcm_hw_params_get_format_mask_proc) (ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_mask_t *mask);
  22386. typedef int (* ma_snd_pcm_hw_params_set_channels_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val);
  22387. typedef int (* ma_snd_pcm_hw_params_set_channels_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val);
  22388. typedef int (* ma_snd_pcm_hw_params_set_channels_minmax_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *minimum, unsigned int *maximum);
  22389. typedef int (* ma_snd_pcm_hw_params_set_rate_resample_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val);
  22390. typedef int (* ma_snd_pcm_hw_params_set_rate_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val, int dir);
  22391. typedef int (* ma_snd_pcm_hw_params_set_rate_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
  22392. typedef int (* ma_snd_pcm_hw_params_set_buffer_size_near_proc)(ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val);
  22393. typedef int (* ma_snd_pcm_hw_params_set_periods_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
  22394. typedef int (* ma_snd_pcm_hw_params_set_access_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t _access);
  22395. typedef int (* ma_snd_pcm_hw_params_get_format_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format);
  22396. typedef int (* ma_snd_pcm_hw_params_get_channels_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
  22397. typedef int (* ma_snd_pcm_hw_params_get_channels_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
  22398. typedef int (* ma_snd_pcm_hw_params_get_channels_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
  22399. typedef int (* ma_snd_pcm_hw_params_get_rate_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
  22400. typedef int (* ma_snd_pcm_hw_params_get_rate_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
  22401. typedef int (* ma_snd_pcm_hw_params_get_rate_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
  22402. typedef int (* ma_snd_pcm_hw_params_get_buffer_size_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val);
  22403. typedef int (* ma_snd_pcm_hw_params_get_periods_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
  22404. typedef int (* ma_snd_pcm_hw_params_get_access_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t *_access);
  22405. typedef int (* ma_snd_pcm_hw_params_test_format_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t val);
  22406. typedef int (* ma_snd_pcm_hw_params_test_channels_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val);
  22407. typedef int (* ma_snd_pcm_hw_params_test_rate_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val, int dir);
  22408. typedef int (* ma_snd_pcm_hw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params);
  22409. typedef size_t (* ma_snd_pcm_sw_params_sizeof_proc) (void);
  22410. typedef int (* ma_snd_pcm_sw_params_current_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params);
  22411. typedef int (* ma_snd_pcm_sw_params_get_boundary_proc) (const ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t* val);
  22412. typedef int (* ma_snd_pcm_sw_params_set_avail_min_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val);
  22413. typedef int (* ma_snd_pcm_sw_params_set_start_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val);
  22414. typedef int (* ma_snd_pcm_sw_params_set_stop_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val);
  22415. typedef int (* ma_snd_pcm_sw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params);
  22416. typedef size_t (* ma_snd_pcm_format_mask_sizeof_proc) (void);
  22417. typedef int (* ma_snd_pcm_format_mask_test_proc) (const ma_snd_pcm_format_mask_t *mask, ma_snd_pcm_format_t val);
  22418. typedef ma_snd_pcm_chmap_t * (* ma_snd_pcm_get_chmap_proc) (ma_snd_pcm_t *pcm);
  22419. typedef ma_snd_pcm_state_t (* ma_snd_pcm_state_proc) (ma_snd_pcm_t *pcm);
  22420. typedef int (* ma_snd_pcm_prepare_proc) (ma_snd_pcm_t *pcm);
  22421. typedef int (* ma_snd_pcm_start_proc) (ma_snd_pcm_t *pcm);
  22422. typedef int (* ma_snd_pcm_drop_proc) (ma_snd_pcm_t *pcm);
  22423. typedef int (* ma_snd_pcm_drain_proc) (ma_snd_pcm_t *pcm);
  22424. typedef int (* ma_snd_pcm_reset_proc) (ma_snd_pcm_t *pcm);
  22425. typedef int (* ma_snd_device_name_hint_proc) (int card, const char *iface, void ***hints);
  22426. typedef char * (* ma_snd_device_name_get_hint_proc) (const void *hint, const char *id);
  22427. typedef int (* ma_snd_card_get_index_proc) (const char *name);
  22428. typedef int (* ma_snd_device_name_free_hint_proc) (void **hints);
  22429. typedef int (* ma_snd_pcm_mmap_begin_proc) (ma_snd_pcm_t *pcm, const ma_snd_pcm_channel_area_t **areas, ma_snd_pcm_uframes_t *offset, ma_snd_pcm_uframes_t *frames);
  22430. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_mmap_commit_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_uframes_t offset, ma_snd_pcm_uframes_t frames);
  22431. typedef int (* ma_snd_pcm_recover_proc) (ma_snd_pcm_t *pcm, int err, int silent);
  22432. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_readi_proc) (ma_snd_pcm_t *pcm, void *buffer, ma_snd_pcm_uframes_t size);
  22433. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_writei_proc) (ma_snd_pcm_t *pcm, const void *buffer, ma_snd_pcm_uframes_t size);
  22434. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_proc) (ma_snd_pcm_t *pcm);
  22435. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_update_proc) (ma_snd_pcm_t *pcm);
  22436. typedef int (* ma_snd_pcm_wait_proc) (ma_snd_pcm_t *pcm, int timeout);
  22437. typedef int (* ma_snd_pcm_nonblock_proc) (ma_snd_pcm_t *pcm, int nonblock);
  22438. typedef int (* ma_snd_pcm_info_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_info_t* info);
  22439. typedef size_t (* ma_snd_pcm_info_sizeof_proc) (void);
  22440. typedef const char* (* ma_snd_pcm_info_get_name_proc) (const ma_snd_pcm_info_t* info);
  22441. typedef int (* ma_snd_pcm_poll_descriptors_proc) (ma_snd_pcm_t *pcm, struct pollfd *pfds, unsigned int space);
  22442. typedef int (* ma_snd_pcm_poll_descriptors_count_proc) (ma_snd_pcm_t *pcm);
  22443. typedef int (* ma_snd_pcm_poll_descriptors_revents_proc) (ma_snd_pcm_t *pcm, struct pollfd *pfds, unsigned int nfds, unsigned short *revents);
  22444. typedef int (* ma_snd_config_update_free_global_proc) (void);
  22445. /* This array specifies each of the common devices that can be used for both playback and capture. */
  22446. static const char* g_maCommonDeviceNamesALSA[] = {
  22447. "default",
  22448. "null",
  22449. "pulse",
  22450. "jack"
  22451. };
  22452. /* This array allows us to blacklist specific playback devices. */
  22453. static const char* g_maBlacklistedPlaybackDeviceNamesALSA[] = {
  22454. ""
  22455. };
  22456. /* This array allows us to blacklist specific capture devices. */
  22457. static const char* g_maBlacklistedCaptureDeviceNamesALSA[] = {
  22458. ""
  22459. };
  22460. static ma_snd_pcm_format_t ma_convert_ma_format_to_alsa_format(ma_format format)
  22461. {
  22462. ma_snd_pcm_format_t ALSAFormats[] = {
  22463. MA_SND_PCM_FORMAT_UNKNOWN, /* ma_format_unknown */
  22464. MA_SND_PCM_FORMAT_U8, /* ma_format_u8 */
  22465. MA_SND_PCM_FORMAT_S16_LE, /* ma_format_s16 */
  22466. MA_SND_PCM_FORMAT_S24_3LE, /* ma_format_s24 */
  22467. MA_SND_PCM_FORMAT_S32_LE, /* ma_format_s32 */
  22468. MA_SND_PCM_FORMAT_FLOAT_LE /* ma_format_f32 */
  22469. };
  22470. if (ma_is_big_endian()) {
  22471. ALSAFormats[0] = MA_SND_PCM_FORMAT_UNKNOWN;
  22472. ALSAFormats[1] = MA_SND_PCM_FORMAT_U8;
  22473. ALSAFormats[2] = MA_SND_PCM_FORMAT_S16_BE;
  22474. ALSAFormats[3] = MA_SND_PCM_FORMAT_S24_3BE;
  22475. ALSAFormats[4] = MA_SND_PCM_FORMAT_S32_BE;
  22476. ALSAFormats[5] = MA_SND_PCM_FORMAT_FLOAT_BE;
  22477. }
  22478. return ALSAFormats[format];
  22479. }
  22480. static ma_format ma_format_from_alsa(ma_snd_pcm_format_t formatALSA)
  22481. {
  22482. if (ma_is_little_endian()) {
  22483. switch (formatALSA) {
  22484. case MA_SND_PCM_FORMAT_S16_LE: return ma_format_s16;
  22485. case MA_SND_PCM_FORMAT_S24_3LE: return ma_format_s24;
  22486. case MA_SND_PCM_FORMAT_S32_LE: return ma_format_s32;
  22487. case MA_SND_PCM_FORMAT_FLOAT_LE: return ma_format_f32;
  22488. default: break;
  22489. }
  22490. } else {
  22491. switch (formatALSA) {
  22492. case MA_SND_PCM_FORMAT_S16_BE: return ma_format_s16;
  22493. case MA_SND_PCM_FORMAT_S24_3BE: return ma_format_s24;
  22494. case MA_SND_PCM_FORMAT_S32_BE: return ma_format_s32;
  22495. case MA_SND_PCM_FORMAT_FLOAT_BE: return ma_format_f32;
  22496. default: break;
  22497. }
  22498. }
  22499. /* Endian agnostic. */
  22500. switch (formatALSA) {
  22501. case MA_SND_PCM_FORMAT_U8: return ma_format_u8;
  22502. default: return ma_format_unknown;
  22503. }
  22504. }
  22505. static ma_channel ma_convert_alsa_channel_position_to_ma_channel(unsigned int alsaChannelPos)
  22506. {
  22507. switch (alsaChannelPos)
  22508. {
  22509. case MA_SND_CHMAP_MONO: return MA_CHANNEL_MONO;
  22510. case MA_SND_CHMAP_FL: return MA_CHANNEL_FRONT_LEFT;
  22511. case MA_SND_CHMAP_FR: return MA_CHANNEL_FRONT_RIGHT;
  22512. case MA_SND_CHMAP_RL: return MA_CHANNEL_BACK_LEFT;
  22513. case MA_SND_CHMAP_RR: return MA_CHANNEL_BACK_RIGHT;
  22514. case MA_SND_CHMAP_FC: return MA_CHANNEL_FRONT_CENTER;
  22515. case MA_SND_CHMAP_LFE: return MA_CHANNEL_LFE;
  22516. case MA_SND_CHMAP_SL: return MA_CHANNEL_SIDE_LEFT;
  22517. case MA_SND_CHMAP_SR: return MA_CHANNEL_SIDE_RIGHT;
  22518. case MA_SND_CHMAP_RC: return MA_CHANNEL_BACK_CENTER;
  22519. case MA_SND_CHMAP_FLC: return MA_CHANNEL_FRONT_LEFT_CENTER;
  22520. case MA_SND_CHMAP_FRC: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  22521. case MA_SND_CHMAP_RLC: return 0;
  22522. case MA_SND_CHMAP_RRC: return 0;
  22523. case MA_SND_CHMAP_FLW: return 0;
  22524. case MA_SND_CHMAP_FRW: return 0;
  22525. case MA_SND_CHMAP_FLH: return 0;
  22526. case MA_SND_CHMAP_FCH: return 0;
  22527. case MA_SND_CHMAP_FRH: return 0;
  22528. case MA_SND_CHMAP_TC: return MA_CHANNEL_TOP_CENTER;
  22529. case MA_SND_CHMAP_TFL: return MA_CHANNEL_TOP_FRONT_LEFT;
  22530. case MA_SND_CHMAP_TFR: return MA_CHANNEL_TOP_FRONT_RIGHT;
  22531. case MA_SND_CHMAP_TFC: return MA_CHANNEL_TOP_FRONT_CENTER;
  22532. case MA_SND_CHMAP_TRL: return MA_CHANNEL_TOP_BACK_LEFT;
  22533. case MA_SND_CHMAP_TRR: return MA_CHANNEL_TOP_BACK_RIGHT;
  22534. case MA_SND_CHMAP_TRC: return MA_CHANNEL_TOP_BACK_CENTER;
  22535. default: break;
  22536. }
  22537. return 0;
  22538. }
  22539. static ma_bool32 ma_is_common_device_name__alsa(const char* name)
  22540. {
  22541. size_t iName;
  22542. for (iName = 0; iName < ma_countof(g_maCommonDeviceNamesALSA); ++iName) {
  22543. if (ma_strcmp(name, g_maCommonDeviceNamesALSA[iName]) == 0) {
  22544. return MA_TRUE;
  22545. }
  22546. }
  22547. return MA_FALSE;
  22548. }
  22549. static ma_bool32 ma_is_playback_device_blacklisted__alsa(const char* name)
  22550. {
  22551. size_t iName;
  22552. for (iName = 0; iName < ma_countof(g_maBlacklistedPlaybackDeviceNamesALSA); ++iName) {
  22553. if (ma_strcmp(name, g_maBlacklistedPlaybackDeviceNamesALSA[iName]) == 0) {
  22554. return MA_TRUE;
  22555. }
  22556. }
  22557. return MA_FALSE;
  22558. }
  22559. static ma_bool32 ma_is_capture_device_blacklisted__alsa(const char* name)
  22560. {
  22561. size_t iName;
  22562. for (iName = 0; iName < ma_countof(g_maBlacklistedCaptureDeviceNamesALSA); ++iName) {
  22563. if (ma_strcmp(name, g_maBlacklistedCaptureDeviceNamesALSA[iName]) == 0) {
  22564. return MA_TRUE;
  22565. }
  22566. }
  22567. return MA_FALSE;
  22568. }
  22569. static ma_bool32 ma_is_device_blacklisted__alsa(ma_device_type deviceType, const char* name)
  22570. {
  22571. if (deviceType == ma_device_type_playback) {
  22572. return ma_is_playback_device_blacklisted__alsa(name);
  22573. } else {
  22574. return ma_is_capture_device_blacklisted__alsa(name);
  22575. }
  22576. }
  22577. static const char* ma_find_char(const char* str, char c, int* index)
  22578. {
  22579. int i = 0;
  22580. for (;;) {
  22581. if (str[i] == '\0') {
  22582. if (index) *index = -1;
  22583. return NULL;
  22584. }
  22585. if (str[i] == c) {
  22586. if (index) *index = i;
  22587. return str + i;
  22588. }
  22589. i += 1;
  22590. }
  22591. /* Should never get here, but treat it as though the character was not found to make me feel better inside. */
  22592. if (index) *index = -1;
  22593. return NULL;
  22594. }
  22595. static ma_bool32 ma_is_device_name_in_hw_format__alsa(const char* hwid)
  22596. {
  22597. /* This function is just checking whether or not hwid is in "hw:%d,%d" format. */
  22598. int commaPos;
  22599. const char* dev;
  22600. int i;
  22601. if (hwid == NULL) {
  22602. return MA_FALSE;
  22603. }
  22604. if (hwid[0] != 'h' || hwid[1] != 'w' || hwid[2] != ':') {
  22605. return MA_FALSE;
  22606. }
  22607. hwid += 3;
  22608. dev = ma_find_char(hwid, ',', &commaPos);
  22609. if (dev == NULL) {
  22610. return MA_FALSE;
  22611. } else {
  22612. dev += 1; /* Skip past the ",". */
  22613. }
  22614. /* Check if the part between the ":" and the "," contains only numbers. If not, return false. */
  22615. for (i = 0; i < commaPos; ++i) {
  22616. if (hwid[i] < '0' || hwid[i] > '9') {
  22617. return MA_FALSE;
  22618. }
  22619. }
  22620. /* Check if everything after the "," is numeric. If not, return false. */
  22621. i = 0;
  22622. while (dev[i] != '\0') {
  22623. if (dev[i] < '0' || dev[i] > '9') {
  22624. return MA_FALSE;
  22625. }
  22626. i += 1;
  22627. }
  22628. return MA_TRUE;
  22629. }
  22630. static int ma_convert_device_name_to_hw_format__alsa(ma_context* pContext, char* dst, size_t dstSize, const char* src) /* Returns 0 on success, non-0 on error. */
  22631. {
  22632. /* src should look something like this: "hw:CARD=I82801AAICH,DEV=0" */
  22633. int colonPos;
  22634. int commaPos;
  22635. char card[256];
  22636. const char* dev;
  22637. int cardIndex;
  22638. if (dst == NULL) {
  22639. return -1;
  22640. }
  22641. if (dstSize < 7) {
  22642. return -1; /* Absolute minimum size of the output buffer is 7 bytes. */
  22643. }
  22644. *dst = '\0'; /* Safety. */
  22645. if (src == NULL) {
  22646. return -1;
  22647. }
  22648. /* If the input name is already in "hw:%d,%d" format, just return that verbatim. */
  22649. if (ma_is_device_name_in_hw_format__alsa(src)) {
  22650. return ma_strcpy_s(dst, dstSize, src);
  22651. }
  22652. src = ma_find_char(src, ':', &colonPos);
  22653. if (src == NULL) {
  22654. return -1; /* Couldn't find a colon */
  22655. }
  22656. dev = ma_find_char(src, ',', &commaPos);
  22657. if (dev == NULL) {
  22658. dev = "0";
  22659. ma_strncpy_s(card, sizeof(card), src+6, (size_t)-1); /* +6 = ":CARD=" */
  22660. } else {
  22661. dev = dev + 5; /* +5 = ",DEV=" */
  22662. ma_strncpy_s(card, sizeof(card), src+6, commaPos-6); /* +6 = ":CARD=" */
  22663. }
  22664. cardIndex = ((ma_snd_card_get_index_proc)pContext->alsa.snd_card_get_index)(card);
  22665. if (cardIndex < 0) {
  22666. return -2; /* Failed to retrieve the card index. */
  22667. }
  22668. /* Construction. */
  22669. dst[0] = 'h'; dst[1] = 'w'; dst[2] = ':';
  22670. if (ma_itoa_s(cardIndex, dst+3, dstSize-3, 10) != 0) {
  22671. return -3;
  22672. }
  22673. if (ma_strcat_s(dst, dstSize, ",") != 0) {
  22674. return -3;
  22675. }
  22676. if (ma_strcat_s(dst, dstSize, dev) != 0) {
  22677. return -3;
  22678. }
  22679. return 0;
  22680. }
  22681. static ma_bool32 ma_does_id_exist_in_list__alsa(ma_device_id* pUniqueIDs, ma_uint32 count, const char* pHWID)
  22682. {
  22683. ma_uint32 i;
  22684. MA_ASSERT(pHWID != NULL);
  22685. for (i = 0; i < count; ++i) {
  22686. if (ma_strcmp(pUniqueIDs[i].alsa, pHWID) == 0) {
  22687. return MA_TRUE;
  22688. }
  22689. }
  22690. return MA_FALSE;
  22691. }
  22692. static ma_result ma_context_open_pcm__alsa(ma_context* pContext, ma_share_mode shareMode, ma_device_type deviceType, const ma_device_id* pDeviceID, int openMode, ma_snd_pcm_t** ppPCM)
  22693. {
  22694. ma_snd_pcm_t* pPCM;
  22695. ma_snd_pcm_stream_t stream;
  22696. MA_ASSERT(pContext != NULL);
  22697. MA_ASSERT(ppPCM != NULL);
  22698. *ppPCM = NULL;
  22699. pPCM = NULL;
  22700. stream = (deviceType == ma_device_type_playback) ? MA_SND_PCM_STREAM_PLAYBACK : MA_SND_PCM_STREAM_CAPTURE;
  22701. if (pDeviceID == NULL) {
  22702. ma_bool32 isDeviceOpen;
  22703. size_t i;
  22704. /*
  22705. We're opening the default device. I don't know if trying anything other than "default" is necessary, but it makes
  22706. me feel better to try as hard as we can get to get _something_ working.
  22707. */
  22708. const char* defaultDeviceNames[] = {
  22709. "default",
  22710. NULL,
  22711. NULL,
  22712. NULL,
  22713. NULL,
  22714. NULL,
  22715. NULL
  22716. };
  22717. if (shareMode == ma_share_mode_exclusive) {
  22718. defaultDeviceNames[1] = "hw";
  22719. defaultDeviceNames[2] = "hw:0";
  22720. defaultDeviceNames[3] = "hw:0,0";
  22721. } else {
  22722. if (deviceType == ma_device_type_playback) {
  22723. defaultDeviceNames[1] = "dmix";
  22724. defaultDeviceNames[2] = "dmix:0";
  22725. defaultDeviceNames[3] = "dmix:0,0";
  22726. } else {
  22727. defaultDeviceNames[1] = "dsnoop";
  22728. defaultDeviceNames[2] = "dsnoop:0";
  22729. defaultDeviceNames[3] = "dsnoop:0,0";
  22730. }
  22731. defaultDeviceNames[4] = "hw";
  22732. defaultDeviceNames[5] = "hw:0";
  22733. defaultDeviceNames[6] = "hw:0,0";
  22734. }
  22735. isDeviceOpen = MA_FALSE;
  22736. for (i = 0; i < ma_countof(defaultDeviceNames); ++i) {
  22737. if (defaultDeviceNames[i] != NULL && defaultDeviceNames[i][0] != '\0') {
  22738. if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, defaultDeviceNames[i], stream, openMode) == 0) {
  22739. isDeviceOpen = MA_TRUE;
  22740. break;
  22741. }
  22742. }
  22743. }
  22744. if (!isDeviceOpen) {
  22745. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed when trying to open an appropriate default device.");
  22746. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  22747. }
  22748. } else {
  22749. /*
  22750. We're trying to open a specific device. There's a few things to consider here:
  22751. miniaudio recongnizes a special format of device id that excludes the "hw", "dmix", etc. prefix. It looks like this: ":0,0", ":0,1", etc. When
  22752. an ID of this format is specified, it indicates to miniaudio that it can try different combinations of plugins ("hw", "dmix", etc.) until it
  22753. finds an appropriate one that works. This comes in very handy when trying to open a device in shared mode ("dmix"), vs exclusive mode ("hw").
  22754. */
  22755. /* May end up needing to make small adjustments to the ID, so make a copy. */
  22756. ma_device_id deviceID = *pDeviceID;
  22757. int resultALSA = -ENODEV;
  22758. if (deviceID.alsa[0] != ':') {
  22759. /* The ID is not in ":0,0" format. Use the ID exactly as-is. */
  22760. resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, deviceID.alsa, stream, openMode);
  22761. } else {
  22762. char hwid[256];
  22763. /* The ID is in ":0,0" format. Try different plugins depending on the shared mode. */
  22764. if (deviceID.alsa[1] == '\0') {
  22765. deviceID.alsa[0] = '\0'; /* An ID of ":" should be converted to "". */
  22766. }
  22767. if (shareMode == ma_share_mode_shared) {
  22768. if (deviceType == ma_device_type_playback) {
  22769. ma_strcpy_s(hwid, sizeof(hwid), "dmix");
  22770. } else {
  22771. ma_strcpy_s(hwid, sizeof(hwid), "dsnoop");
  22772. }
  22773. if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) {
  22774. resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode);
  22775. }
  22776. }
  22777. /* If at this point we still don't have an open device it means we're either preferencing exclusive mode or opening with "dmix"/"dsnoop" failed. */
  22778. if (resultALSA != 0) {
  22779. ma_strcpy_s(hwid, sizeof(hwid), "hw");
  22780. if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) {
  22781. resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode);
  22782. }
  22783. }
  22784. }
  22785. if (resultALSA < 0) {
  22786. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed.");
  22787. return ma_result_from_errno(-resultALSA);
  22788. }
  22789. }
  22790. *ppPCM = pPCM;
  22791. return MA_SUCCESS;
  22792. }
  22793. static ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  22794. {
  22795. int resultALSA;
  22796. ma_bool32 cbResult = MA_TRUE;
  22797. char** ppDeviceHints;
  22798. ma_device_id* pUniqueIDs = NULL;
  22799. ma_uint32 uniqueIDCount = 0;
  22800. char** ppNextDeviceHint;
  22801. MA_ASSERT(pContext != NULL);
  22802. MA_ASSERT(callback != NULL);
  22803. ma_mutex_lock(&pContext->alsa.internalDeviceEnumLock);
  22804. resultALSA = ((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints);
  22805. if (resultALSA < 0) {
  22806. ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock);
  22807. return ma_result_from_errno(-resultALSA);
  22808. }
  22809. ppNextDeviceHint = ppDeviceHints;
  22810. while (*ppNextDeviceHint != NULL) {
  22811. char* NAME = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME");
  22812. char* DESC = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC");
  22813. char* IOID = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID");
  22814. ma_device_type deviceType = ma_device_type_playback;
  22815. ma_bool32 stopEnumeration = MA_FALSE;
  22816. char hwid[sizeof(pUniqueIDs->alsa)];
  22817. ma_device_info deviceInfo;
  22818. if ((IOID == NULL || ma_strcmp(IOID, "Output") == 0)) {
  22819. deviceType = ma_device_type_playback;
  22820. }
  22821. if ((IOID != NULL && ma_strcmp(IOID, "Input" ) == 0)) {
  22822. deviceType = ma_device_type_capture;
  22823. }
  22824. if (NAME != NULL) {
  22825. if (pContext->alsa.useVerboseDeviceEnumeration) {
  22826. /* Verbose mode. Use the name exactly as-is. */
  22827. ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1);
  22828. } else {
  22829. /* Simplified mode. Use ":%d,%d" format. */
  22830. if (ma_convert_device_name_to_hw_format__alsa(pContext, hwid, sizeof(hwid), NAME) == 0) {
  22831. /*
  22832. At this point, hwid looks like "hw:0,0". In simplified enumeration mode, we actually want to strip off the
  22833. plugin name so it looks like ":0,0". The reason for this is that this special format is detected at device
  22834. initialization time and is used as an indicator to try and use the most appropriate plugin depending on the
  22835. device type and sharing mode.
  22836. */
  22837. char* dst = hwid;
  22838. char* src = hwid+2;
  22839. while ((*dst++ = *src++));
  22840. } else {
  22841. /* Conversion to "hw:%d,%d" failed. Just use the name as-is. */
  22842. ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1);
  22843. }
  22844. if (ma_does_id_exist_in_list__alsa(pUniqueIDs, uniqueIDCount, hwid)) {
  22845. goto next_device; /* The device has already been enumerated. Move on to the next one. */
  22846. } else {
  22847. /* The device has not yet been enumerated. Make sure it's added to our list so that it's not enumerated again. */
  22848. size_t newCapacity = sizeof(*pUniqueIDs) * (uniqueIDCount + 1);
  22849. ma_device_id* pNewUniqueIDs = (ma_device_id*)ma_realloc(pUniqueIDs, newCapacity, &pContext->allocationCallbacks);
  22850. if (pNewUniqueIDs == NULL) {
  22851. goto next_device; /* Failed to allocate memory. */
  22852. }
  22853. pUniqueIDs = pNewUniqueIDs;
  22854. MA_COPY_MEMORY(pUniqueIDs[uniqueIDCount].alsa, hwid, sizeof(hwid));
  22855. uniqueIDCount += 1;
  22856. }
  22857. }
  22858. } else {
  22859. MA_ZERO_MEMORY(hwid, sizeof(hwid));
  22860. }
  22861. MA_ZERO_OBJECT(&deviceInfo);
  22862. ma_strncpy_s(deviceInfo.id.alsa, sizeof(deviceInfo.id.alsa), hwid, (size_t)-1);
  22863. /*
  22864. There's no good way to determine whether or not a device is the default on Linux. We're just going to do something simple and
  22865. just use the name of "default" as the indicator.
  22866. */
  22867. if (ma_strcmp(deviceInfo.id.alsa, "default") == 0) {
  22868. deviceInfo.isDefault = MA_TRUE;
  22869. }
  22870. /*
  22871. DESC is the friendly name. We treat this slightly differently depending on whether or not we are using verbose
  22872. device enumeration. In verbose mode we want to take the entire description so that the end-user can distinguish
  22873. between the subdevices of each card/dev pair. In simplified mode, however, we only want the first part of the
  22874. description.
  22875. The value in DESC seems to be split into two lines, with the first line being the name of the device and the
  22876. second line being a description of the device. I don't like having the description be across two lines because
  22877. it makes formatting ugly and annoying. I'm therefore deciding to put it all on a single line with the second line
  22878. being put into parentheses. In simplified mode I'm just stripping the second line entirely.
  22879. */
  22880. if (DESC != NULL) {
  22881. int lfPos;
  22882. const char* line2 = ma_find_char(DESC, '\n', &lfPos);
  22883. if (line2 != NULL) {
  22884. line2 += 1; /* Skip past the new-line character. */
  22885. if (pContext->alsa.useVerboseDeviceEnumeration) {
  22886. /* Verbose mode. Put the second line in brackets. */
  22887. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos);
  22888. ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), " (");
  22889. ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), line2);
  22890. ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), ")");
  22891. } else {
  22892. /* Simplified mode. Strip the second line entirely. */
  22893. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos);
  22894. }
  22895. } else {
  22896. /* There's no second line. Just copy the whole description. */
  22897. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, (size_t)-1);
  22898. }
  22899. }
  22900. if (!ma_is_device_blacklisted__alsa(deviceType, NAME)) {
  22901. cbResult = callback(pContext, deviceType, &deviceInfo, pUserData);
  22902. }
  22903. /*
  22904. Some devices are both playback and capture, but they are only enumerated by ALSA once. We need to fire the callback
  22905. again for the other device type in this case. We do this for known devices and where the IOID hint is NULL, which
  22906. means both Input and Output.
  22907. */
  22908. if (cbResult) {
  22909. if (ma_is_common_device_name__alsa(NAME) || IOID == NULL) {
  22910. if (deviceType == ma_device_type_playback) {
  22911. if (!ma_is_capture_device_blacklisted__alsa(NAME)) {
  22912. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  22913. }
  22914. } else {
  22915. if (!ma_is_playback_device_blacklisted__alsa(NAME)) {
  22916. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  22917. }
  22918. }
  22919. }
  22920. }
  22921. if (cbResult == MA_FALSE) {
  22922. stopEnumeration = MA_TRUE;
  22923. }
  22924. next_device:
  22925. free(NAME);
  22926. free(DESC);
  22927. free(IOID);
  22928. ppNextDeviceHint += 1;
  22929. /* We need to stop enumeration if the callback returned false. */
  22930. if (stopEnumeration) {
  22931. break;
  22932. }
  22933. }
  22934. ma_free(pUniqueIDs, &pContext->allocationCallbacks);
  22935. ((ma_snd_device_name_free_hint_proc)pContext->alsa.snd_device_name_free_hint)((void**)ppDeviceHints);
  22936. ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock);
  22937. return MA_SUCCESS;
  22938. }
  22939. typedef struct
  22940. {
  22941. ma_device_type deviceType;
  22942. const ma_device_id* pDeviceID;
  22943. ma_share_mode shareMode;
  22944. ma_device_info* pDeviceInfo;
  22945. ma_bool32 foundDevice;
  22946. } ma_context_get_device_info_enum_callback_data__alsa;
  22947. static ma_bool32 ma_context_get_device_info_enum_callback__alsa(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pDeviceInfo, void* pUserData)
  22948. {
  22949. ma_context_get_device_info_enum_callback_data__alsa* pData = (ma_context_get_device_info_enum_callback_data__alsa*)pUserData;
  22950. MA_ASSERT(pData != NULL);
  22951. (void)pContext;
  22952. if (pData->pDeviceID == NULL && ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) {
  22953. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1);
  22954. pData->foundDevice = MA_TRUE;
  22955. } else {
  22956. if (pData->deviceType == deviceType && (pData->pDeviceID != NULL && ma_strcmp(pData->pDeviceID->alsa, pDeviceInfo->id.alsa) == 0)) {
  22957. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1);
  22958. pData->foundDevice = MA_TRUE;
  22959. }
  22960. }
  22961. /* Keep enumerating until we have found the device. */
  22962. return !pData->foundDevice;
  22963. }
  22964. static void ma_context_test_rate_and_add_native_data_format__alsa(ma_context* pContext, ma_snd_pcm_t* pPCM, ma_snd_pcm_hw_params_t* pHWParams, ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 flags, ma_device_info* pDeviceInfo)
  22965. {
  22966. MA_ASSERT(pPCM != NULL);
  22967. MA_ASSERT(pHWParams != NULL);
  22968. MA_ASSERT(pDeviceInfo != NULL);
  22969. if (pDeviceInfo->nativeDataFormatCount < ma_countof(pDeviceInfo->nativeDataFormats) && ((ma_snd_pcm_hw_params_test_rate_proc)pContext->alsa.snd_pcm_hw_params_test_rate)(pPCM, pHWParams, sampleRate, 0) == 0) {
  22970. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  22971. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  22972. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  22973. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags;
  22974. pDeviceInfo->nativeDataFormatCount += 1;
  22975. }
  22976. }
  22977. static void ma_context_iterate_rates_and_add_native_data_format__alsa(ma_context* pContext, ma_snd_pcm_t* pPCM, ma_snd_pcm_hw_params_t* pHWParams, ma_format format, ma_uint32 channels, ma_uint32 flags, ma_device_info* pDeviceInfo)
  22978. {
  22979. ma_uint32 iSampleRate;
  22980. unsigned int minSampleRate;
  22981. unsigned int maxSampleRate;
  22982. int sampleRateDir; /* Not used. Just passed into snd_pcm_hw_params_get_rate_min/max(). */
  22983. /* There could be a range. */
  22984. ((ma_snd_pcm_hw_params_get_rate_min_proc)pContext->alsa.snd_pcm_hw_params_get_rate_min)(pHWParams, &minSampleRate, &sampleRateDir);
  22985. ((ma_snd_pcm_hw_params_get_rate_max_proc)pContext->alsa.snd_pcm_hw_params_get_rate_max)(pHWParams, &maxSampleRate, &sampleRateDir);
  22986. /* Make sure our sample rates are clamped to sane values. Stupid devices like "pulse" will reports rates like "1" which is ridiculus. */
  22987. minSampleRate = ma_clamp(minSampleRate, (unsigned int)ma_standard_sample_rate_min, (unsigned int)ma_standard_sample_rate_max);
  22988. maxSampleRate = ma_clamp(maxSampleRate, (unsigned int)ma_standard_sample_rate_min, (unsigned int)ma_standard_sample_rate_max);
  22989. for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); iSampleRate += 1) {
  22990. ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iSampleRate];
  22991. if (standardSampleRate >= minSampleRate && standardSampleRate <= maxSampleRate) {
  22992. ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, standardSampleRate, flags, pDeviceInfo);
  22993. }
  22994. }
  22995. /* Now make sure our min and max rates are included just in case they aren't in the range of our standard rates. */
  22996. if (!ma_is_standard_sample_rate(minSampleRate)) {
  22997. ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, minSampleRate, flags, pDeviceInfo);
  22998. }
  22999. if (!ma_is_standard_sample_rate(maxSampleRate) && maxSampleRate != minSampleRate) {
  23000. ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, maxSampleRate, flags, pDeviceInfo);
  23001. }
  23002. }
  23003. static ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  23004. {
  23005. ma_context_get_device_info_enum_callback_data__alsa data;
  23006. ma_result result;
  23007. int resultALSA;
  23008. ma_snd_pcm_t* pPCM;
  23009. ma_snd_pcm_hw_params_t* pHWParams;
  23010. ma_uint32 iFormat;
  23011. ma_uint32 iChannel;
  23012. MA_ASSERT(pContext != NULL);
  23013. /* We just enumerate to find basic information about the device. */
  23014. data.deviceType = deviceType;
  23015. data.pDeviceID = pDeviceID;
  23016. data.pDeviceInfo = pDeviceInfo;
  23017. data.foundDevice = MA_FALSE;
  23018. result = ma_context_enumerate_devices__alsa(pContext, ma_context_get_device_info_enum_callback__alsa, &data);
  23019. if (result != MA_SUCCESS) {
  23020. return result;
  23021. }
  23022. if (!data.foundDevice) {
  23023. return MA_NO_DEVICE;
  23024. }
  23025. if (ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) {
  23026. pDeviceInfo->isDefault = MA_TRUE;
  23027. }
  23028. /* For detailed info we need to open the device. */
  23029. result = ma_context_open_pcm__alsa(pContext, ma_share_mode_shared, deviceType, pDeviceID, 0, &pPCM);
  23030. if (result != MA_SUCCESS) {
  23031. return result;
  23032. }
  23033. /* We need to initialize a HW parameters object in order to know what formats are supported. */
  23034. pHWParams = (ma_snd_pcm_hw_params_t*)ma_calloc(((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)(), &pContext->allocationCallbacks);
  23035. if (pHWParams == NULL) {
  23036. ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
  23037. return MA_OUT_OF_MEMORY;
  23038. }
  23039. resultALSA = ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  23040. if (resultALSA < 0) {
  23041. ma_free(pHWParams, &pContext->allocationCallbacks);
  23042. ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
  23043. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.");
  23044. return ma_result_from_errno(-resultALSA);
  23045. }
  23046. /*
  23047. Some ALSA devices can support many permutations of formats, channels and rates. We only support
  23048. a fixed number of permutations which means we need to employ some strategies to ensure the best
  23049. combinations are returned. An example is the "pulse" device which can do it's own data conversion
  23050. in software and as a result can support any combination of format, channels and rate.
  23051. We want to ensure the the first data formats are the best. We have a list of favored sample
  23052. formats and sample rates, so these will be the basis of our iteration.
  23053. */
  23054. /* Formats. We just iterate over our standard formats and test them, making sure we reset the configuration space each iteration. */
  23055. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); iFormat += 1) {
  23056. ma_format format = g_maFormatPriorities[iFormat];
  23057. /*
  23058. For each format we need to make sure we reset the configuration space so we don't return
  23059. channel counts and rates that aren't compatible with a format.
  23060. */
  23061. ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  23062. /* Test the format first. If this fails it means the format is not supported and we can skip it. */
  23063. if (((ma_snd_pcm_hw_params_test_format_proc)pContext->alsa.snd_pcm_hw_params_test_format)(pPCM, pHWParams, ma_convert_ma_format_to_alsa_format(format)) == 0) {
  23064. /* The format is supported. */
  23065. unsigned int minChannels;
  23066. unsigned int maxChannels;
  23067. /*
  23068. The configuration space needs to be restricted to this format so we can get an accurate
  23069. picture of which sample rates and channel counts are support with this format.
  23070. */
  23071. ((ma_snd_pcm_hw_params_set_format_proc)pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, ma_convert_ma_format_to_alsa_format(format));
  23072. /* Now we need to check for supported channels. */
  23073. ((ma_snd_pcm_hw_params_get_channels_min_proc)pContext->alsa.snd_pcm_hw_params_get_channels_min)(pHWParams, &minChannels);
  23074. ((ma_snd_pcm_hw_params_get_channels_max_proc)pContext->alsa.snd_pcm_hw_params_get_channels_max)(pHWParams, &maxChannels);
  23075. if (minChannels > MA_MAX_CHANNELS) {
  23076. continue; /* Too many channels. */
  23077. }
  23078. if (maxChannels < MA_MIN_CHANNELS) {
  23079. continue; /* Not enough channels. */
  23080. }
  23081. /*
  23082. Make sure the channel count is clamped. This is mainly intended for the max channels
  23083. because some devices can report an unbound maximum.
  23084. */
  23085. minChannels = ma_clamp(minChannels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  23086. maxChannels = ma_clamp(maxChannels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  23087. if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) {
  23088. /* The device supports all channels. Don't iterate over every single one. Instead just set the channels to 0 which means all channels are supported. */
  23089. ma_context_iterate_rates_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, 0, 0, pDeviceInfo); /* Intentionally setting the channel count to 0 as that means all channels are supported. */
  23090. } else {
  23091. /* The device only supports a specific set of channels. We need to iterate over all of them. */
  23092. for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) {
  23093. /* Test the channel before applying it to the configuration space. */
  23094. unsigned int channels = iChannel;
  23095. /* Make sure our channel range is reset before testing again or else we'll always fail the test. */
  23096. ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  23097. ((ma_snd_pcm_hw_params_set_format_proc)pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, ma_convert_ma_format_to_alsa_format(format));
  23098. if (((ma_snd_pcm_hw_params_test_channels_proc)pContext->alsa.snd_pcm_hw_params_test_channels)(pPCM, pHWParams, channels) == 0) {
  23099. /* The channel count is supported. */
  23100. /* The configuration space now needs to be restricted to the channel count before extracting the sample rate. */
  23101. ((ma_snd_pcm_hw_params_set_channels_proc)pContext->alsa.snd_pcm_hw_params_set_channels)(pPCM, pHWParams, channels);
  23102. /* Only after the configuration space has been restricted to the specific channel count should we iterate over our sample rates. */
  23103. ma_context_iterate_rates_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, 0, pDeviceInfo);
  23104. } else {
  23105. /* The channel count is not supported. Skip. */
  23106. }
  23107. }
  23108. }
  23109. } else {
  23110. /* The format is not supported. Skip. */
  23111. }
  23112. }
  23113. ma_free(pHWParams, &pContext->allocationCallbacks);
  23114. ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
  23115. return MA_SUCCESS;
  23116. }
  23117. static ma_result ma_device_uninit__alsa(ma_device* pDevice)
  23118. {
  23119. MA_ASSERT(pDevice != NULL);
  23120. if ((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) {
  23121. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  23122. close(pDevice->alsa.wakeupfdCapture);
  23123. ma_free(pDevice->alsa.pPollDescriptorsCapture, &pDevice->pContext->allocationCallbacks);
  23124. }
  23125. if ((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) {
  23126. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
  23127. close(pDevice->alsa.wakeupfdPlayback);
  23128. ma_free(pDevice->alsa.pPollDescriptorsPlayback, &pDevice->pContext->allocationCallbacks);
  23129. }
  23130. return MA_SUCCESS;
  23131. }
  23132. static ma_result ma_device_init_by_type__alsa(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  23133. {
  23134. ma_result result;
  23135. int resultALSA;
  23136. ma_snd_pcm_t* pPCM;
  23137. ma_bool32 isUsingMMap;
  23138. ma_snd_pcm_format_t formatALSA;
  23139. ma_format internalFormat;
  23140. ma_uint32 internalChannels;
  23141. ma_uint32 internalSampleRate;
  23142. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  23143. ma_uint32 internalPeriodSizeInFrames;
  23144. ma_uint32 internalPeriods;
  23145. int openMode;
  23146. ma_snd_pcm_hw_params_t* pHWParams;
  23147. ma_snd_pcm_sw_params_t* pSWParams;
  23148. ma_snd_pcm_uframes_t bufferBoundary;
  23149. int pollDescriptorCount;
  23150. struct pollfd* pPollDescriptors;
  23151. int wakeupfd;
  23152. MA_ASSERT(pConfig != NULL);
  23153. MA_ASSERT(deviceType != ma_device_type_duplex); /* This function should only be called for playback _or_ capture, never duplex. */
  23154. MA_ASSERT(pDevice != NULL);
  23155. formatALSA = ma_convert_ma_format_to_alsa_format(pDescriptor->format);
  23156. openMode = 0;
  23157. if (pConfig->alsa.noAutoResample) {
  23158. openMode |= MA_SND_PCM_NO_AUTO_RESAMPLE;
  23159. }
  23160. if (pConfig->alsa.noAutoChannels) {
  23161. openMode |= MA_SND_PCM_NO_AUTO_CHANNELS;
  23162. }
  23163. if (pConfig->alsa.noAutoFormat) {
  23164. openMode |= MA_SND_PCM_NO_AUTO_FORMAT;
  23165. }
  23166. result = ma_context_open_pcm__alsa(pDevice->pContext, pDescriptor->shareMode, deviceType, pDescriptor->pDeviceID, openMode, &pPCM);
  23167. if (result != MA_SUCCESS) {
  23168. return result;
  23169. }
  23170. /* Hardware parameters. */
  23171. pHWParams = (ma_snd_pcm_hw_params_t*)ma_calloc(((ma_snd_pcm_hw_params_sizeof_proc)pDevice->pContext->alsa.snd_pcm_hw_params_sizeof)(), &pDevice->pContext->allocationCallbacks);
  23172. if (pHWParams == NULL) {
  23173. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23174. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for hardware parameters.");
  23175. return MA_OUT_OF_MEMORY;
  23176. }
  23177. resultALSA = ((ma_snd_pcm_hw_params_any_proc)pDevice->pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  23178. if (resultALSA < 0) {
  23179. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23180. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23181. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.");
  23182. return ma_result_from_errno(-resultALSA);
  23183. }
  23184. /* MMAP Mode. Try using interleaved MMAP access. If this fails, fall back to standard readi/writei. */
  23185. isUsingMMap = MA_FALSE;
  23186. #if 0 /* NOTE: MMAP mode temporarily disabled. */
  23187. if (deviceType != ma_device_type_capture) { /* <-- Disabling MMAP mode for capture devices because I apparently do not have a device that supports it which means I can't test it... Contributions welcome. */
  23188. if (!pConfig->alsa.noMMap) {
  23189. if (((ma_snd_pcm_hw_params_set_access_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_access)(pPCM, pHWParams, MA_SND_PCM_ACCESS_MMAP_INTERLEAVED) == 0) {
  23190. pDevice->alsa.isUsingMMap = MA_TRUE;
  23191. }
  23192. }
  23193. }
  23194. #endif
  23195. if (!isUsingMMap) {
  23196. resultALSA = ((ma_snd_pcm_hw_params_set_access_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_access)(pPCM, pHWParams, MA_SND_PCM_ACCESS_RW_INTERLEAVED);
  23197. if (resultALSA < 0) {
  23198. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23199. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23200. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set access mode to neither SND_PCM_ACCESS_MMAP_INTERLEAVED nor SND_PCM_ACCESS_RW_INTERLEAVED. snd_pcm_hw_params_set_access() failed.");
  23201. return ma_result_from_errno(-resultALSA);
  23202. }
  23203. }
  23204. /*
  23205. Most important properties first. The documentation for OSS (yes, I know this is ALSA!) recommends format, channels, then sample rate. I can't
  23206. find any documentation for ALSA specifically, so I'm going to copy the recommendation for OSS.
  23207. */
  23208. /* Format. */
  23209. {
  23210. /*
  23211. At this point we should have a list of supported formats, so now we need to find the best one. We first check if the requested format is
  23212. supported, and if so, use that one. If it's not supported, we just run though a list of formats and try to find the best one.
  23213. */
  23214. if (formatALSA == MA_SND_PCM_FORMAT_UNKNOWN || ((ma_snd_pcm_hw_params_test_format_proc)pDevice->pContext->alsa.snd_pcm_hw_params_test_format)(pPCM, pHWParams, formatALSA) != 0) {
  23215. /* We're either requesting the native format or the specified format is not supported. */
  23216. size_t iFormat;
  23217. formatALSA = MA_SND_PCM_FORMAT_UNKNOWN;
  23218. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); ++iFormat) {
  23219. if (((ma_snd_pcm_hw_params_test_format_proc)pDevice->pContext->alsa.snd_pcm_hw_params_test_format)(pPCM, pHWParams, ma_convert_ma_format_to_alsa_format(g_maFormatPriorities[iFormat])) == 0) {
  23220. formatALSA = ma_convert_ma_format_to_alsa_format(g_maFormatPriorities[iFormat]);
  23221. break;
  23222. }
  23223. }
  23224. if (formatALSA == MA_SND_PCM_FORMAT_UNKNOWN) {
  23225. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23226. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23227. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. The device does not support any miniaudio formats.");
  23228. return MA_FORMAT_NOT_SUPPORTED;
  23229. }
  23230. }
  23231. resultALSA = ((ma_snd_pcm_hw_params_set_format_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, formatALSA);
  23232. if (resultALSA < 0) {
  23233. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23234. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23235. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. snd_pcm_hw_params_set_format() failed.");
  23236. return ma_result_from_errno(-resultALSA);
  23237. }
  23238. internalFormat = ma_format_from_alsa(formatALSA);
  23239. if (internalFormat == ma_format_unknown) {
  23240. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23241. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23242. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] The chosen format is not supported by miniaudio.");
  23243. return MA_FORMAT_NOT_SUPPORTED;
  23244. }
  23245. }
  23246. /* Channels. */
  23247. {
  23248. unsigned int channels = pDescriptor->channels;
  23249. if (channels == 0) {
  23250. channels = MA_DEFAULT_CHANNELS;
  23251. }
  23252. resultALSA = ((ma_snd_pcm_hw_params_set_channels_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_channels_near)(pPCM, pHWParams, &channels);
  23253. if (resultALSA < 0) {
  23254. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23255. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23256. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set channel count. snd_pcm_hw_params_set_channels_near() failed.");
  23257. return ma_result_from_errno(-resultALSA);
  23258. }
  23259. internalChannels = (ma_uint32)channels;
  23260. }
  23261. /* Sample Rate */
  23262. {
  23263. unsigned int sampleRate;
  23264. /*
  23265. It appears there's either a bug in ALSA, a bug in some drivers, or I'm doing something silly; but having resampling enabled causes
  23266. problems with some device configurations when used in conjunction with MMAP access mode. To fix this problem we need to disable
  23267. resampling.
  23268. To reproduce this problem, open the "plug:dmix" device, and set the sample rate to 44100. Internally, it looks like dmix uses a
  23269. sample rate of 48000. The hardware parameters will get set correctly with no errors, but it looks like the 44100 -> 48000 resampling
  23270. doesn't work properly - but only with MMAP access mode. You will notice skipping/crackling in the audio, and it'll run at a slightly
  23271. faster rate.
  23272. miniaudio has built-in support for sample rate conversion (albeit low quality at the moment), so disabling resampling should be fine
  23273. for us. The only problem is that it won't be taking advantage of any kind of hardware-accelerated resampling and it won't be very
  23274. good quality until I get a chance to improve the quality of miniaudio's software sample rate conversion.
  23275. I don't currently know if the dmix plugin is the only one with this error. Indeed, this is the only one I've been able to reproduce
  23276. this error with. In the future, we may want to restrict the disabling of resampling to only known bad plugins.
  23277. */
  23278. ((ma_snd_pcm_hw_params_set_rate_resample_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_rate_resample)(pPCM, pHWParams, 0);
  23279. sampleRate = pDescriptor->sampleRate;
  23280. if (sampleRate == 0) {
  23281. sampleRate = MA_DEFAULT_SAMPLE_RATE;
  23282. }
  23283. resultALSA = ((ma_snd_pcm_hw_params_set_rate_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_rate_near)(pPCM, pHWParams, &sampleRate, 0);
  23284. if (resultALSA < 0) {
  23285. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23286. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23287. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Sample rate not supported. snd_pcm_hw_params_set_rate_near() failed.");
  23288. return ma_result_from_errno(-resultALSA);
  23289. }
  23290. internalSampleRate = (ma_uint32)sampleRate;
  23291. }
  23292. /* Periods. */
  23293. {
  23294. ma_uint32 periods = pDescriptor->periodCount;
  23295. resultALSA = ((ma_snd_pcm_hw_params_set_periods_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_periods_near)(pPCM, pHWParams, &periods, NULL);
  23296. if (resultALSA < 0) {
  23297. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23298. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23299. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set period count. snd_pcm_hw_params_set_periods_near() failed.");
  23300. return ma_result_from_errno(-resultALSA);
  23301. }
  23302. internalPeriods = periods;
  23303. }
  23304. /* Buffer Size */
  23305. {
  23306. ma_snd_pcm_uframes_t actualBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile) * internalPeriods;
  23307. resultALSA = ((ma_snd_pcm_hw_params_set_buffer_size_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_buffer_size_near)(pPCM, pHWParams, &actualBufferSizeInFrames);
  23308. if (resultALSA < 0) {
  23309. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23310. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23311. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set buffer size for device. snd_pcm_hw_params_set_buffer_size() failed.");
  23312. return ma_result_from_errno(-resultALSA);
  23313. }
  23314. internalPeriodSizeInFrames = actualBufferSizeInFrames / internalPeriods;
  23315. }
  23316. /* Apply hardware parameters. */
  23317. resultALSA = ((ma_snd_pcm_hw_params_proc)pDevice->pContext->alsa.snd_pcm_hw_params)(pPCM, pHWParams);
  23318. if (resultALSA < 0) {
  23319. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23320. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23321. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set hardware parameters. snd_pcm_hw_params() failed.");
  23322. return ma_result_from_errno(-resultALSA);
  23323. }
  23324. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23325. pHWParams = NULL;
  23326. /* Software parameters. */
  23327. pSWParams = (ma_snd_pcm_sw_params_t*)ma_calloc(((ma_snd_pcm_sw_params_sizeof_proc)pDevice->pContext->alsa.snd_pcm_sw_params_sizeof)(), &pDevice->pContext->allocationCallbacks);
  23328. if (pSWParams == NULL) {
  23329. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23330. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for software parameters.");
  23331. return MA_OUT_OF_MEMORY;
  23332. }
  23333. resultALSA = ((ma_snd_pcm_sw_params_current_proc)pDevice->pContext->alsa.snd_pcm_sw_params_current)(pPCM, pSWParams);
  23334. if (resultALSA < 0) {
  23335. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23336. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23337. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize software parameters. snd_pcm_sw_params_current() failed.");
  23338. return ma_result_from_errno(-resultALSA);
  23339. }
  23340. resultALSA = ((ma_snd_pcm_sw_params_set_avail_min_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_avail_min)(pPCM, pSWParams, ma_prev_power_of_2(internalPeriodSizeInFrames));
  23341. if (resultALSA < 0) {
  23342. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23343. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23344. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed.");
  23345. return ma_result_from_errno(-resultALSA);
  23346. }
  23347. resultALSA = ((ma_snd_pcm_sw_params_get_boundary_proc)pDevice->pContext->alsa.snd_pcm_sw_params_get_boundary)(pSWParams, &bufferBoundary);
  23348. if (resultALSA < 0) {
  23349. bufferBoundary = internalPeriodSizeInFrames * internalPeriods;
  23350. }
  23351. if (deviceType == ma_device_type_playback && !isUsingMMap) { /* Only playback devices in writei/readi mode need a start threshold. */
  23352. /*
  23353. Subtle detail here with the start threshold. When in playback-only mode (no full-duplex) we can set the start threshold to
  23354. the size of a period. But for full-duplex we need to set it such that it is at least two periods.
  23355. */
  23356. resultALSA = ((ma_snd_pcm_sw_params_set_start_threshold_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_start_threshold)(pPCM, pSWParams, internalPeriodSizeInFrames*2);
  23357. if (resultALSA < 0) {
  23358. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23359. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23360. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set start threshold for playback device. snd_pcm_sw_params_set_start_threshold() failed.");
  23361. return ma_result_from_errno(-resultALSA);
  23362. }
  23363. resultALSA = ((ma_snd_pcm_sw_params_set_stop_threshold_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_stop_threshold)(pPCM, pSWParams, bufferBoundary);
  23364. if (resultALSA < 0) { /* Set to boundary to loop instead of stop in the event of an xrun. */
  23365. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23366. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23367. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set stop threshold for playback device. snd_pcm_sw_params_set_stop_threshold() failed.");
  23368. return ma_result_from_errno(-resultALSA);
  23369. }
  23370. }
  23371. resultALSA = ((ma_snd_pcm_sw_params_proc)pDevice->pContext->alsa.snd_pcm_sw_params)(pPCM, pSWParams);
  23372. if (resultALSA < 0) {
  23373. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23374. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23375. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set software parameters. snd_pcm_sw_params() failed.");
  23376. return ma_result_from_errno(-resultALSA);
  23377. }
  23378. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23379. pSWParams = NULL;
  23380. /* Grab the internal channel map. For now we're not going to bother trying to change the channel map and instead just do it ourselves. */
  23381. {
  23382. ma_snd_pcm_chmap_t* pChmap = NULL;
  23383. if (pDevice->pContext->alsa.snd_pcm_get_chmap != NULL) {
  23384. pChmap = ((ma_snd_pcm_get_chmap_proc)pDevice->pContext->alsa.snd_pcm_get_chmap)(pPCM);
  23385. }
  23386. if (pChmap != NULL) {
  23387. ma_uint32 iChannel;
  23388. /* There are cases where the returned channel map can have a different channel count than was returned by snd_pcm_hw_params_set_channels_near(). */
  23389. if (pChmap->channels >= internalChannels) {
  23390. /* Drop excess channels. */
  23391. for (iChannel = 0; iChannel < internalChannels; ++iChannel) {
  23392. internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]);
  23393. }
  23394. } else {
  23395. ma_uint32 i;
  23396. /*
  23397. Excess channels use defaults. Do an initial fill with defaults, overwrite the first pChmap->channels, validate to ensure there are no duplicate
  23398. channels. If validation fails, fall back to defaults.
  23399. */
  23400. ma_bool32 isValid = MA_TRUE;
  23401. /* Fill with defaults. */
  23402. ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels);
  23403. /* Overwrite first pChmap->channels channels. */
  23404. for (iChannel = 0; iChannel < pChmap->channels; ++iChannel) {
  23405. internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]);
  23406. }
  23407. /* Validate. */
  23408. for (i = 0; i < internalChannels && isValid; ++i) {
  23409. ma_uint32 j;
  23410. for (j = i+1; j < internalChannels; ++j) {
  23411. if (internalChannelMap[i] == internalChannelMap[j]) {
  23412. isValid = MA_FALSE;
  23413. break;
  23414. }
  23415. }
  23416. }
  23417. /* If our channel map is invalid, fall back to defaults. */
  23418. if (!isValid) {
  23419. ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels);
  23420. }
  23421. }
  23422. free(pChmap);
  23423. pChmap = NULL;
  23424. } else {
  23425. /* Could not retrieve the channel map. Fall back to a hard-coded assumption. */
  23426. ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels);
  23427. }
  23428. }
  23429. /*
  23430. We need to retrieve the poll descriptors so we can use poll() to wait for data to become
  23431. available for reading or writing. There's no well defined maximum for this so we're just going
  23432. to allocate this on the heap.
  23433. */
  23434. pollDescriptorCount = ((ma_snd_pcm_poll_descriptors_count_proc)pDevice->pContext->alsa.snd_pcm_poll_descriptors_count)(pPCM);
  23435. if (pollDescriptorCount <= 0) {
  23436. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23437. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to retrieve poll descriptors count.");
  23438. return MA_ERROR;
  23439. }
  23440. pPollDescriptors = (struct pollfd*)ma_malloc(sizeof(*pPollDescriptors) * (pollDescriptorCount + 1), &pDevice->pContext->allocationCallbacks); /* +1 because we want room for the wakeup descriptor. */
  23441. if (pPollDescriptors == NULL) {
  23442. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23443. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for poll descriptors.");
  23444. return MA_OUT_OF_MEMORY;
  23445. }
  23446. /*
  23447. We need an eventfd to wakeup from poll() and avoid a deadlock in situations where the driver
  23448. never returns from writei() and readi(). This has been observed with the "pulse" device.
  23449. */
  23450. wakeupfd = eventfd(0, 0);
  23451. if (wakeupfd < 0) {
  23452. ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks);
  23453. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23454. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to create eventfd for poll wakeup.");
  23455. return ma_result_from_errno(errno);
  23456. }
  23457. /* We'll place the wakeup fd at the start of the buffer. */
  23458. pPollDescriptors[0].fd = wakeupfd;
  23459. pPollDescriptors[0].events = POLLIN; /* We only care about waiting to read from the wakeup file descriptor. */
  23460. pPollDescriptors[0].revents = 0;
  23461. /* We can now extract the PCM poll descriptors which we place after the wakeup descriptor. */
  23462. pollDescriptorCount = ((ma_snd_pcm_poll_descriptors_proc)pDevice->pContext->alsa.snd_pcm_poll_descriptors)(pPCM, pPollDescriptors + 1, pollDescriptorCount); /* +1 because we want to place these descriptors after the wakeup descriptor. */
  23463. if (pollDescriptorCount <= 0) {
  23464. close(wakeupfd);
  23465. ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks);
  23466. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23467. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to retrieve poll descriptors.");
  23468. return MA_ERROR;
  23469. }
  23470. if (deviceType == ma_device_type_capture) {
  23471. pDevice->alsa.pollDescriptorCountCapture = pollDescriptorCount;
  23472. pDevice->alsa.pPollDescriptorsCapture = pPollDescriptors;
  23473. pDevice->alsa.wakeupfdCapture = wakeupfd;
  23474. } else {
  23475. pDevice->alsa.pollDescriptorCountPlayback = pollDescriptorCount;
  23476. pDevice->alsa.pPollDescriptorsPlayback = pPollDescriptors;
  23477. pDevice->alsa.wakeupfdPlayback = wakeupfd;
  23478. }
  23479. /* We're done. Prepare the device. */
  23480. resultALSA = ((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)(pPCM);
  23481. if (resultALSA < 0) {
  23482. close(wakeupfd);
  23483. ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks);
  23484. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23485. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to prepare device.");
  23486. return ma_result_from_errno(-resultALSA);
  23487. }
  23488. if (deviceType == ma_device_type_capture) {
  23489. pDevice->alsa.pPCMCapture = (ma_ptr)pPCM;
  23490. pDevice->alsa.isUsingMMapCapture = isUsingMMap;
  23491. } else {
  23492. pDevice->alsa.pPCMPlayback = (ma_ptr)pPCM;
  23493. pDevice->alsa.isUsingMMapPlayback = isUsingMMap;
  23494. }
  23495. pDescriptor->format = internalFormat;
  23496. pDescriptor->channels = internalChannels;
  23497. pDescriptor->sampleRate = internalSampleRate;
  23498. ma_channel_map_copy(pDescriptor->channelMap, internalChannelMap, ma_min(internalChannels, MA_MAX_CHANNELS));
  23499. pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames;
  23500. pDescriptor->periodCount = internalPeriods;
  23501. return MA_SUCCESS;
  23502. }
  23503. static ma_result ma_device_init__alsa(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  23504. {
  23505. MA_ASSERT(pDevice != NULL);
  23506. MA_ZERO_OBJECT(&pDevice->alsa);
  23507. if (pConfig->deviceType == ma_device_type_loopback) {
  23508. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  23509. }
  23510. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  23511. ma_result result = ma_device_init_by_type__alsa(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  23512. if (result != MA_SUCCESS) {
  23513. return result;
  23514. }
  23515. }
  23516. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  23517. ma_result result = ma_device_init_by_type__alsa(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  23518. if (result != MA_SUCCESS) {
  23519. return result;
  23520. }
  23521. }
  23522. return MA_SUCCESS;
  23523. }
  23524. static ma_result ma_device_start__alsa(ma_device* pDevice)
  23525. {
  23526. int resultALSA;
  23527. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  23528. resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  23529. if (resultALSA < 0) {
  23530. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start capture device.");
  23531. return ma_result_from_errno(-resultALSA);
  23532. }
  23533. }
  23534. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  23535. /* Don't need to do anything for playback because it'll be started automatically when enough data has been written. */
  23536. }
  23537. return MA_SUCCESS;
  23538. }
  23539. static ma_result ma_device_stop__alsa(ma_device* pDevice)
  23540. {
  23541. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  23542. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping capture device...\n");
  23543. ((ma_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  23544. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping capture device successful.\n");
  23545. /* We need to prepare the device again, otherwise we won't be able to restart the device. */
  23546. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device...\n");
  23547. if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) < 0) {
  23548. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device failed.\n");
  23549. } else {
  23550. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device successful.\n");
  23551. }
  23552. }
  23553. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  23554. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping playback device...\n");
  23555. ((ma_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
  23556. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping playback device successful.\n");
  23557. /* We need to prepare the device again, otherwise we won't be able to restart the device. */
  23558. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device...\n");
  23559. if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) < 0) {
  23560. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device failed.\n");
  23561. } else {
  23562. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device successful.\n");
  23563. }
  23564. }
  23565. return MA_SUCCESS;
  23566. }
  23567. static ma_result ma_device_wait__alsa(ma_device* pDevice, ma_snd_pcm_t* pPCM, struct pollfd* pPollDescriptors, int pollDescriptorCount, short requiredEvent)
  23568. {
  23569. for (;;) {
  23570. unsigned short revents;
  23571. int resultALSA;
  23572. int resultPoll = poll(pPollDescriptors, pollDescriptorCount, -1);
  23573. if (resultPoll < 0) {
  23574. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] poll() failed.");
  23575. return ma_result_from_errno(errno);
  23576. }
  23577. /*
  23578. Before checking the ALSA poll descriptor flag we need to check if the wakeup descriptor
  23579. has had it's POLLIN flag set. If so, we need to actually read the data and then exit
  23580. function. The wakeup descriptor will be the first item in the descriptors buffer.
  23581. */
  23582. if ((pPollDescriptors[0].revents & POLLIN) != 0) {
  23583. ma_uint64 t;
  23584. int resultRead = read(pPollDescriptors[0].fd, &t, sizeof(t)); /* <-- Important that we read here so that the next write() does not block. */
  23585. if (resultRead < 0) {
  23586. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] read() failed.");
  23587. return ma_result_from_errno(errno);
  23588. }
  23589. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] POLLIN set for wakeupfd\n");
  23590. return MA_DEVICE_NOT_STARTED;
  23591. }
  23592. /*
  23593. Getting here means that some data should be able to be read. We need to use ALSA to
  23594. translate the revents flags for us.
  23595. */
  23596. resultALSA = ((ma_snd_pcm_poll_descriptors_revents_proc)pDevice->pContext->alsa.snd_pcm_poll_descriptors_revents)(pPCM, pPollDescriptors + 1, pollDescriptorCount - 1, &revents); /* +1, -1 to ignore the wakeup descriptor. */
  23597. if (resultALSA < 0) {
  23598. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_poll_descriptors_revents() failed.");
  23599. return ma_result_from_errno(-resultALSA);
  23600. }
  23601. if ((revents & POLLERR) != 0) {
  23602. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] POLLERR detected.");
  23603. return ma_result_from_errno(errno);
  23604. }
  23605. if ((revents & requiredEvent) == requiredEvent) {
  23606. break; /* We're done. Data available for reading or writing. */
  23607. }
  23608. }
  23609. return MA_SUCCESS;
  23610. }
  23611. static ma_result ma_device_wait_read__alsa(ma_device* pDevice)
  23612. {
  23613. return ma_device_wait__alsa(pDevice, (ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, (struct pollfd*)pDevice->alsa.pPollDescriptorsCapture, pDevice->alsa.pollDescriptorCountCapture + 1, POLLIN); /* +1 to account for the wakeup descriptor. */
  23614. }
  23615. static ma_result ma_device_wait_write__alsa(ma_device* pDevice)
  23616. {
  23617. return ma_device_wait__alsa(pDevice, (ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, (struct pollfd*)pDevice->alsa.pPollDescriptorsPlayback, pDevice->alsa.pollDescriptorCountPlayback + 1, POLLOUT); /* +1 to account for the wakeup descriptor. */
  23618. }
  23619. static ma_result ma_device_read__alsa(ma_device* pDevice, void* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead)
  23620. {
  23621. ma_snd_pcm_sframes_t resultALSA = 0;
  23622. MA_ASSERT(pDevice != NULL);
  23623. MA_ASSERT(pFramesOut != NULL);
  23624. if (pFramesRead != NULL) {
  23625. *pFramesRead = 0;
  23626. }
  23627. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  23628. ma_result result;
  23629. /* The first thing to do is wait for data to become available for reading. This will return an error code if the device has been stopped. */
  23630. result = ma_device_wait_read__alsa(pDevice);
  23631. if (result != MA_SUCCESS) {
  23632. return result;
  23633. }
  23634. /* Getting here means we should have data available. */
  23635. resultALSA = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, pFramesOut, frameCount);
  23636. if (resultALSA >= 0) {
  23637. break; /* Success. */
  23638. } else {
  23639. if (resultALSA == -EAGAIN) {
  23640. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EGAIN (read)\n");*/
  23641. continue; /* Try again. */
  23642. } else if (resultALSA == -EPIPE) {
  23643. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EPIPE (read)\n");
  23644. /* Overrun. Recover and try again. If this fails we need to return an error. */
  23645. resultALSA = ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, resultALSA, MA_TRUE);
  23646. if (resultALSA < 0) {
  23647. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun.");
  23648. return ma_result_from_errno((int)-resultALSA);
  23649. }
  23650. resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  23651. if (resultALSA < 0) {
  23652. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.");
  23653. return ma_result_from_errno((int)-resultALSA);
  23654. }
  23655. continue; /* Try reading again. */
  23656. }
  23657. }
  23658. }
  23659. if (pFramesRead != NULL) {
  23660. *pFramesRead = resultALSA;
  23661. }
  23662. return MA_SUCCESS;
  23663. }
  23664. static ma_result ma_device_write__alsa(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  23665. {
  23666. ma_snd_pcm_sframes_t resultALSA = 0;
  23667. MA_ASSERT(pDevice != NULL);
  23668. MA_ASSERT(pFrames != NULL);
  23669. if (pFramesWritten != NULL) {
  23670. *pFramesWritten = 0;
  23671. }
  23672. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  23673. ma_result result;
  23674. /* The first thing to do is wait for space to become available for writing. This will return an error code if the device has been stopped. */
  23675. result = ma_device_wait_write__alsa(pDevice);
  23676. if (result != MA_SUCCESS) {
  23677. return result;
  23678. }
  23679. resultALSA = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, pFrames, frameCount);
  23680. if (resultALSA >= 0) {
  23681. break; /* Success. */
  23682. } else {
  23683. if (resultALSA == -EAGAIN) {
  23684. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EGAIN (write)\n");*/
  23685. continue; /* Try again. */
  23686. } else if (resultALSA == -EPIPE) {
  23687. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EPIPE (write)\n");
  23688. /* Underrun. Recover and try again. If this fails we need to return an error. */
  23689. resultALSA = ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, resultALSA, MA_TRUE); /* MA_TRUE=silent (don't print anything on error). */
  23690. if (resultALSA < 0) {
  23691. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun.");
  23692. return ma_result_from_errno((int)-resultALSA);
  23693. }
  23694. /*
  23695. In my testing I have had a situation where writei() does not automatically restart the device even though I've set it
  23696. up as such in the software parameters. What will happen is writei() will block indefinitely even though the number of
  23697. frames is well beyond the auto-start threshold. To work around this I've needed to add an explicit start here. Not sure
  23698. if this is me just being stupid and not recovering the device properly, but this definitely feels like something isn't
  23699. quite right here.
  23700. */
  23701. resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
  23702. if (resultALSA < 0) {
  23703. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.");
  23704. return ma_result_from_errno((int)-resultALSA);
  23705. }
  23706. continue; /* Try writing again. */
  23707. }
  23708. }
  23709. }
  23710. if (pFramesWritten != NULL) {
  23711. *pFramesWritten = resultALSA;
  23712. }
  23713. return MA_SUCCESS;
  23714. }
  23715. static ma_result ma_device_data_loop_wakeup__alsa(ma_device* pDevice)
  23716. {
  23717. ma_uint64 t = 1;
  23718. int resultWrite = 0;
  23719. MA_ASSERT(pDevice != NULL);
  23720. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Waking up...\n");
  23721. /* Write to an eventfd to trigger a wakeup from poll() and abort any reading or writing. */
  23722. if (pDevice->alsa.pPollDescriptorsCapture != NULL) {
  23723. resultWrite = write(pDevice->alsa.wakeupfdCapture, &t, sizeof(t));
  23724. }
  23725. if (pDevice->alsa.pPollDescriptorsPlayback != NULL) {
  23726. resultWrite = write(pDevice->alsa.wakeupfdPlayback, &t, sizeof(t));
  23727. }
  23728. if (resultWrite < 0) {
  23729. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] write() failed.\n");
  23730. return ma_result_from_errno(errno);
  23731. }
  23732. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Waking up completed successfully.\n");
  23733. return MA_SUCCESS;
  23734. }
  23735. static ma_result ma_context_uninit__alsa(ma_context* pContext)
  23736. {
  23737. MA_ASSERT(pContext != NULL);
  23738. MA_ASSERT(pContext->backend == ma_backend_alsa);
  23739. /* Clean up memory for memory leak checkers. */
  23740. ((ma_snd_config_update_free_global_proc)pContext->alsa.snd_config_update_free_global)();
  23741. #ifndef MA_NO_RUNTIME_LINKING
  23742. ma_dlclose(pContext, pContext->alsa.asoundSO);
  23743. #endif
  23744. ma_mutex_uninit(&pContext->alsa.internalDeviceEnumLock);
  23745. return MA_SUCCESS;
  23746. }
  23747. static ma_result ma_context_init__alsa(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  23748. {
  23749. ma_result result;
  23750. #ifndef MA_NO_RUNTIME_LINKING
  23751. const char* libasoundNames[] = {
  23752. "libasound.so.2",
  23753. "libasound.so"
  23754. };
  23755. size_t i;
  23756. for (i = 0; i < ma_countof(libasoundNames); ++i) {
  23757. pContext->alsa.asoundSO = ma_dlopen(pContext, libasoundNames[i]);
  23758. if (pContext->alsa.asoundSO != NULL) {
  23759. break;
  23760. }
  23761. }
  23762. if (pContext->alsa.asoundSO == NULL) {
  23763. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[ALSA] Failed to open shared object.\n");
  23764. return MA_NO_BACKEND;
  23765. }
  23766. pContext->alsa.snd_pcm_open = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_open");
  23767. pContext->alsa.snd_pcm_close = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_close");
  23768. pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_sizeof");
  23769. pContext->alsa.snd_pcm_hw_params_any = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_any");
  23770. pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format");
  23771. pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format_first");
  23772. pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format_mask");
  23773. pContext->alsa.snd_pcm_hw_params_set_channels = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels");
  23774. pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_near");
  23775. pContext->alsa.snd_pcm_hw_params_set_channels_minmax = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_minmax");
  23776. pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_resample");
  23777. pContext->alsa.snd_pcm_hw_params_set_rate = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate");
  23778. pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_near");
  23779. pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_buffer_size_near");
  23780. pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_periods_near");
  23781. pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_access");
  23782. pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format");
  23783. pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels");
  23784. pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_min");
  23785. pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_max");
  23786. pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate");
  23787. pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_min");
  23788. pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_max");
  23789. pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_buffer_size");
  23790. pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_periods");
  23791. pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_access");
  23792. pContext->alsa.snd_pcm_hw_params_test_format = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_test_format");
  23793. pContext->alsa.snd_pcm_hw_params_test_channels = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_test_channels");
  23794. pContext->alsa.snd_pcm_hw_params_test_rate = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_test_rate");
  23795. pContext->alsa.snd_pcm_hw_params = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params");
  23796. pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_sizeof");
  23797. pContext->alsa.snd_pcm_sw_params_current = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_current");
  23798. pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_get_boundary");
  23799. pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_set_avail_min");
  23800. pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_set_start_threshold");
  23801. pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_set_stop_threshold");
  23802. pContext->alsa.snd_pcm_sw_params = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params");
  23803. pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_format_mask_sizeof");
  23804. pContext->alsa.snd_pcm_format_mask_test = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_format_mask_test");
  23805. pContext->alsa.snd_pcm_get_chmap = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_get_chmap");
  23806. pContext->alsa.snd_pcm_state = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_state");
  23807. pContext->alsa.snd_pcm_prepare = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_prepare");
  23808. pContext->alsa.snd_pcm_start = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_start");
  23809. pContext->alsa.snd_pcm_drop = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_drop");
  23810. pContext->alsa.snd_pcm_drain = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_drain");
  23811. pContext->alsa.snd_pcm_reset = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_reset");
  23812. pContext->alsa.snd_device_name_hint = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_device_name_hint");
  23813. pContext->alsa.snd_device_name_get_hint = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_device_name_get_hint");
  23814. pContext->alsa.snd_card_get_index = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_card_get_index");
  23815. pContext->alsa.snd_device_name_free_hint = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_device_name_free_hint");
  23816. pContext->alsa.snd_pcm_mmap_begin = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_mmap_begin");
  23817. pContext->alsa.snd_pcm_mmap_commit = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_mmap_commit");
  23818. pContext->alsa.snd_pcm_recover = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_recover");
  23819. pContext->alsa.snd_pcm_readi = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_readi");
  23820. pContext->alsa.snd_pcm_writei = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_writei");
  23821. pContext->alsa.snd_pcm_avail = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_avail");
  23822. pContext->alsa.snd_pcm_avail_update = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_avail_update");
  23823. pContext->alsa.snd_pcm_wait = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_wait");
  23824. pContext->alsa.snd_pcm_nonblock = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_nonblock");
  23825. pContext->alsa.snd_pcm_info = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_info");
  23826. pContext->alsa.snd_pcm_info_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_info_sizeof");
  23827. pContext->alsa.snd_pcm_info_get_name = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_info_get_name");
  23828. pContext->alsa.snd_pcm_poll_descriptors = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_poll_descriptors");
  23829. pContext->alsa.snd_pcm_poll_descriptors_count = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_poll_descriptors_count");
  23830. pContext->alsa.snd_pcm_poll_descriptors_revents = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_poll_descriptors_revents");
  23831. pContext->alsa.snd_config_update_free_global = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_config_update_free_global");
  23832. #else
  23833. /* The system below is just for type safety. */
  23834. ma_snd_pcm_open_proc _snd_pcm_open = snd_pcm_open;
  23835. ma_snd_pcm_close_proc _snd_pcm_close = snd_pcm_close;
  23836. ma_snd_pcm_hw_params_sizeof_proc _snd_pcm_hw_params_sizeof = snd_pcm_hw_params_sizeof;
  23837. ma_snd_pcm_hw_params_any_proc _snd_pcm_hw_params_any = snd_pcm_hw_params_any;
  23838. ma_snd_pcm_hw_params_set_format_proc _snd_pcm_hw_params_set_format = snd_pcm_hw_params_set_format;
  23839. ma_snd_pcm_hw_params_set_format_first_proc _snd_pcm_hw_params_set_format_first = snd_pcm_hw_params_set_format_first;
  23840. ma_snd_pcm_hw_params_get_format_mask_proc _snd_pcm_hw_params_get_format_mask = snd_pcm_hw_params_get_format_mask;
  23841. ma_snd_pcm_hw_params_set_channels_proc _snd_pcm_hw_params_set_channels = snd_pcm_hw_params_set_channels;
  23842. ma_snd_pcm_hw_params_set_channels_near_proc _snd_pcm_hw_params_set_channels_near = snd_pcm_hw_params_set_channels_near;
  23843. ma_snd_pcm_hw_params_set_rate_resample_proc _snd_pcm_hw_params_set_rate_resample = snd_pcm_hw_params_set_rate_resample;
  23844. ma_snd_pcm_hw_params_set_rate_near _snd_pcm_hw_params_set_rate = snd_pcm_hw_params_set_rate;
  23845. ma_snd_pcm_hw_params_set_rate_near_proc _snd_pcm_hw_params_set_rate_near = snd_pcm_hw_params_set_rate_near;
  23846. ma_snd_pcm_hw_params_set_rate_minmax_proc _snd_pcm_hw_params_set_rate_minmax = snd_pcm_hw_params_set_rate_minmax;
  23847. ma_snd_pcm_hw_params_set_buffer_size_near_proc _snd_pcm_hw_params_set_buffer_size_near = snd_pcm_hw_params_set_buffer_size_near;
  23848. ma_snd_pcm_hw_params_set_periods_near_proc _snd_pcm_hw_params_set_periods_near = snd_pcm_hw_params_set_periods_near;
  23849. ma_snd_pcm_hw_params_set_access_proc _snd_pcm_hw_params_set_access = snd_pcm_hw_params_set_access;
  23850. ma_snd_pcm_hw_params_get_format_proc _snd_pcm_hw_params_get_format = snd_pcm_hw_params_get_format;
  23851. ma_snd_pcm_hw_params_get_channels_proc _snd_pcm_hw_params_get_channels = snd_pcm_hw_params_get_channels;
  23852. ma_snd_pcm_hw_params_get_channels_min_proc _snd_pcm_hw_params_get_channels_min = snd_pcm_hw_params_get_channels_min;
  23853. ma_snd_pcm_hw_params_get_channels_max_proc _snd_pcm_hw_params_get_channels_max = snd_pcm_hw_params_get_channels_max;
  23854. ma_snd_pcm_hw_params_get_rate_proc _snd_pcm_hw_params_get_rate = snd_pcm_hw_params_get_rate;
  23855. ma_snd_pcm_hw_params_get_rate_min_proc _snd_pcm_hw_params_get_rate_min = snd_pcm_hw_params_get_rate_min;
  23856. ma_snd_pcm_hw_params_get_rate_max_proc _snd_pcm_hw_params_get_rate_max = snd_pcm_hw_params_get_rate_max;
  23857. ma_snd_pcm_hw_params_get_buffer_size_proc _snd_pcm_hw_params_get_buffer_size = snd_pcm_hw_params_get_buffer_size;
  23858. ma_snd_pcm_hw_params_get_periods_proc _snd_pcm_hw_params_get_periods = snd_pcm_hw_params_get_periods;
  23859. ma_snd_pcm_hw_params_get_access_proc _snd_pcm_hw_params_get_access = snd_pcm_hw_params_get_access;
  23860. ma_snd_pcm_hw_params_test_format_proc _snd_pcm_hw_params_test_format = snd_pcm_hw_params_test_format;
  23861. ma_snd_pcm_hw_params_test_channels_proc _snd_pcm_hw_params_test_channels = snd_pcm_hw_params_test_channels;
  23862. ma_snd_pcm_hw_params_test_rate_proc _snd_pcm_hw_params_test_rate = snd_pcm_hw_params_test_rate;
  23863. ma_snd_pcm_hw_params_proc _snd_pcm_hw_params = snd_pcm_hw_params;
  23864. ma_snd_pcm_sw_params_sizeof_proc _snd_pcm_sw_params_sizeof = snd_pcm_sw_params_sizeof;
  23865. ma_snd_pcm_sw_params_current_proc _snd_pcm_sw_params_current = snd_pcm_sw_params_current;
  23866. ma_snd_pcm_sw_params_get_boundary_proc _snd_pcm_sw_params_get_boundary = snd_pcm_sw_params_get_boundary;
  23867. ma_snd_pcm_sw_params_set_avail_min_proc _snd_pcm_sw_params_set_avail_min = snd_pcm_sw_params_set_avail_min;
  23868. ma_snd_pcm_sw_params_set_start_threshold_proc _snd_pcm_sw_params_set_start_threshold = snd_pcm_sw_params_set_start_threshold;
  23869. ma_snd_pcm_sw_params_set_stop_threshold_proc _snd_pcm_sw_params_set_stop_threshold = snd_pcm_sw_params_set_stop_threshold;
  23870. ma_snd_pcm_sw_params_proc _snd_pcm_sw_params = snd_pcm_sw_params;
  23871. ma_snd_pcm_format_mask_sizeof_proc _snd_pcm_format_mask_sizeof = snd_pcm_format_mask_sizeof;
  23872. ma_snd_pcm_format_mask_test_proc _snd_pcm_format_mask_test = snd_pcm_format_mask_test;
  23873. ma_snd_pcm_get_chmap_proc _snd_pcm_get_chmap = snd_pcm_get_chmap;
  23874. ma_snd_pcm_state_proc _snd_pcm_state = snd_pcm_state;
  23875. ma_snd_pcm_prepare_proc _snd_pcm_prepare = snd_pcm_prepare;
  23876. ma_snd_pcm_start_proc _snd_pcm_start = snd_pcm_start;
  23877. ma_snd_pcm_drop_proc _snd_pcm_drop = snd_pcm_drop;
  23878. ma_snd_pcm_drain_proc _snd_pcm_drain = snd_pcm_drain;
  23879. ma_snd_pcm_reset_proc _snd_pcm_reset = snd_pcm_reset;
  23880. ma_snd_device_name_hint_proc _snd_device_name_hint = snd_device_name_hint;
  23881. ma_snd_device_name_get_hint_proc _snd_device_name_get_hint = snd_device_name_get_hint;
  23882. ma_snd_card_get_index_proc _snd_card_get_index = snd_card_get_index;
  23883. ma_snd_device_name_free_hint_proc _snd_device_name_free_hint = snd_device_name_free_hint;
  23884. ma_snd_pcm_mmap_begin_proc _snd_pcm_mmap_begin = snd_pcm_mmap_begin;
  23885. ma_snd_pcm_mmap_commit_proc _snd_pcm_mmap_commit = snd_pcm_mmap_commit;
  23886. ma_snd_pcm_recover_proc _snd_pcm_recover = snd_pcm_recover;
  23887. ma_snd_pcm_readi_proc _snd_pcm_readi = snd_pcm_readi;
  23888. ma_snd_pcm_writei_proc _snd_pcm_writei = snd_pcm_writei;
  23889. ma_snd_pcm_avail_proc _snd_pcm_avail = snd_pcm_avail;
  23890. ma_snd_pcm_avail_update_proc _snd_pcm_avail_update = snd_pcm_avail_update;
  23891. ma_snd_pcm_wait_proc _snd_pcm_wait = snd_pcm_wait;
  23892. ma_snd_pcm_nonblock_proc _snd_pcm_nonblock = snd_pcm_nonblock;
  23893. ma_snd_pcm_info_proc _snd_pcm_info = snd_pcm_info;
  23894. ma_snd_pcm_info_sizeof_proc _snd_pcm_info_sizeof = snd_pcm_info_sizeof;
  23895. ma_snd_pcm_info_get_name_proc _snd_pcm_info_get_name = snd_pcm_info_get_name;
  23896. ma_snd_pcm_poll_descriptors _snd_pcm_poll_descriptors = snd_pcm_poll_descriptors;
  23897. ma_snd_pcm_poll_descriptors_count _snd_pcm_poll_descriptors_count = snd_pcm_poll_descriptors_count;
  23898. ma_snd_pcm_poll_descriptors_revents _snd_pcm_poll_descriptors_revents = snd_pcm_poll_descriptors_revents;
  23899. ma_snd_config_update_free_global_proc _snd_config_update_free_global = snd_config_update_free_global;
  23900. pContext->alsa.snd_pcm_open = (ma_proc)_snd_pcm_open;
  23901. pContext->alsa.snd_pcm_close = (ma_proc)_snd_pcm_close;
  23902. pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)_snd_pcm_hw_params_sizeof;
  23903. pContext->alsa.snd_pcm_hw_params_any = (ma_proc)_snd_pcm_hw_params_any;
  23904. pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)_snd_pcm_hw_params_set_format;
  23905. pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)_snd_pcm_hw_params_set_format_first;
  23906. pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)_snd_pcm_hw_params_get_format_mask;
  23907. pContext->alsa.snd_pcm_hw_params_set_channels = (ma_proc)_snd_pcm_hw_params_set_channels;
  23908. pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)_snd_pcm_hw_params_set_channels_near;
  23909. pContext->alsa.snd_pcm_hw_params_set_channels_minmax = (ma_proc)_snd_pcm_hw_params_set_channels_minmax;
  23910. pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)_snd_pcm_hw_params_set_rate_resample;
  23911. pContext->alsa.snd_pcm_hw_params_set_rate = (ma_proc)_snd_pcm_hw_params_set_rate;
  23912. pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)_snd_pcm_hw_params_set_rate_near;
  23913. pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)_snd_pcm_hw_params_set_buffer_size_near;
  23914. pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)_snd_pcm_hw_params_set_periods_near;
  23915. pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)_snd_pcm_hw_params_set_access;
  23916. pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)_snd_pcm_hw_params_get_format;
  23917. pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)_snd_pcm_hw_params_get_channels;
  23918. pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)_snd_pcm_hw_params_get_channels_min;
  23919. pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)_snd_pcm_hw_params_get_channels_max;
  23920. pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)_snd_pcm_hw_params_get_rate;
  23921. pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)_snd_pcm_hw_params_get_rate_min;
  23922. pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)_snd_pcm_hw_params_get_rate_max;
  23923. pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)_snd_pcm_hw_params_get_buffer_size;
  23924. pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)_snd_pcm_hw_params_get_periods;
  23925. pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)_snd_pcm_hw_params_get_access;
  23926. pContext->alsa.snd_pcm_hw_params_test_format = (ma_proc)_snd_pcm_hw_params_test_format;
  23927. pContext->alsa.snd_pcm_hw_params_test_channels = (ma_proc)_snd_pcm_hw_params_test_channels;
  23928. pContext->alsa.snd_pcm_hw_params_test_rate = (ma_proc)_snd_pcm_hw_params_test_rate;
  23929. pContext->alsa.snd_pcm_hw_params = (ma_proc)_snd_pcm_hw_params;
  23930. pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)_snd_pcm_sw_params_sizeof;
  23931. pContext->alsa.snd_pcm_sw_params_current = (ma_proc)_snd_pcm_sw_params_current;
  23932. pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)_snd_pcm_sw_params_get_boundary;
  23933. pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)_snd_pcm_sw_params_set_avail_min;
  23934. pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)_snd_pcm_sw_params_set_start_threshold;
  23935. pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)_snd_pcm_sw_params_set_stop_threshold;
  23936. pContext->alsa.snd_pcm_sw_params = (ma_proc)_snd_pcm_sw_params;
  23937. pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)_snd_pcm_format_mask_sizeof;
  23938. pContext->alsa.snd_pcm_format_mask_test = (ma_proc)_snd_pcm_format_mask_test;
  23939. pContext->alsa.snd_pcm_get_chmap = (ma_proc)_snd_pcm_get_chmap;
  23940. pContext->alsa.snd_pcm_state = (ma_proc)_snd_pcm_state;
  23941. pContext->alsa.snd_pcm_prepare = (ma_proc)_snd_pcm_prepare;
  23942. pContext->alsa.snd_pcm_start = (ma_proc)_snd_pcm_start;
  23943. pContext->alsa.snd_pcm_drop = (ma_proc)_snd_pcm_drop;
  23944. pContext->alsa.snd_pcm_drain = (ma_proc)_snd_pcm_drain;
  23945. pContext->alsa.snd_pcm_reset = (ma_proc)_snd_pcm_reset;
  23946. pContext->alsa.snd_device_name_hint = (ma_proc)_snd_device_name_hint;
  23947. pContext->alsa.snd_device_name_get_hint = (ma_proc)_snd_device_name_get_hint;
  23948. pContext->alsa.snd_card_get_index = (ma_proc)_snd_card_get_index;
  23949. pContext->alsa.snd_device_name_free_hint = (ma_proc)_snd_device_name_free_hint;
  23950. pContext->alsa.snd_pcm_mmap_begin = (ma_proc)_snd_pcm_mmap_begin;
  23951. pContext->alsa.snd_pcm_mmap_commit = (ma_proc)_snd_pcm_mmap_commit;
  23952. pContext->alsa.snd_pcm_recover = (ma_proc)_snd_pcm_recover;
  23953. pContext->alsa.snd_pcm_readi = (ma_proc)_snd_pcm_readi;
  23954. pContext->alsa.snd_pcm_writei = (ma_proc)_snd_pcm_writei;
  23955. pContext->alsa.snd_pcm_avail = (ma_proc)_snd_pcm_avail;
  23956. pContext->alsa.snd_pcm_avail_update = (ma_proc)_snd_pcm_avail_update;
  23957. pContext->alsa.snd_pcm_wait = (ma_proc)_snd_pcm_wait;
  23958. pContext->alsa.snd_pcm_nonblock = (ma_proc)_snd_pcm_nonblock;
  23959. pContext->alsa.snd_pcm_info = (ma_proc)_snd_pcm_info;
  23960. pContext->alsa.snd_pcm_info_sizeof = (ma_proc)_snd_pcm_info_sizeof;
  23961. pContext->alsa.snd_pcm_info_get_name = (ma_proc)_snd_pcm_info_get_name;
  23962. pContext->alsa.snd_pcm_poll_descriptors = (ma_proc)_snd_pcm_poll_descriptors;
  23963. pContext->alsa.snd_pcm_poll_descriptors_count = (ma_proc)_snd_pcm_poll_descriptors_count;
  23964. pContext->alsa.snd_pcm_poll_descriptors_revents = (ma_proc)_snd_pcm_poll_descriptors_revents;
  23965. pContext->alsa.snd_config_update_free_global = (ma_proc)_snd_config_update_free_global;
  23966. #endif
  23967. pContext->alsa.useVerboseDeviceEnumeration = pConfig->alsa.useVerboseDeviceEnumeration;
  23968. result = ma_mutex_init(&pContext->alsa.internalDeviceEnumLock);
  23969. if (result != MA_SUCCESS) {
  23970. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] WARNING: Failed to initialize mutex for internal device enumeration.");
  23971. return result;
  23972. }
  23973. pCallbacks->onContextInit = ma_context_init__alsa;
  23974. pCallbacks->onContextUninit = ma_context_uninit__alsa;
  23975. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__alsa;
  23976. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__alsa;
  23977. pCallbacks->onDeviceInit = ma_device_init__alsa;
  23978. pCallbacks->onDeviceUninit = ma_device_uninit__alsa;
  23979. pCallbacks->onDeviceStart = ma_device_start__alsa;
  23980. pCallbacks->onDeviceStop = ma_device_stop__alsa;
  23981. pCallbacks->onDeviceRead = ma_device_read__alsa;
  23982. pCallbacks->onDeviceWrite = ma_device_write__alsa;
  23983. pCallbacks->onDeviceDataLoop = NULL;
  23984. pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__alsa;
  23985. return MA_SUCCESS;
  23986. }
  23987. #endif /* ALSA */
  23988. /******************************************************************************
  23989. PulseAudio Backend
  23990. ******************************************************************************/
  23991. #ifdef MA_HAS_PULSEAUDIO
  23992. /*
  23993. The PulseAudio API, along with Apple's Core Audio, is the worst of the maintream audio APIs. This is a brief description of what's going on
  23994. in the PulseAudio backend. I apologize if this gets a bit ranty for your liking - you might want to skip this discussion.
  23995. PulseAudio has something they call the "Simple API", which unfortunately isn't suitable for miniaudio. I've not seen anywhere where it
  23996. allows you to enumerate over devices, nor does it seem to support the ability to stop and start streams. Looking at the documentation, it
  23997. appears as though the stream is constantly running and you prevent sound from being emitted or captured by simply not calling the read or
  23998. write functions. This is not a professional solution as it would be much better to *actually* stop the underlying stream. Perhaps the
  23999. simple API has some smarts to do this automatically, but I'm not sure. Another limitation with the simple API is that it seems inefficient
  24000. when you want to have multiple streams to a single context. For these reasons, miniaudio is not using the simple API.
  24001. Since we're not using the simple API, we're left with the asynchronous API as our only other option. And boy, is this where it starts to
  24002. get fun, and I don't mean that in a good way...
  24003. The problems start with the very name of the API - "asynchronous". Yes, this is an asynchronous oriented API which means your commands
  24004. don't immediately take effect. You instead need to issue your commands, and then wait for them to complete. The waiting mechanism is
  24005. enabled through the use of a "main loop". In the asychronous API you cannot get away from the main loop, and the main loop is where almost
  24006. all of PulseAudio's problems stem from.
  24007. When you first initialize PulseAudio you need an object referred to as "main loop". You can implement this yourself by defining your own
  24008. vtable, but it's much easier to just use one of the built-in main loop implementations. There's two generic implementations called
  24009. pa_mainloop and pa_threaded_mainloop, and another implementation specific to GLib called pa_glib_mainloop. We're using pa_threaded_mainloop
  24010. because it simplifies management of the worker thread. The idea of the main loop object is pretty self explanatory - you're supposed to use
  24011. it to implement a worker thread which runs in a loop. The main loop is where operations are actually executed.
  24012. To initialize the main loop, you just use `pa_threaded_mainloop_new()`. This is the first function you'll call. You can then get a pointer
  24013. to the vtable with `pa_threaded_mainloop_get_api()` (the main loop vtable is called `pa_mainloop_api`). Again, you can bypass the threaded
  24014. main loop object entirely and just implement `pa_mainloop_api` directly, but there's no need for it unless you're doing something extremely
  24015. specialized such as if you want to integrate it into your application's existing main loop infrastructure.
  24016. (EDIT 2021-01-26: miniaudio is no longer using `pa_threaded_mainloop` due to this issue: https://github.com/mackron/miniaudio/issues/262.
  24017. It is now using `pa_mainloop` which turns out to be a simpler solution anyway. The rest of this rant still applies, however.)
  24018. Once you have your main loop vtable (the `pa_mainloop_api` object) you can create the PulseAudio context. This is very similar to
  24019. miniaudio's context and they map to each other quite well. You have one context to many streams, which is basically the same as miniaudio's
  24020. one `ma_context` to many `ma_device`s. Here's where it starts to get annoying, however. When you first create the PulseAudio context, which
  24021. is done with `pa_context_new()`, it's not actually connected to anything. When you connect, you call `pa_context_connect()`. However, if
  24022. you remember, PulseAudio is an asynchronous API. That means you cannot just assume the context is connected after `pa_context_context()`
  24023. has returned. You instead need to wait for it to connect. To do this, you need to either wait for a callback to get fired, which you can
  24024. set with `pa_context_set_state_callback()`, or you can continuously poll the context's state. Either way, you need to run this in a loop.
  24025. All objects from here out are created from the context, and, I believe, you can't be creating these objects until the context is connected.
  24026. This waiting loop is therefore unavoidable. In order for the waiting to ever complete, however, the main loop needs to be running. Before
  24027. attempting to connect the context, the main loop needs to be started with `pa_threaded_mainloop_start()`.
  24028. The reason for this asynchronous design is to support cases where you're connecting to a remote server, say through a local network or an
  24029. internet connection. However, the *VAST* majority of cases don't involve this at all - they just connect to a local "server" running on the
  24030. host machine. The fact that this would be the default rather than making `pa_context_connect()` synchronous tends to boggle the mind.
  24031. Once the context has been created and connected you can start creating a stream. A PulseAudio stream is analogous to miniaudio's device.
  24032. The initialization of a stream is fairly standard - you configure some attributes (analogous to miniaudio's device config) and then call
  24033. `pa_stream_new()` to actually create it. Here is where we start to get into "operations". When configuring the stream, you can get
  24034. information about the source (such as sample format, sample rate, etc.), however it's not synchronous. Instead, a `pa_operation` object
  24035. is returned from `pa_context_get_source_info_by_name()` (capture) or `pa_context_get_sink_info_by_name()` (playback). Then, you need to
  24036. run a loop (again!) to wait for the operation to complete which you can determine via a callback or polling, just like we did with the
  24037. context. Then, as an added bonus, you need to decrement the reference counter of the `pa_operation` object to ensure memory is cleaned up.
  24038. All of that just to retrieve basic information about a device!
  24039. Once the basic information about the device has been retrieved, miniaudio can now create the stream with `ma_stream_new()`. Like the
  24040. context, this needs to be connected. But we need to be careful here, because we're now about to introduce one of the most horrific design
  24041. choices in PulseAudio.
  24042. PulseAudio allows you to specify a callback that is fired when data can be written to or read from a stream. The language is important here
  24043. because PulseAudio takes it literally, specifically the "can be". You would think these callbacks would be appropriate as the place for
  24044. writing and reading data to and from the stream, and that would be right, except when it's not. When you initialize the stream, you can
  24045. set a flag that tells PulseAudio to not start the stream automatically. This is required because miniaudio does not auto-start devices
  24046. straight after initialization - you need to call `ma_device_start()` manually. The problem is that even when this flag is specified,
  24047. PulseAudio will immediately fire it's write or read callback. This is *technically* correct (based on the wording in the documentation)
  24048. because indeed, data *can* be written at this point. The problem is that it's not *practical*. It makes sense that the write/read callback
  24049. would be where a program will want to write or read data to or from the stream, but when it's called before the application has even
  24050. requested that the stream be started, it's just not practical because the program probably isn't ready for any kind of data delivery at
  24051. that point (it may still need to load files or whatnot). Instead, this callback should only be fired when the application requests the
  24052. stream be started which is how it works with literally *every* other callback-based audio API. Since miniaudio forbids firing of the data
  24053. callback until the device has been started (as it should be with *all* callback based APIs), logic needs to be added to ensure miniaudio
  24054. doesn't just blindly fire the application-defined data callback from within the PulseAudio callback before the stream has actually been
  24055. started. The device state is used for this - if the state is anything other than `ma_device_state_starting` or `ma_device_state_started`, the main data
  24056. callback is not fired.
  24057. This, unfortunately, is not the end of the problems with the PulseAudio write callback. Any normal callback based audio API will
  24058. continuously fire the callback at regular intervals based on the size of the internal buffer. This will only ever be fired when the device
  24059. is running, and will be fired regardless of whether or not the user actually wrote anything to the device/stream. This not the case in
  24060. PulseAudio. In PulseAudio, the data callback will *only* be called if you wrote something to it previously. That means, if you don't call
  24061. `pa_stream_write()`, the callback will not get fired. On the surface you wouldn't think this would matter because you should be always
  24062. writing data, and if you don't have anything to write, just write silence. That's fine until you want to drain the stream. You see, if
  24063. you're continuously writing data to the stream, the stream will never get drained! That means in order to drain the stream, you need to
  24064. *not* write data to it! But remember, when you don't write data to the stream, the callback won't get fired again! Why is draining
  24065. important? Because that's how we've defined stopping to work in miniaudio. In miniaudio, stopping the device requires it to be drained
  24066. before returning from ma_device_stop(). So we've stopped the device, which requires us to drain, but draining requires us to *not* write
  24067. data to the stream (or else it won't ever complete draining), but not writing to the stream means the callback won't get fired again!
  24068. This becomes a problem when stopping and then restarting the device. When the device is stopped, it's drained, which requires us to *not*
  24069. write anything to the stream. But then, since we didn't write anything to it, the write callback will *never* get called again if we just
  24070. resume the stream naively. This means that starting the stream requires us to write data to the stream from outside the callback. This
  24071. disconnect is something PulseAudio has got seriously wrong - there should only ever be a single source of data delivery, that being the
  24072. callback. (I have tried using `pa_stream_flush()` to trigger the write callback to fire, but this just doesn't work for some reason.)
  24073. Once you've created the stream, you need to connect it which involves the whole waiting procedure. This is the same process as the context,
  24074. only this time you'll poll for the state with `pa_stream_get_status()`. The starting and stopping of a streaming is referred to as
  24075. "corking" in PulseAudio. The analogy is corking a barrel. To start the stream, you uncork it, to stop it you cork it. Personally I think
  24076. it's silly - why would you not just call it "starting" and "stopping" like any other normal audio API? Anyway, the act of corking is, you
  24077. guessed it, asynchronous. This means you'll need our waiting loop as usual. Again, why this asynchronous design is the default is
  24078. absolutely beyond me. Would it really be that hard to just make it run synchronously?
  24079. Teardown is pretty simple (what?!). It's just a matter of calling the relevant `_unref()` function on each object in reverse order that
  24080. they were initialized in.
  24081. That's about it from the PulseAudio side. A bit ranty, I know, but they really need to fix that main loop and callback system. They're
  24082. embarrassingly unpractical. The main loop thing is an easy fix - have synchronous versions of all APIs. If an application wants these to
  24083. run asynchronously, they can execute them in a separate thread themselves. The desire to run these asynchronously is such a niche
  24084. requirement - it makes no sense to make it the default. The stream write callback needs to be change, or an alternative provided, that is
  24085. constantly fired, regardless of whether or not `pa_stream_write()` has been called, and it needs to take a pointer to a buffer as a
  24086. parameter which the program just writes to directly rather than having to call `pa_stream_writable_size()` and `pa_stream_write()`. These
  24087. changes alone will change PulseAudio from one of the worst audio APIs to one of the best.
  24088. */
  24089. /*
  24090. It is assumed pulseaudio.h is available when linking at compile time. When linking at compile time, we use the declarations in the header
  24091. to check for type safety. We cannot do this when linking at run time because the header might not be available.
  24092. */
  24093. #ifdef MA_NO_RUNTIME_LINKING
  24094. /* pulseaudio.h marks some functions with "inline" which isn't always supported. Need to emulate it. */
  24095. #if !defined(__cplusplus)
  24096. #if defined(__STRICT_ANSI__)
  24097. #if !defined(inline)
  24098. #define inline __inline__ __attribute__((always_inline))
  24099. #define MA_INLINE_DEFINED
  24100. #endif
  24101. #endif
  24102. #endif
  24103. #include <pulse/pulseaudio.h>
  24104. #if defined(MA_INLINE_DEFINED)
  24105. #undef inline
  24106. #undef MA_INLINE_DEFINED
  24107. #endif
  24108. #define MA_PA_OK PA_OK
  24109. #define MA_PA_ERR_ACCESS PA_ERR_ACCESS
  24110. #define MA_PA_ERR_INVALID PA_ERR_INVALID
  24111. #define MA_PA_ERR_NOENTITY PA_ERR_NOENTITY
  24112. #define MA_PA_ERR_NOTSUPPORTED PA_ERR_NOTSUPPORTED
  24113. #define MA_PA_CHANNELS_MAX PA_CHANNELS_MAX
  24114. #define MA_PA_RATE_MAX PA_RATE_MAX
  24115. typedef pa_context_flags_t ma_pa_context_flags_t;
  24116. #define MA_PA_CONTEXT_NOFLAGS PA_CONTEXT_NOFLAGS
  24117. #define MA_PA_CONTEXT_NOAUTOSPAWN PA_CONTEXT_NOAUTOSPAWN
  24118. #define MA_PA_CONTEXT_NOFAIL PA_CONTEXT_NOFAIL
  24119. typedef pa_stream_flags_t ma_pa_stream_flags_t;
  24120. #define MA_PA_STREAM_NOFLAGS PA_STREAM_NOFLAGS
  24121. #define MA_PA_STREAM_START_CORKED PA_STREAM_START_CORKED
  24122. #define MA_PA_STREAM_INTERPOLATE_TIMING PA_STREAM_INTERPOLATE_TIMING
  24123. #define MA_PA_STREAM_NOT_MONOTONIC PA_STREAM_NOT_MONOTONIC
  24124. #define MA_PA_STREAM_AUTO_TIMING_UPDATE PA_STREAM_AUTO_TIMING_UPDATE
  24125. #define MA_PA_STREAM_NO_REMAP_CHANNELS PA_STREAM_NO_REMAP_CHANNELS
  24126. #define MA_PA_STREAM_NO_REMIX_CHANNELS PA_STREAM_NO_REMIX_CHANNELS
  24127. #define MA_PA_STREAM_FIX_FORMAT PA_STREAM_FIX_FORMAT
  24128. #define MA_PA_STREAM_FIX_RATE PA_STREAM_FIX_RATE
  24129. #define MA_PA_STREAM_FIX_CHANNELS PA_STREAM_FIX_CHANNELS
  24130. #define MA_PA_STREAM_DONT_MOVE PA_STREAM_DONT_MOVE
  24131. #define MA_PA_STREAM_VARIABLE_RATE PA_STREAM_VARIABLE_RATE
  24132. #define MA_PA_STREAM_PEAK_DETECT PA_STREAM_PEAK_DETECT
  24133. #define MA_PA_STREAM_START_MUTED PA_STREAM_START_MUTED
  24134. #define MA_PA_STREAM_ADJUST_LATENCY PA_STREAM_ADJUST_LATENCY
  24135. #define MA_PA_STREAM_EARLY_REQUESTS PA_STREAM_EARLY_REQUESTS
  24136. #define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND
  24137. #define MA_PA_STREAM_START_UNMUTED PA_STREAM_START_UNMUTED
  24138. #define MA_PA_STREAM_FAIL_ON_SUSPEND PA_STREAM_FAIL_ON_SUSPEND
  24139. #define MA_PA_STREAM_RELATIVE_VOLUME PA_STREAM_RELATIVE_VOLUME
  24140. #define MA_PA_STREAM_PASSTHROUGH PA_STREAM_PASSTHROUGH
  24141. typedef pa_sink_flags_t ma_pa_sink_flags_t;
  24142. #define MA_PA_SINK_NOFLAGS PA_SINK_NOFLAGS
  24143. #define MA_PA_SINK_HW_VOLUME_CTRL PA_SINK_HW_VOLUME_CTRL
  24144. #define MA_PA_SINK_LATENCY PA_SINK_LATENCY
  24145. #define MA_PA_SINK_HARDWARE PA_SINK_HARDWARE
  24146. #define MA_PA_SINK_NETWORK PA_SINK_NETWORK
  24147. #define MA_PA_SINK_HW_MUTE_CTRL PA_SINK_HW_MUTE_CTRL
  24148. #define MA_PA_SINK_DECIBEL_VOLUME PA_SINK_DECIBEL_VOLUME
  24149. #define MA_PA_SINK_FLAT_VOLUME PA_SINK_FLAT_VOLUME
  24150. #define MA_PA_SINK_DYNAMIC_LATENCY PA_SINK_DYNAMIC_LATENCY
  24151. #define MA_PA_SINK_SET_FORMATS PA_SINK_SET_FORMATS
  24152. typedef pa_source_flags_t ma_pa_source_flags_t;
  24153. #define MA_PA_SOURCE_NOFLAGS PA_SOURCE_NOFLAGS
  24154. #define MA_PA_SOURCE_HW_VOLUME_CTRL PA_SOURCE_HW_VOLUME_CTRL
  24155. #define MA_PA_SOURCE_LATENCY PA_SOURCE_LATENCY
  24156. #define MA_PA_SOURCE_HARDWARE PA_SOURCE_HARDWARE
  24157. #define MA_PA_SOURCE_NETWORK PA_SOURCE_NETWORK
  24158. #define MA_PA_SOURCE_HW_MUTE_CTRL PA_SOURCE_HW_MUTE_CTRL
  24159. #define MA_PA_SOURCE_DECIBEL_VOLUME PA_SOURCE_DECIBEL_VOLUME
  24160. #define MA_PA_SOURCE_DYNAMIC_LATENCY PA_SOURCE_DYNAMIC_LATENCY
  24161. #define MA_PA_SOURCE_FLAT_VOLUME PA_SOURCE_FLAT_VOLUME
  24162. typedef pa_context_state_t ma_pa_context_state_t;
  24163. #define MA_PA_CONTEXT_UNCONNECTED PA_CONTEXT_UNCONNECTED
  24164. #define MA_PA_CONTEXT_CONNECTING PA_CONTEXT_CONNECTING
  24165. #define MA_PA_CONTEXT_AUTHORIZING PA_CONTEXT_AUTHORIZING
  24166. #define MA_PA_CONTEXT_SETTING_NAME PA_CONTEXT_SETTING_NAME
  24167. #define MA_PA_CONTEXT_READY PA_CONTEXT_READY
  24168. #define MA_PA_CONTEXT_FAILED PA_CONTEXT_FAILED
  24169. #define MA_PA_CONTEXT_TERMINATED PA_CONTEXT_TERMINATED
  24170. typedef pa_stream_state_t ma_pa_stream_state_t;
  24171. #define MA_PA_STREAM_UNCONNECTED PA_STREAM_UNCONNECTED
  24172. #define MA_PA_STREAM_CREATING PA_STREAM_CREATING
  24173. #define MA_PA_STREAM_READY PA_STREAM_READY
  24174. #define MA_PA_STREAM_FAILED PA_STREAM_FAILED
  24175. #define MA_PA_STREAM_TERMINATED PA_STREAM_TERMINATED
  24176. typedef pa_operation_state_t ma_pa_operation_state_t;
  24177. #define MA_PA_OPERATION_RUNNING PA_OPERATION_RUNNING
  24178. #define MA_PA_OPERATION_DONE PA_OPERATION_DONE
  24179. #define MA_PA_OPERATION_CANCELLED PA_OPERATION_CANCELLED
  24180. typedef pa_sink_state_t ma_pa_sink_state_t;
  24181. #define MA_PA_SINK_INVALID_STATE PA_SINK_INVALID_STATE
  24182. #define MA_PA_SINK_RUNNING PA_SINK_RUNNING
  24183. #define MA_PA_SINK_IDLE PA_SINK_IDLE
  24184. #define MA_PA_SINK_SUSPENDED PA_SINK_SUSPENDED
  24185. typedef pa_source_state_t ma_pa_source_state_t;
  24186. #define MA_PA_SOURCE_INVALID_STATE PA_SOURCE_INVALID_STATE
  24187. #define MA_PA_SOURCE_RUNNING PA_SOURCE_RUNNING
  24188. #define MA_PA_SOURCE_IDLE PA_SOURCE_IDLE
  24189. #define MA_PA_SOURCE_SUSPENDED PA_SOURCE_SUSPENDED
  24190. typedef pa_seek_mode_t ma_pa_seek_mode_t;
  24191. #define MA_PA_SEEK_RELATIVE PA_SEEK_RELATIVE
  24192. #define MA_PA_SEEK_ABSOLUTE PA_SEEK_ABSOLUTE
  24193. #define MA_PA_SEEK_RELATIVE_ON_READ PA_SEEK_RELATIVE_ON_READ
  24194. #define MA_PA_SEEK_RELATIVE_END PA_SEEK_RELATIVE_END
  24195. typedef pa_channel_position_t ma_pa_channel_position_t;
  24196. #define MA_PA_CHANNEL_POSITION_INVALID PA_CHANNEL_POSITION_INVALID
  24197. #define MA_PA_CHANNEL_POSITION_MONO PA_CHANNEL_POSITION_MONO
  24198. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT PA_CHANNEL_POSITION_FRONT_LEFT
  24199. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT PA_CHANNEL_POSITION_FRONT_RIGHT
  24200. #define MA_PA_CHANNEL_POSITION_FRONT_CENTER PA_CHANNEL_POSITION_FRONT_CENTER
  24201. #define MA_PA_CHANNEL_POSITION_REAR_CENTER PA_CHANNEL_POSITION_REAR_CENTER
  24202. #define MA_PA_CHANNEL_POSITION_REAR_LEFT PA_CHANNEL_POSITION_REAR_LEFT
  24203. #define MA_PA_CHANNEL_POSITION_REAR_RIGHT PA_CHANNEL_POSITION_REAR_RIGHT
  24204. #define MA_PA_CHANNEL_POSITION_LFE PA_CHANNEL_POSITION_LFE
  24205. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER
  24206. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER
  24207. #define MA_PA_CHANNEL_POSITION_SIDE_LEFT PA_CHANNEL_POSITION_SIDE_LEFT
  24208. #define MA_PA_CHANNEL_POSITION_SIDE_RIGHT PA_CHANNEL_POSITION_SIDE_RIGHT
  24209. #define MA_PA_CHANNEL_POSITION_AUX0 PA_CHANNEL_POSITION_AUX0
  24210. #define MA_PA_CHANNEL_POSITION_AUX1 PA_CHANNEL_POSITION_AUX1
  24211. #define MA_PA_CHANNEL_POSITION_AUX2 PA_CHANNEL_POSITION_AUX2
  24212. #define MA_PA_CHANNEL_POSITION_AUX3 PA_CHANNEL_POSITION_AUX3
  24213. #define MA_PA_CHANNEL_POSITION_AUX4 PA_CHANNEL_POSITION_AUX4
  24214. #define MA_PA_CHANNEL_POSITION_AUX5 PA_CHANNEL_POSITION_AUX5
  24215. #define MA_PA_CHANNEL_POSITION_AUX6 PA_CHANNEL_POSITION_AUX6
  24216. #define MA_PA_CHANNEL_POSITION_AUX7 PA_CHANNEL_POSITION_AUX7
  24217. #define MA_PA_CHANNEL_POSITION_AUX8 PA_CHANNEL_POSITION_AUX8
  24218. #define MA_PA_CHANNEL_POSITION_AUX9 PA_CHANNEL_POSITION_AUX9
  24219. #define MA_PA_CHANNEL_POSITION_AUX10 PA_CHANNEL_POSITION_AUX10
  24220. #define MA_PA_CHANNEL_POSITION_AUX11 PA_CHANNEL_POSITION_AUX11
  24221. #define MA_PA_CHANNEL_POSITION_AUX12 PA_CHANNEL_POSITION_AUX12
  24222. #define MA_PA_CHANNEL_POSITION_AUX13 PA_CHANNEL_POSITION_AUX13
  24223. #define MA_PA_CHANNEL_POSITION_AUX14 PA_CHANNEL_POSITION_AUX14
  24224. #define MA_PA_CHANNEL_POSITION_AUX15 PA_CHANNEL_POSITION_AUX15
  24225. #define MA_PA_CHANNEL_POSITION_AUX16 PA_CHANNEL_POSITION_AUX16
  24226. #define MA_PA_CHANNEL_POSITION_AUX17 PA_CHANNEL_POSITION_AUX17
  24227. #define MA_PA_CHANNEL_POSITION_AUX18 PA_CHANNEL_POSITION_AUX18
  24228. #define MA_PA_CHANNEL_POSITION_AUX19 PA_CHANNEL_POSITION_AUX19
  24229. #define MA_PA_CHANNEL_POSITION_AUX20 PA_CHANNEL_POSITION_AUX20
  24230. #define MA_PA_CHANNEL_POSITION_AUX21 PA_CHANNEL_POSITION_AUX21
  24231. #define MA_PA_CHANNEL_POSITION_AUX22 PA_CHANNEL_POSITION_AUX22
  24232. #define MA_PA_CHANNEL_POSITION_AUX23 PA_CHANNEL_POSITION_AUX23
  24233. #define MA_PA_CHANNEL_POSITION_AUX24 PA_CHANNEL_POSITION_AUX24
  24234. #define MA_PA_CHANNEL_POSITION_AUX25 PA_CHANNEL_POSITION_AUX25
  24235. #define MA_PA_CHANNEL_POSITION_AUX26 PA_CHANNEL_POSITION_AUX26
  24236. #define MA_PA_CHANNEL_POSITION_AUX27 PA_CHANNEL_POSITION_AUX27
  24237. #define MA_PA_CHANNEL_POSITION_AUX28 PA_CHANNEL_POSITION_AUX28
  24238. #define MA_PA_CHANNEL_POSITION_AUX29 PA_CHANNEL_POSITION_AUX29
  24239. #define MA_PA_CHANNEL_POSITION_AUX30 PA_CHANNEL_POSITION_AUX30
  24240. #define MA_PA_CHANNEL_POSITION_AUX31 PA_CHANNEL_POSITION_AUX31
  24241. #define MA_PA_CHANNEL_POSITION_TOP_CENTER PA_CHANNEL_POSITION_TOP_CENTER
  24242. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT PA_CHANNEL_POSITION_TOP_FRONT_LEFT
  24243. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT PA_CHANNEL_POSITION_TOP_FRONT_RIGHT
  24244. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER PA_CHANNEL_POSITION_TOP_FRONT_CENTER
  24245. #define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT PA_CHANNEL_POSITION_TOP_REAR_LEFT
  24246. #define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT PA_CHANNEL_POSITION_TOP_REAR_RIGHT
  24247. #define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER PA_CHANNEL_POSITION_TOP_REAR_CENTER
  24248. #define MA_PA_CHANNEL_POSITION_LEFT PA_CHANNEL_POSITION_LEFT
  24249. #define MA_PA_CHANNEL_POSITION_RIGHT PA_CHANNEL_POSITION_RIGHT
  24250. #define MA_PA_CHANNEL_POSITION_CENTER PA_CHANNEL_POSITION_CENTER
  24251. #define MA_PA_CHANNEL_POSITION_SUBWOOFER PA_CHANNEL_POSITION_SUBWOOFER
  24252. typedef pa_channel_map_def_t ma_pa_channel_map_def_t;
  24253. #define MA_PA_CHANNEL_MAP_AIFF PA_CHANNEL_MAP_AIFF
  24254. #define MA_PA_CHANNEL_MAP_ALSA PA_CHANNEL_MAP_ALSA
  24255. #define MA_PA_CHANNEL_MAP_AUX PA_CHANNEL_MAP_AUX
  24256. #define MA_PA_CHANNEL_MAP_WAVEEX PA_CHANNEL_MAP_WAVEEX
  24257. #define MA_PA_CHANNEL_MAP_OSS PA_CHANNEL_MAP_OSS
  24258. #define MA_PA_CHANNEL_MAP_DEFAULT PA_CHANNEL_MAP_DEFAULT
  24259. typedef pa_sample_format_t ma_pa_sample_format_t;
  24260. #define MA_PA_SAMPLE_INVALID PA_SAMPLE_INVALID
  24261. #define MA_PA_SAMPLE_U8 PA_SAMPLE_U8
  24262. #define MA_PA_SAMPLE_ALAW PA_SAMPLE_ALAW
  24263. #define MA_PA_SAMPLE_ULAW PA_SAMPLE_ULAW
  24264. #define MA_PA_SAMPLE_S16LE PA_SAMPLE_S16LE
  24265. #define MA_PA_SAMPLE_S16BE PA_SAMPLE_S16BE
  24266. #define MA_PA_SAMPLE_FLOAT32LE PA_SAMPLE_FLOAT32LE
  24267. #define MA_PA_SAMPLE_FLOAT32BE PA_SAMPLE_FLOAT32BE
  24268. #define MA_PA_SAMPLE_S32LE PA_SAMPLE_S32LE
  24269. #define MA_PA_SAMPLE_S32BE PA_SAMPLE_S32BE
  24270. #define MA_PA_SAMPLE_S24LE PA_SAMPLE_S24LE
  24271. #define MA_PA_SAMPLE_S24BE PA_SAMPLE_S24BE
  24272. #define MA_PA_SAMPLE_S24_32LE PA_SAMPLE_S24_32LE
  24273. #define MA_PA_SAMPLE_S24_32BE PA_SAMPLE_S24_32BE
  24274. typedef pa_mainloop ma_pa_mainloop;
  24275. typedef pa_threaded_mainloop ma_pa_threaded_mainloop;
  24276. typedef pa_mainloop_api ma_pa_mainloop_api;
  24277. typedef pa_context ma_pa_context;
  24278. typedef pa_operation ma_pa_operation;
  24279. typedef pa_stream ma_pa_stream;
  24280. typedef pa_spawn_api ma_pa_spawn_api;
  24281. typedef pa_buffer_attr ma_pa_buffer_attr;
  24282. typedef pa_channel_map ma_pa_channel_map;
  24283. typedef pa_cvolume ma_pa_cvolume;
  24284. typedef pa_sample_spec ma_pa_sample_spec;
  24285. typedef pa_sink_info ma_pa_sink_info;
  24286. typedef pa_source_info ma_pa_source_info;
  24287. typedef pa_context_notify_cb_t ma_pa_context_notify_cb_t;
  24288. typedef pa_sink_info_cb_t ma_pa_sink_info_cb_t;
  24289. typedef pa_source_info_cb_t ma_pa_source_info_cb_t;
  24290. typedef pa_stream_success_cb_t ma_pa_stream_success_cb_t;
  24291. typedef pa_stream_request_cb_t ma_pa_stream_request_cb_t;
  24292. typedef pa_stream_notify_cb_t ma_pa_stream_notify_cb_t;
  24293. typedef pa_free_cb_t ma_pa_free_cb_t;
  24294. #else
  24295. #define MA_PA_OK 0
  24296. #define MA_PA_ERR_ACCESS 1
  24297. #define MA_PA_ERR_INVALID 2
  24298. #define MA_PA_ERR_NOENTITY 5
  24299. #define MA_PA_ERR_NOTSUPPORTED 19
  24300. #define MA_PA_CHANNELS_MAX 32
  24301. #define MA_PA_RATE_MAX 384000
  24302. typedef int ma_pa_context_flags_t;
  24303. #define MA_PA_CONTEXT_NOFLAGS 0x00000000
  24304. #define MA_PA_CONTEXT_NOAUTOSPAWN 0x00000001
  24305. #define MA_PA_CONTEXT_NOFAIL 0x00000002
  24306. typedef int ma_pa_stream_flags_t;
  24307. #define MA_PA_STREAM_NOFLAGS 0x00000000
  24308. #define MA_PA_STREAM_START_CORKED 0x00000001
  24309. #define MA_PA_STREAM_INTERPOLATE_TIMING 0x00000002
  24310. #define MA_PA_STREAM_NOT_MONOTONIC 0x00000004
  24311. #define MA_PA_STREAM_AUTO_TIMING_UPDATE 0x00000008
  24312. #define MA_PA_STREAM_NO_REMAP_CHANNELS 0x00000010
  24313. #define MA_PA_STREAM_NO_REMIX_CHANNELS 0x00000020
  24314. #define MA_PA_STREAM_FIX_FORMAT 0x00000040
  24315. #define MA_PA_STREAM_FIX_RATE 0x00000080
  24316. #define MA_PA_STREAM_FIX_CHANNELS 0x00000100
  24317. #define MA_PA_STREAM_DONT_MOVE 0x00000200
  24318. #define MA_PA_STREAM_VARIABLE_RATE 0x00000400
  24319. #define MA_PA_STREAM_PEAK_DETECT 0x00000800
  24320. #define MA_PA_STREAM_START_MUTED 0x00001000
  24321. #define MA_PA_STREAM_ADJUST_LATENCY 0x00002000
  24322. #define MA_PA_STREAM_EARLY_REQUESTS 0x00004000
  24323. #define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND 0x00008000
  24324. #define MA_PA_STREAM_START_UNMUTED 0x00010000
  24325. #define MA_PA_STREAM_FAIL_ON_SUSPEND 0x00020000
  24326. #define MA_PA_STREAM_RELATIVE_VOLUME 0x00040000
  24327. #define MA_PA_STREAM_PASSTHROUGH 0x00080000
  24328. typedef int ma_pa_sink_flags_t;
  24329. #define MA_PA_SINK_NOFLAGS 0x00000000
  24330. #define MA_PA_SINK_HW_VOLUME_CTRL 0x00000001
  24331. #define MA_PA_SINK_LATENCY 0x00000002
  24332. #define MA_PA_SINK_HARDWARE 0x00000004
  24333. #define MA_PA_SINK_NETWORK 0x00000008
  24334. #define MA_PA_SINK_HW_MUTE_CTRL 0x00000010
  24335. #define MA_PA_SINK_DECIBEL_VOLUME 0x00000020
  24336. #define MA_PA_SINK_FLAT_VOLUME 0x00000040
  24337. #define MA_PA_SINK_DYNAMIC_LATENCY 0x00000080
  24338. #define MA_PA_SINK_SET_FORMATS 0x00000100
  24339. typedef int ma_pa_source_flags_t;
  24340. #define MA_PA_SOURCE_NOFLAGS 0x00000000
  24341. #define MA_PA_SOURCE_HW_VOLUME_CTRL 0x00000001
  24342. #define MA_PA_SOURCE_LATENCY 0x00000002
  24343. #define MA_PA_SOURCE_HARDWARE 0x00000004
  24344. #define MA_PA_SOURCE_NETWORK 0x00000008
  24345. #define MA_PA_SOURCE_HW_MUTE_CTRL 0x00000010
  24346. #define MA_PA_SOURCE_DECIBEL_VOLUME 0x00000020
  24347. #define MA_PA_SOURCE_DYNAMIC_LATENCY 0x00000040
  24348. #define MA_PA_SOURCE_FLAT_VOLUME 0x00000080
  24349. typedef int ma_pa_context_state_t;
  24350. #define MA_PA_CONTEXT_UNCONNECTED 0
  24351. #define MA_PA_CONTEXT_CONNECTING 1
  24352. #define MA_PA_CONTEXT_AUTHORIZING 2
  24353. #define MA_PA_CONTEXT_SETTING_NAME 3
  24354. #define MA_PA_CONTEXT_READY 4
  24355. #define MA_PA_CONTEXT_FAILED 5
  24356. #define MA_PA_CONTEXT_TERMINATED 6
  24357. typedef int ma_pa_stream_state_t;
  24358. #define MA_PA_STREAM_UNCONNECTED 0
  24359. #define MA_PA_STREAM_CREATING 1
  24360. #define MA_PA_STREAM_READY 2
  24361. #define MA_PA_STREAM_FAILED 3
  24362. #define MA_PA_STREAM_TERMINATED 4
  24363. typedef int ma_pa_operation_state_t;
  24364. #define MA_PA_OPERATION_RUNNING 0
  24365. #define MA_PA_OPERATION_DONE 1
  24366. #define MA_PA_OPERATION_CANCELLED 2
  24367. typedef int ma_pa_sink_state_t;
  24368. #define MA_PA_SINK_INVALID_STATE -1
  24369. #define MA_PA_SINK_RUNNING 0
  24370. #define MA_PA_SINK_IDLE 1
  24371. #define MA_PA_SINK_SUSPENDED 2
  24372. typedef int ma_pa_source_state_t;
  24373. #define MA_PA_SOURCE_INVALID_STATE -1
  24374. #define MA_PA_SOURCE_RUNNING 0
  24375. #define MA_PA_SOURCE_IDLE 1
  24376. #define MA_PA_SOURCE_SUSPENDED 2
  24377. typedef int ma_pa_seek_mode_t;
  24378. #define MA_PA_SEEK_RELATIVE 0
  24379. #define MA_PA_SEEK_ABSOLUTE 1
  24380. #define MA_PA_SEEK_RELATIVE_ON_READ 2
  24381. #define MA_PA_SEEK_RELATIVE_END 3
  24382. typedef int ma_pa_channel_position_t;
  24383. #define MA_PA_CHANNEL_POSITION_INVALID -1
  24384. #define MA_PA_CHANNEL_POSITION_MONO 0
  24385. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT 1
  24386. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT 2
  24387. #define MA_PA_CHANNEL_POSITION_FRONT_CENTER 3
  24388. #define MA_PA_CHANNEL_POSITION_REAR_CENTER 4
  24389. #define MA_PA_CHANNEL_POSITION_REAR_LEFT 5
  24390. #define MA_PA_CHANNEL_POSITION_REAR_RIGHT 6
  24391. #define MA_PA_CHANNEL_POSITION_LFE 7
  24392. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER 8
  24393. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER 9
  24394. #define MA_PA_CHANNEL_POSITION_SIDE_LEFT 10
  24395. #define MA_PA_CHANNEL_POSITION_SIDE_RIGHT 11
  24396. #define MA_PA_CHANNEL_POSITION_AUX0 12
  24397. #define MA_PA_CHANNEL_POSITION_AUX1 13
  24398. #define MA_PA_CHANNEL_POSITION_AUX2 14
  24399. #define MA_PA_CHANNEL_POSITION_AUX3 15
  24400. #define MA_PA_CHANNEL_POSITION_AUX4 16
  24401. #define MA_PA_CHANNEL_POSITION_AUX5 17
  24402. #define MA_PA_CHANNEL_POSITION_AUX6 18
  24403. #define MA_PA_CHANNEL_POSITION_AUX7 19
  24404. #define MA_PA_CHANNEL_POSITION_AUX8 20
  24405. #define MA_PA_CHANNEL_POSITION_AUX9 21
  24406. #define MA_PA_CHANNEL_POSITION_AUX10 22
  24407. #define MA_PA_CHANNEL_POSITION_AUX11 23
  24408. #define MA_PA_CHANNEL_POSITION_AUX12 24
  24409. #define MA_PA_CHANNEL_POSITION_AUX13 25
  24410. #define MA_PA_CHANNEL_POSITION_AUX14 26
  24411. #define MA_PA_CHANNEL_POSITION_AUX15 27
  24412. #define MA_PA_CHANNEL_POSITION_AUX16 28
  24413. #define MA_PA_CHANNEL_POSITION_AUX17 29
  24414. #define MA_PA_CHANNEL_POSITION_AUX18 30
  24415. #define MA_PA_CHANNEL_POSITION_AUX19 31
  24416. #define MA_PA_CHANNEL_POSITION_AUX20 32
  24417. #define MA_PA_CHANNEL_POSITION_AUX21 33
  24418. #define MA_PA_CHANNEL_POSITION_AUX22 34
  24419. #define MA_PA_CHANNEL_POSITION_AUX23 35
  24420. #define MA_PA_CHANNEL_POSITION_AUX24 36
  24421. #define MA_PA_CHANNEL_POSITION_AUX25 37
  24422. #define MA_PA_CHANNEL_POSITION_AUX26 38
  24423. #define MA_PA_CHANNEL_POSITION_AUX27 39
  24424. #define MA_PA_CHANNEL_POSITION_AUX28 40
  24425. #define MA_PA_CHANNEL_POSITION_AUX29 41
  24426. #define MA_PA_CHANNEL_POSITION_AUX30 42
  24427. #define MA_PA_CHANNEL_POSITION_AUX31 43
  24428. #define MA_PA_CHANNEL_POSITION_TOP_CENTER 44
  24429. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT 45
  24430. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT 46
  24431. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER 47
  24432. #define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT 48
  24433. #define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT 49
  24434. #define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER 50
  24435. #define MA_PA_CHANNEL_POSITION_LEFT MA_PA_CHANNEL_POSITION_FRONT_LEFT
  24436. #define MA_PA_CHANNEL_POSITION_RIGHT MA_PA_CHANNEL_POSITION_FRONT_RIGHT
  24437. #define MA_PA_CHANNEL_POSITION_CENTER MA_PA_CHANNEL_POSITION_FRONT_CENTER
  24438. #define MA_PA_CHANNEL_POSITION_SUBWOOFER MA_PA_CHANNEL_POSITION_LFE
  24439. typedef int ma_pa_channel_map_def_t;
  24440. #define MA_PA_CHANNEL_MAP_AIFF 0
  24441. #define MA_PA_CHANNEL_MAP_ALSA 1
  24442. #define MA_PA_CHANNEL_MAP_AUX 2
  24443. #define MA_PA_CHANNEL_MAP_WAVEEX 3
  24444. #define MA_PA_CHANNEL_MAP_OSS 4
  24445. #define MA_PA_CHANNEL_MAP_DEFAULT MA_PA_CHANNEL_MAP_AIFF
  24446. typedef int ma_pa_sample_format_t;
  24447. #define MA_PA_SAMPLE_INVALID -1
  24448. #define MA_PA_SAMPLE_U8 0
  24449. #define MA_PA_SAMPLE_ALAW 1
  24450. #define MA_PA_SAMPLE_ULAW 2
  24451. #define MA_PA_SAMPLE_S16LE 3
  24452. #define MA_PA_SAMPLE_S16BE 4
  24453. #define MA_PA_SAMPLE_FLOAT32LE 5
  24454. #define MA_PA_SAMPLE_FLOAT32BE 6
  24455. #define MA_PA_SAMPLE_S32LE 7
  24456. #define MA_PA_SAMPLE_S32BE 8
  24457. #define MA_PA_SAMPLE_S24LE 9
  24458. #define MA_PA_SAMPLE_S24BE 10
  24459. #define MA_PA_SAMPLE_S24_32LE 11
  24460. #define MA_PA_SAMPLE_S24_32BE 12
  24461. typedef struct ma_pa_mainloop ma_pa_mainloop;
  24462. typedef struct ma_pa_threaded_mainloop ma_pa_threaded_mainloop;
  24463. typedef struct ma_pa_mainloop_api ma_pa_mainloop_api;
  24464. typedef struct ma_pa_context ma_pa_context;
  24465. typedef struct ma_pa_operation ma_pa_operation;
  24466. typedef struct ma_pa_stream ma_pa_stream;
  24467. typedef struct ma_pa_spawn_api ma_pa_spawn_api;
  24468. typedef struct
  24469. {
  24470. ma_uint32 maxlength;
  24471. ma_uint32 tlength;
  24472. ma_uint32 prebuf;
  24473. ma_uint32 minreq;
  24474. ma_uint32 fragsize;
  24475. } ma_pa_buffer_attr;
  24476. typedef struct
  24477. {
  24478. ma_uint8 channels;
  24479. ma_pa_channel_position_t map[MA_PA_CHANNELS_MAX];
  24480. } ma_pa_channel_map;
  24481. typedef struct
  24482. {
  24483. ma_uint8 channels;
  24484. ma_uint32 values[MA_PA_CHANNELS_MAX];
  24485. } ma_pa_cvolume;
  24486. typedef struct
  24487. {
  24488. ma_pa_sample_format_t format;
  24489. ma_uint32 rate;
  24490. ma_uint8 channels;
  24491. } ma_pa_sample_spec;
  24492. typedef struct
  24493. {
  24494. const char* name;
  24495. ma_uint32 index;
  24496. const char* description;
  24497. ma_pa_sample_spec sample_spec;
  24498. ma_pa_channel_map channel_map;
  24499. ma_uint32 owner_module;
  24500. ma_pa_cvolume volume;
  24501. int mute;
  24502. ma_uint32 monitor_source;
  24503. const char* monitor_source_name;
  24504. ma_uint64 latency;
  24505. const char* driver;
  24506. ma_pa_sink_flags_t flags;
  24507. void* proplist;
  24508. ma_uint64 configured_latency;
  24509. ma_uint32 base_volume;
  24510. ma_pa_sink_state_t state;
  24511. ma_uint32 n_volume_steps;
  24512. ma_uint32 card;
  24513. ma_uint32 n_ports;
  24514. void** ports;
  24515. void* active_port;
  24516. ma_uint8 n_formats;
  24517. void** formats;
  24518. } ma_pa_sink_info;
  24519. typedef struct
  24520. {
  24521. const char *name;
  24522. ma_uint32 index;
  24523. const char *description;
  24524. ma_pa_sample_spec sample_spec;
  24525. ma_pa_channel_map channel_map;
  24526. ma_uint32 owner_module;
  24527. ma_pa_cvolume volume;
  24528. int mute;
  24529. ma_uint32 monitor_of_sink;
  24530. const char *monitor_of_sink_name;
  24531. ma_uint64 latency;
  24532. const char *driver;
  24533. ma_pa_source_flags_t flags;
  24534. void* proplist;
  24535. ma_uint64 configured_latency;
  24536. ma_uint32 base_volume;
  24537. ma_pa_source_state_t state;
  24538. ma_uint32 n_volume_steps;
  24539. ma_uint32 card;
  24540. ma_uint32 n_ports;
  24541. void** ports;
  24542. void* active_port;
  24543. ma_uint8 n_formats;
  24544. void** formats;
  24545. } ma_pa_source_info;
  24546. typedef void (* ma_pa_context_notify_cb_t)(ma_pa_context* c, void* userdata);
  24547. typedef void (* ma_pa_sink_info_cb_t) (ma_pa_context* c, const ma_pa_sink_info* i, int eol, void* userdata);
  24548. typedef void (* ma_pa_source_info_cb_t) (ma_pa_context* c, const ma_pa_source_info* i, int eol, void* userdata);
  24549. typedef void (* ma_pa_stream_success_cb_t)(ma_pa_stream* s, int success, void* userdata);
  24550. typedef void (* ma_pa_stream_request_cb_t)(ma_pa_stream* s, size_t nbytes, void* userdata);
  24551. typedef void (* ma_pa_stream_notify_cb_t) (ma_pa_stream* s, void* userdata);
  24552. typedef void (* ma_pa_free_cb_t) (void* p);
  24553. #endif
  24554. typedef ma_pa_mainloop* (* ma_pa_mainloop_new_proc) (void);
  24555. typedef void (* ma_pa_mainloop_free_proc) (ma_pa_mainloop* m);
  24556. typedef void (* ma_pa_mainloop_quit_proc) (ma_pa_mainloop* m, int retval);
  24557. typedef ma_pa_mainloop_api* (* ma_pa_mainloop_get_api_proc) (ma_pa_mainloop* m);
  24558. typedef int (* ma_pa_mainloop_iterate_proc) (ma_pa_mainloop* m, int block, int* retval);
  24559. typedef void (* ma_pa_mainloop_wakeup_proc) (ma_pa_mainloop* m);
  24560. typedef ma_pa_threaded_mainloop* (* ma_pa_threaded_mainloop_new_proc) (void);
  24561. typedef void (* ma_pa_threaded_mainloop_free_proc) (ma_pa_threaded_mainloop* m);
  24562. typedef int (* ma_pa_threaded_mainloop_start_proc) (ma_pa_threaded_mainloop* m);
  24563. typedef void (* ma_pa_threaded_mainloop_stop_proc) (ma_pa_threaded_mainloop* m);
  24564. typedef void (* ma_pa_threaded_mainloop_lock_proc) (ma_pa_threaded_mainloop* m);
  24565. typedef void (* ma_pa_threaded_mainloop_unlock_proc) (ma_pa_threaded_mainloop* m);
  24566. typedef void (* ma_pa_threaded_mainloop_wait_proc) (ma_pa_threaded_mainloop* m);
  24567. typedef void (* ma_pa_threaded_mainloop_signal_proc) (ma_pa_threaded_mainloop* m, int wait_for_accept);
  24568. typedef void (* ma_pa_threaded_mainloop_accept_proc) (ma_pa_threaded_mainloop* m);
  24569. typedef int (* ma_pa_threaded_mainloop_get_retval_proc) (ma_pa_threaded_mainloop* m);
  24570. typedef ma_pa_mainloop_api* (* ma_pa_threaded_mainloop_get_api_proc) (ma_pa_threaded_mainloop* m);
  24571. typedef int (* ma_pa_threaded_mainloop_in_thread_proc) (ma_pa_threaded_mainloop* m);
  24572. typedef void (* ma_pa_threaded_mainloop_set_name_proc) (ma_pa_threaded_mainloop* m, const char* name);
  24573. typedef ma_pa_context* (* ma_pa_context_new_proc) (ma_pa_mainloop_api* mainloop, const char* name);
  24574. typedef void (* ma_pa_context_unref_proc) (ma_pa_context* c);
  24575. typedef int (* ma_pa_context_connect_proc) (ma_pa_context* c, const char* server, ma_pa_context_flags_t flags, const ma_pa_spawn_api* api);
  24576. typedef void (* ma_pa_context_disconnect_proc) (ma_pa_context* c);
  24577. typedef void (* ma_pa_context_set_state_callback_proc) (ma_pa_context* c, ma_pa_context_notify_cb_t cb, void* userdata);
  24578. typedef ma_pa_context_state_t (* ma_pa_context_get_state_proc) (ma_pa_context* c);
  24579. typedef ma_pa_operation* (* ma_pa_context_get_sink_info_list_proc) (ma_pa_context* c, ma_pa_sink_info_cb_t cb, void* userdata);
  24580. typedef ma_pa_operation* (* ma_pa_context_get_source_info_list_proc) (ma_pa_context* c, ma_pa_source_info_cb_t cb, void* userdata);
  24581. typedef ma_pa_operation* (* ma_pa_context_get_sink_info_by_name_proc) (ma_pa_context* c, const char* name, ma_pa_sink_info_cb_t cb, void* userdata);
  24582. typedef ma_pa_operation* (* ma_pa_context_get_source_info_by_name_proc)(ma_pa_context* c, const char* name, ma_pa_source_info_cb_t cb, void* userdata);
  24583. typedef void (* ma_pa_operation_unref_proc) (ma_pa_operation* o);
  24584. typedef ma_pa_operation_state_t (* ma_pa_operation_get_state_proc) (ma_pa_operation* o);
  24585. typedef ma_pa_channel_map* (* ma_pa_channel_map_init_extend_proc) (ma_pa_channel_map* m, unsigned channels, ma_pa_channel_map_def_t def);
  24586. typedef int (* ma_pa_channel_map_valid_proc) (const ma_pa_channel_map* m);
  24587. typedef int (* ma_pa_channel_map_compatible_proc) (const ma_pa_channel_map* m, const ma_pa_sample_spec* ss);
  24588. typedef ma_pa_stream* (* ma_pa_stream_new_proc) (ma_pa_context* c, const char* name, const ma_pa_sample_spec* ss, const ma_pa_channel_map* map);
  24589. typedef void (* ma_pa_stream_unref_proc) (ma_pa_stream* s);
  24590. typedef int (* ma_pa_stream_connect_playback_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags, const ma_pa_cvolume* volume, ma_pa_stream* sync_stream);
  24591. typedef int (* ma_pa_stream_connect_record_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags);
  24592. typedef int (* ma_pa_stream_disconnect_proc) (ma_pa_stream* s);
  24593. typedef ma_pa_stream_state_t (* ma_pa_stream_get_state_proc) (ma_pa_stream* s);
  24594. typedef const ma_pa_sample_spec* (* ma_pa_stream_get_sample_spec_proc) (ma_pa_stream* s);
  24595. typedef const ma_pa_channel_map* (* ma_pa_stream_get_channel_map_proc) (ma_pa_stream* s);
  24596. typedef const ma_pa_buffer_attr* (* ma_pa_stream_get_buffer_attr_proc) (ma_pa_stream* s);
  24597. typedef ma_pa_operation* (* ma_pa_stream_set_buffer_attr_proc) (ma_pa_stream* s, const ma_pa_buffer_attr* attr, ma_pa_stream_success_cb_t cb, void* userdata);
  24598. typedef const char* (* ma_pa_stream_get_device_name_proc) (ma_pa_stream* s);
  24599. typedef void (* ma_pa_stream_set_write_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata);
  24600. typedef void (* ma_pa_stream_set_read_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata);
  24601. typedef void (* ma_pa_stream_set_suspended_callback_proc) (ma_pa_stream* s, ma_pa_stream_notify_cb_t cb, void* userdata);
  24602. typedef void (* ma_pa_stream_set_moved_callback_proc) (ma_pa_stream* s, ma_pa_stream_notify_cb_t cb, void* userdata);
  24603. typedef int (* ma_pa_stream_is_suspended_proc) (const ma_pa_stream* s);
  24604. typedef ma_pa_operation* (* ma_pa_stream_flush_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
  24605. typedef ma_pa_operation* (* ma_pa_stream_drain_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
  24606. typedef int (* ma_pa_stream_is_corked_proc) (ma_pa_stream* s);
  24607. typedef ma_pa_operation* (* ma_pa_stream_cork_proc) (ma_pa_stream* s, int b, ma_pa_stream_success_cb_t cb, void* userdata);
  24608. typedef ma_pa_operation* (* ma_pa_stream_trigger_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
  24609. typedef int (* ma_pa_stream_begin_write_proc) (ma_pa_stream* s, void** data, size_t* nbytes);
  24610. typedef int (* ma_pa_stream_write_proc) (ma_pa_stream* s, const void* data, size_t nbytes, ma_pa_free_cb_t free_cb, int64_t offset, ma_pa_seek_mode_t seek);
  24611. typedef int (* ma_pa_stream_peek_proc) (ma_pa_stream* s, const void** data, size_t* nbytes);
  24612. typedef int (* ma_pa_stream_drop_proc) (ma_pa_stream* s);
  24613. typedef size_t (* ma_pa_stream_writable_size_proc) (ma_pa_stream* s);
  24614. typedef size_t (* ma_pa_stream_readable_size_proc) (ma_pa_stream* s);
  24615. typedef struct
  24616. {
  24617. ma_uint32 count;
  24618. ma_uint32 capacity;
  24619. ma_device_info* pInfo;
  24620. } ma_pulse_device_enum_data;
  24621. static ma_result ma_result_from_pulse(int result)
  24622. {
  24623. if (result < 0) {
  24624. return MA_ERROR;
  24625. }
  24626. switch (result) {
  24627. case MA_PA_OK: return MA_SUCCESS;
  24628. case MA_PA_ERR_ACCESS: return MA_ACCESS_DENIED;
  24629. case MA_PA_ERR_INVALID: return MA_INVALID_ARGS;
  24630. case MA_PA_ERR_NOENTITY: return MA_NO_DEVICE;
  24631. default: return MA_ERROR;
  24632. }
  24633. }
  24634. #if 0
  24635. static ma_pa_sample_format_t ma_format_to_pulse(ma_format format)
  24636. {
  24637. if (ma_is_little_endian()) {
  24638. switch (format) {
  24639. case ma_format_s16: return MA_PA_SAMPLE_S16LE;
  24640. case ma_format_s24: return MA_PA_SAMPLE_S24LE;
  24641. case ma_format_s32: return MA_PA_SAMPLE_S32LE;
  24642. case ma_format_f32: return MA_PA_SAMPLE_FLOAT32LE;
  24643. default: break;
  24644. }
  24645. } else {
  24646. switch (format) {
  24647. case ma_format_s16: return MA_PA_SAMPLE_S16BE;
  24648. case ma_format_s24: return MA_PA_SAMPLE_S24BE;
  24649. case ma_format_s32: return MA_PA_SAMPLE_S32BE;
  24650. case ma_format_f32: return MA_PA_SAMPLE_FLOAT32BE;
  24651. default: break;
  24652. }
  24653. }
  24654. /* Endian agnostic. */
  24655. switch (format) {
  24656. case ma_format_u8: return MA_PA_SAMPLE_U8;
  24657. default: return MA_PA_SAMPLE_INVALID;
  24658. }
  24659. }
  24660. #endif
  24661. static ma_format ma_format_from_pulse(ma_pa_sample_format_t format)
  24662. {
  24663. if (ma_is_little_endian()) {
  24664. switch (format) {
  24665. case MA_PA_SAMPLE_S16LE: return ma_format_s16;
  24666. case MA_PA_SAMPLE_S24LE: return ma_format_s24;
  24667. case MA_PA_SAMPLE_S32LE: return ma_format_s32;
  24668. case MA_PA_SAMPLE_FLOAT32LE: return ma_format_f32;
  24669. default: break;
  24670. }
  24671. } else {
  24672. switch (format) {
  24673. case MA_PA_SAMPLE_S16BE: return ma_format_s16;
  24674. case MA_PA_SAMPLE_S24BE: return ma_format_s24;
  24675. case MA_PA_SAMPLE_S32BE: return ma_format_s32;
  24676. case MA_PA_SAMPLE_FLOAT32BE: return ma_format_f32;
  24677. default: break;
  24678. }
  24679. }
  24680. /* Endian agnostic. */
  24681. switch (format) {
  24682. case MA_PA_SAMPLE_U8: return ma_format_u8;
  24683. default: return ma_format_unknown;
  24684. }
  24685. }
  24686. static ma_channel ma_channel_position_from_pulse(ma_pa_channel_position_t position)
  24687. {
  24688. switch (position)
  24689. {
  24690. case MA_PA_CHANNEL_POSITION_INVALID: return MA_CHANNEL_NONE;
  24691. case MA_PA_CHANNEL_POSITION_MONO: return MA_CHANNEL_MONO;
  24692. case MA_PA_CHANNEL_POSITION_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
  24693. case MA_PA_CHANNEL_POSITION_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
  24694. case MA_PA_CHANNEL_POSITION_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
  24695. case MA_PA_CHANNEL_POSITION_REAR_CENTER: return MA_CHANNEL_BACK_CENTER;
  24696. case MA_PA_CHANNEL_POSITION_REAR_LEFT: return MA_CHANNEL_BACK_LEFT;
  24697. case MA_PA_CHANNEL_POSITION_REAR_RIGHT: return MA_CHANNEL_BACK_RIGHT;
  24698. case MA_PA_CHANNEL_POSITION_LFE: return MA_CHANNEL_LFE;
  24699. case MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
  24700. case MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  24701. case MA_PA_CHANNEL_POSITION_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
  24702. case MA_PA_CHANNEL_POSITION_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
  24703. case MA_PA_CHANNEL_POSITION_AUX0: return MA_CHANNEL_AUX_0;
  24704. case MA_PA_CHANNEL_POSITION_AUX1: return MA_CHANNEL_AUX_1;
  24705. case MA_PA_CHANNEL_POSITION_AUX2: return MA_CHANNEL_AUX_2;
  24706. case MA_PA_CHANNEL_POSITION_AUX3: return MA_CHANNEL_AUX_3;
  24707. case MA_PA_CHANNEL_POSITION_AUX4: return MA_CHANNEL_AUX_4;
  24708. case MA_PA_CHANNEL_POSITION_AUX5: return MA_CHANNEL_AUX_5;
  24709. case MA_PA_CHANNEL_POSITION_AUX6: return MA_CHANNEL_AUX_6;
  24710. case MA_PA_CHANNEL_POSITION_AUX7: return MA_CHANNEL_AUX_7;
  24711. case MA_PA_CHANNEL_POSITION_AUX8: return MA_CHANNEL_AUX_8;
  24712. case MA_PA_CHANNEL_POSITION_AUX9: return MA_CHANNEL_AUX_9;
  24713. case MA_PA_CHANNEL_POSITION_AUX10: return MA_CHANNEL_AUX_10;
  24714. case MA_PA_CHANNEL_POSITION_AUX11: return MA_CHANNEL_AUX_11;
  24715. case MA_PA_CHANNEL_POSITION_AUX12: return MA_CHANNEL_AUX_12;
  24716. case MA_PA_CHANNEL_POSITION_AUX13: return MA_CHANNEL_AUX_13;
  24717. case MA_PA_CHANNEL_POSITION_AUX14: return MA_CHANNEL_AUX_14;
  24718. case MA_PA_CHANNEL_POSITION_AUX15: return MA_CHANNEL_AUX_15;
  24719. case MA_PA_CHANNEL_POSITION_AUX16: return MA_CHANNEL_AUX_16;
  24720. case MA_PA_CHANNEL_POSITION_AUX17: return MA_CHANNEL_AUX_17;
  24721. case MA_PA_CHANNEL_POSITION_AUX18: return MA_CHANNEL_AUX_18;
  24722. case MA_PA_CHANNEL_POSITION_AUX19: return MA_CHANNEL_AUX_19;
  24723. case MA_PA_CHANNEL_POSITION_AUX20: return MA_CHANNEL_AUX_20;
  24724. case MA_PA_CHANNEL_POSITION_AUX21: return MA_CHANNEL_AUX_21;
  24725. case MA_PA_CHANNEL_POSITION_AUX22: return MA_CHANNEL_AUX_22;
  24726. case MA_PA_CHANNEL_POSITION_AUX23: return MA_CHANNEL_AUX_23;
  24727. case MA_PA_CHANNEL_POSITION_AUX24: return MA_CHANNEL_AUX_24;
  24728. case MA_PA_CHANNEL_POSITION_AUX25: return MA_CHANNEL_AUX_25;
  24729. case MA_PA_CHANNEL_POSITION_AUX26: return MA_CHANNEL_AUX_26;
  24730. case MA_PA_CHANNEL_POSITION_AUX27: return MA_CHANNEL_AUX_27;
  24731. case MA_PA_CHANNEL_POSITION_AUX28: return MA_CHANNEL_AUX_28;
  24732. case MA_PA_CHANNEL_POSITION_AUX29: return MA_CHANNEL_AUX_29;
  24733. case MA_PA_CHANNEL_POSITION_AUX30: return MA_CHANNEL_AUX_30;
  24734. case MA_PA_CHANNEL_POSITION_AUX31: return MA_CHANNEL_AUX_31;
  24735. case MA_PA_CHANNEL_POSITION_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
  24736. case MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
  24737. case MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
  24738. case MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
  24739. case MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
  24740. case MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
  24741. case MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
  24742. default: return MA_CHANNEL_NONE;
  24743. }
  24744. }
  24745. #if 0
  24746. static ma_pa_channel_position_t ma_channel_position_to_pulse(ma_channel position)
  24747. {
  24748. switch (position)
  24749. {
  24750. case MA_CHANNEL_NONE: return MA_PA_CHANNEL_POSITION_INVALID;
  24751. case MA_CHANNEL_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_FRONT_LEFT;
  24752. case MA_CHANNEL_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT;
  24753. case MA_CHANNEL_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_CENTER;
  24754. case MA_CHANNEL_LFE: return MA_PA_CHANNEL_POSITION_LFE;
  24755. case MA_CHANNEL_BACK_LEFT: return MA_PA_CHANNEL_POSITION_REAR_LEFT;
  24756. case MA_CHANNEL_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_REAR_RIGHT;
  24757. case MA_CHANNEL_FRONT_LEFT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;
  24758. case MA_CHANNEL_FRONT_RIGHT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
  24759. case MA_CHANNEL_BACK_CENTER: return MA_PA_CHANNEL_POSITION_REAR_CENTER;
  24760. case MA_CHANNEL_SIDE_LEFT: return MA_PA_CHANNEL_POSITION_SIDE_LEFT;
  24761. case MA_CHANNEL_SIDE_RIGHT: return MA_PA_CHANNEL_POSITION_SIDE_RIGHT;
  24762. case MA_CHANNEL_TOP_CENTER: return MA_PA_CHANNEL_POSITION_TOP_CENTER;
  24763. case MA_CHANNEL_TOP_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT;
  24764. case MA_CHANNEL_TOP_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER;
  24765. case MA_CHANNEL_TOP_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT;
  24766. case MA_CHANNEL_TOP_BACK_LEFT: return MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT;
  24767. case MA_CHANNEL_TOP_BACK_CENTER: return MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER;
  24768. case MA_CHANNEL_TOP_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT;
  24769. case MA_CHANNEL_19: return MA_PA_CHANNEL_POSITION_AUX18;
  24770. case MA_CHANNEL_20: return MA_PA_CHANNEL_POSITION_AUX19;
  24771. case MA_CHANNEL_21: return MA_PA_CHANNEL_POSITION_AUX20;
  24772. case MA_CHANNEL_22: return MA_PA_CHANNEL_POSITION_AUX21;
  24773. case MA_CHANNEL_23: return MA_PA_CHANNEL_POSITION_AUX22;
  24774. case MA_CHANNEL_24: return MA_PA_CHANNEL_POSITION_AUX23;
  24775. case MA_CHANNEL_25: return MA_PA_CHANNEL_POSITION_AUX24;
  24776. case MA_CHANNEL_26: return MA_PA_CHANNEL_POSITION_AUX25;
  24777. case MA_CHANNEL_27: return MA_PA_CHANNEL_POSITION_AUX26;
  24778. case MA_CHANNEL_28: return MA_PA_CHANNEL_POSITION_AUX27;
  24779. case MA_CHANNEL_29: return MA_PA_CHANNEL_POSITION_AUX28;
  24780. case MA_CHANNEL_30: return MA_PA_CHANNEL_POSITION_AUX29;
  24781. case MA_CHANNEL_31: return MA_PA_CHANNEL_POSITION_AUX30;
  24782. case MA_CHANNEL_32: return MA_PA_CHANNEL_POSITION_AUX31;
  24783. default: return (ma_pa_channel_position_t)position;
  24784. }
  24785. }
  24786. #endif
  24787. static ma_result ma_wait_for_operation__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_pa_operation* pOP)
  24788. {
  24789. int resultPA;
  24790. ma_pa_operation_state_t state;
  24791. MA_ASSERT(pContext != NULL);
  24792. MA_ASSERT(pOP != NULL);
  24793. for (;;) {
  24794. state = ((ma_pa_operation_get_state_proc)pContext->pulse.pa_operation_get_state)(pOP);
  24795. if (state != MA_PA_OPERATION_RUNNING) {
  24796. break; /* Done. */
  24797. }
  24798. resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL);
  24799. if (resultPA < 0) {
  24800. return ma_result_from_pulse(resultPA);
  24801. }
  24802. }
  24803. return MA_SUCCESS;
  24804. }
  24805. static ma_result ma_wait_for_operation_and_unref__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_pa_operation* pOP)
  24806. {
  24807. ma_result result;
  24808. if (pOP == NULL) {
  24809. return MA_INVALID_ARGS;
  24810. }
  24811. result = ma_wait_for_operation__pulse(pContext, pMainLoop, pOP);
  24812. ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
  24813. return result;
  24814. }
  24815. static ma_result ma_wait_for_pa_context_to_connect__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_ptr pPulseContext)
  24816. {
  24817. int resultPA;
  24818. ma_pa_context_state_t state;
  24819. for (;;) {
  24820. state = ((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)((ma_pa_context*)pPulseContext);
  24821. if (state == MA_PA_CONTEXT_READY) {
  24822. break; /* Done. */
  24823. }
  24824. if (state == MA_PA_CONTEXT_FAILED || state == MA_PA_CONTEXT_TERMINATED) {
  24825. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio context.");
  24826. return MA_ERROR;
  24827. }
  24828. resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL);
  24829. if (resultPA < 0) {
  24830. return ma_result_from_pulse(resultPA);
  24831. }
  24832. }
  24833. /* Should never get here. */
  24834. return MA_SUCCESS;
  24835. }
  24836. static ma_result ma_wait_for_pa_stream_to_connect__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_ptr pStream)
  24837. {
  24838. int resultPA;
  24839. ma_pa_stream_state_t state;
  24840. for (;;) {
  24841. state = ((ma_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)((ma_pa_stream*)pStream);
  24842. if (state == MA_PA_STREAM_READY) {
  24843. break; /* Done. */
  24844. }
  24845. if (state == MA_PA_STREAM_FAILED || state == MA_PA_STREAM_TERMINATED) {
  24846. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio stream.");
  24847. return MA_ERROR;
  24848. }
  24849. resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL);
  24850. if (resultPA < 0) {
  24851. return ma_result_from_pulse(resultPA);
  24852. }
  24853. }
  24854. return MA_SUCCESS;
  24855. }
  24856. static ma_result ma_init_pa_mainloop_and_pa_context__pulse(ma_context* pContext, const char* pApplicationName, const char* pServerName, ma_bool32 tryAutoSpawn, ma_ptr* ppMainLoop, ma_ptr* ppPulseContext)
  24857. {
  24858. ma_result result;
  24859. ma_ptr pMainLoop;
  24860. ma_ptr pPulseContext;
  24861. MA_ASSERT(ppMainLoop != NULL);
  24862. MA_ASSERT(ppPulseContext != NULL);
  24863. /* The PulseAudio context maps well to miniaudio's notion of a context. The pa_context object will be initialized as part of the ma_context. */
  24864. pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)();
  24865. if (pMainLoop == NULL) {
  24866. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create mainloop.");
  24867. return MA_FAILED_TO_INIT_BACKEND;
  24868. }
  24869. pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)((ma_pa_mainloop*)pMainLoop), pApplicationName);
  24870. if (pPulseContext == NULL) {
  24871. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio context.");
  24872. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop));
  24873. return MA_FAILED_TO_INIT_BACKEND;
  24874. }
  24875. /* Now we need to connect to the context. Everything is asynchronous so we need to wait for it to connect before returning. */
  24876. result = ma_result_from_pulse(((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)((ma_pa_context*)pPulseContext, pServerName, (tryAutoSpawn) ? 0 : MA_PA_CONTEXT_NOAUTOSPAWN, NULL));
  24877. if (result != MA_SUCCESS) {
  24878. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio context.");
  24879. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop));
  24880. return result;
  24881. }
  24882. /* Since ma_context_init() runs synchronously we need to wait for the PulseAudio context to connect before we return. */
  24883. result = ma_wait_for_pa_context_to_connect__pulse(pContext, pMainLoop, pPulseContext);
  24884. if (result != MA_SUCCESS) {
  24885. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Waiting for connection failed.");
  24886. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop));
  24887. return result;
  24888. }
  24889. *ppMainLoop = pMainLoop;
  24890. *ppPulseContext = pPulseContext;
  24891. return MA_SUCCESS;
  24892. }
  24893. static void ma_device_sink_info_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
  24894. {
  24895. ma_pa_sink_info* pInfoOut;
  24896. if (endOfList > 0) {
  24897. return;
  24898. }
  24899. /*
  24900. There has been a report that indicates that pInfo can be null which results
  24901. in a null pointer dereference below. We'll check for this for safety.
  24902. */
  24903. if (pInfo == NULL) {
  24904. return;
  24905. }
  24906. pInfoOut = (ma_pa_sink_info*)pUserData;
  24907. MA_ASSERT(pInfoOut != NULL);
  24908. *pInfoOut = *pInfo;
  24909. (void)pPulseContext; /* Unused. */
  24910. }
  24911. static void ma_device_source_info_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
  24912. {
  24913. ma_pa_source_info* pInfoOut;
  24914. if (endOfList > 0) {
  24915. return;
  24916. }
  24917. /*
  24918. There has been a report that indicates that pInfo can be null which results
  24919. in a null pointer dereference below. We'll check for this for safety.
  24920. */
  24921. if (pInfo == NULL) {
  24922. return;
  24923. }
  24924. pInfoOut = (ma_pa_source_info*)pUserData;
  24925. MA_ASSERT(pInfoOut != NULL);
  24926. *pInfoOut = *pInfo;
  24927. (void)pPulseContext; /* Unused. */
  24928. }
  24929. #if 0
  24930. static void ma_device_sink_name_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
  24931. {
  24932. ma_device* pDevice;
  24933. if (endOfList > 0) {
  24934. return;
  24935. }
  24936. pDevice = (ma_device*)pUserData;
  24937. MA_ASSERT(pDevice != NULL);
  24938. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), pInfo->description, (size_t)-1);
  24939. (void)pPulseContext; /* Unused. */
  24940. }
  24941. static void ma_device_source_name_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
  24942. {
  24943. ma_device* pDevice;
  24944. if (endOfList > 0) {
  24945. return;
  24946. }
  24947. pDevice = (ma_device*)pUserData;
  24948. MA_ASSERT(pDevice != NULL);
  24949. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), pInfo->description, (size_t)-1);
  24950. (void)pPulseContext; /* Unused. */
  24951. }
  24952. #endif
  24953. static ma_result ma_context_get_sink_info__pulse(ma_context* pContext, const char* pDeviceName, ma_pa_sink_info* pSinkInfo)
  24954. {
  24955. ma_pa_operation* pOP;
  24956. pOP = ((ma_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((ma_pa_context*)pContext->pulse.pPulseContext, pDeviceName, ma_device_sink_info_callback, pSinkInfo);
  24957. if (pOP == NULL) {
  24958. return MA_ERROR;
  24959. }
  24960. return ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  24961. }
  24962. static ma_result ma_context_get_source_info__pulse(ma_context* pContext, const char* pDeviceName, ma_pa_source_info* pSourceInfo)
  24963. {
  24964. ma_pa_operation* pOP;
  24965. pOP = ((ma_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((ma_pa_context*)pContext->pulse.pPulseContext, pDeviceName, ma_device_source_info_callback, pSourceInfo);
  24966. if (pOP == NULL) {
  24967. return MA_ERROR;
  24968. }
  24969. return ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  24970. }
  24971. static ma_result ma_context_get_default_device_index__pulse(ma_context* pContext, ma_device_type deviceType, ma_uint32* pIndex)
  24972. {
  24973. ma_result result;
  24974. MA_ASSERT(pContext != NULL);
  24975. MA_ASSERT(pIndex != NULL);
  24976. if (pIndex != NULL) {
  24977. *pIndex = (ma_uint32)-1;
  24978. }
  24979. if (deviceType == ma_device_type_playback) {
  24980. ma_pa_sink_info sinkInfo;
  24981. result = ma_context_get_sink_info__pulse(pContext, NULL, &sinkInfo);
  24982. if (result != MA_SUCCESS) {
  24983. return result;
  24984. }
  24985. if (pIndex != NULL) {
  24986. *pIndex = sinkInfo.index;
  24987. }
  24988. }
  24989. if (deviceType == ma_device_type_capture) {
  24990. ma_pa_source_info sourceInfo;
  24991. result = ma_context_get_source_info__pulse(pContext, NULL, &sourceInfo);
  24992. if (result != MA_SUCCESS) {
  24993. return result;
  24994. }
  24995. if (pIndex != NULL) {
  24996. *pIndex = sourceInfo.index;
  24997. }
  24998. }
  24999. return MA_SUCCESS;
  25000. }
  25001. typedef struct
  25002. {
  25003. ma_context* pContext;
  25004. ma_enum_devices_callback_proc callback;
  25005. void* pUserData;
  25006. ma_bool32 isTerminated;
  25007. ma_uint32 defaultDeviceIndexPlayback;
  25008. ma_uint32 defaultDeviceIndexCapture;
  25009. } ma_context_enumerate_devices_callback_data__pulse;
  25010. static void ma_context_enumerate_devices_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pSinkInfo, int endOfList, void* pUserData)
  25011. {
  25012. ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData;
  25013. ma_device_info deviceInfo;
  25014. MA_ASSERT(pData != NULL);
  25015. if (endOfList || pData->isTerminated) {
  25016. return;
  25017. }
  25018. MA_ZERO_OBJECT(&deviceInfo);
  25019. /* The name from PulseAudio is the ID for miniaudio. */
  25020. if (pSinkInfo->name != NULL) {
  25021. ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSinkInfo->name, (size_t)-1);
  25022. }
  25023. /* The description from PulseAudio is the name for miniaudio. */
  25024. if (pSinkInfo->description != NULL) {
  25025. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSinkInfo->description, (size_t)-1);
  25026. }
  25027. if (pSinkInfo->index == pData->defaultDeviceIndexPlayback) {
  25028. deviceInfo.isDefault = MA_TRUE;
  25029. }
  25030. pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_playback, &deviceInfo, pData->pUserData);
  25031. (void)pPulseContext; /* Unused. */
  25032. }
  25033. static void ma_context_enumerate_devices_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pSourceInfo, int endOfList, void* pUserData)
  25034. {
  25035. ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData;
  25036. ma_device_info deviceInfo;
  25037. MA_ASSERT(pData != NULL);
  25038. if (endOfList || pData->isTerminated) {
  25039. return;
  25040. }
  25041. MA_ZERO_OBJECT(&deviceInfo);
  25042. /* The name from PulseAudio is the ID for miniaudio. */
  25043. if (pSourceInfo->name != NULL) {
  25044. ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSourceInfo->name, (size_t)-1);
  25045. }
  25046. /* The description from PulseAudio is the name for miniaudio. */
  25047. if (pSourceInfo->description != NULL) {
  25048. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSourceInfo->description, (size_t)-1);
  25049. }
  25050. if (pSourceInfo->index == pData->defaultDeviceIndexCapture) {
  25051. deviceInfo.isDefault = MA_TRUE;
  25052. }
  25053. pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_capture, &deviceInfo, pData->pUserData);
  25054. (void)pPulseContext; /* Unused. */
  25055. }
  25056. static ma_result ma_context_enumerate_devices__pulse(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  25057. {
  25058. ma_result result = MA_SUCCESS;
  25059. ma_context_enumerate_devices_callback_data__pulse callbackData;
  25060. ma_pa_operation* pOP = NULL;
  25061. MA_ASSERT(pContext != NULL);
  25062. MA_ASSERT(callback != NULL);
  25063. callbackData.pContext = pContext;
  25064. callbackData.callback = callback;
  25065. callbackData.pUserData = pUserData;
  25066. callbackData.isTerminated = MA_FALSE;
  25067. callbackData.defaultDeviceIndexPlayback = (ma_uint32)-1;
  25068. callbackData.defaultDeviceIndexCapture = (ma_uint32)-1;
  25069. /* We need to get the index of the default devices. */
  25070. ma_context_get_default_device_index__pulse(pContext, ma_device_type_playback, &callbackData.defaultDeviceIndexPlayback);
  25071. ma_context_get_default_device_index__pulse(pContext, ma_device_type_capture, &callbackData.defaultDeviceIndexCapture);
  25072. /* Playback. */
  25073. if (!callbackData.isTerminated) {
  25074. pOP = ((ma_pa_context_get_sink_info_list_proc)pContext->pulse.pa_context_get_sink_info_list)((ma_pa_context*)(pContext->pulse.pPulseContext), ma_context_enumerate_devices_sink_callback__pulse, &callbackData);
  25075. if (pOP == NULL) {
  25076. result = MA_ERROR;
  25077. goto done;
  25078. }
  25079. result = ma_wait_for_operation__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  25080. ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
  25081. if (result != MA_SUCCESS) {
  25082. goto done;
  25083. }
  25084. }
  25085. /* Capture. */
  25086. if (!callbackData.isTerminated) {
  25087. pOP = ((ma_pa_context_get_source_info_list_proc)pContext->pulse.pa_context_get_source_info_list)((ma_pa_context*)(pContext->pulse.pPulseContext), ma_context_enumerate_devices_source_callback__pulse, &callbackData);
  25088. if (pOP == NULL) {
  25089. result = MA_ERROR;
  25090. goto done;
  25091. }
  25092. result = ma_wait_for_operation__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  25093. ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
  25094. if (result != MA_SUCCESS) {
  25095. goto done;
  25096. }
  25097. }
  25098. done:
  25099. return result;
  25100. }
  25101. typedef struct
  25102. {
  25103. ma_device_info* pDeviceInfo;
  25104. ma_uint32 defaultDeviceIndex;
  25105. ma_bool32 foundDevice;
  25106. } ma_context_get_device_info_callback_data__pulse;
  25107. static void ma_context_get_device_info_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
  25108. {
  25109. ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData;
  25110. if (endOfList > 0) {
  25111. return;
  25112. }
  25113. MA_ASSERT(pData != NULL);
  25114. pData->foundDevice = MA_TRUE;
  25115. if (pInfo->name != NULL) {
  25116. ma_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1);
  25117. }
  25118. if (pInfo->description != NULL) {
  25119. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1);
  25120. }
  25121. /*
  25122. We're just reporting a single data format here. I think technically PulseAudio might support
  25123. all formats, but I don't trust that PulseAudio will do *anything* right, so I'm just going to
  25124. report the "native" device format.
  25125. */
  25126. pData->pDeviceInfo->nativeDataFormats[0].format = ma_format_from_pulse(pInfo->sample_spec.format);
  25127. pData->pDeviceInfo->nativeDataFormats[0].channels = pInfo->sample_spec.channels;
  25128. pData->pDeviceInfo->nativeDataFormats[0].sampleRate = pInfo->sample_spec.rate;
  25129. pData->pDeviceInfo->nativeDataFormats[0].flags = 0;
  25130. pData->pDeviceInfo->nativeDataFormatCount = 1;
  25131. if (pData->defaultDeviceIndex == pInfo->index) {
  25132. pData->pDeviceInfo->isDefault = MA_TRUE;
  25133. }
  25134. (void)pPulseContext; /* Unused. */
  25135. }
  25136. static void ma_context_get_device_info_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
  25137. {
  25138. ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData;
  25139. if (endOfList > 0) {
  25140. return;
  25141. }
  25142. MA_ASSERT(pData != NULL);
  25143. pData->foundDevice = MA_TRUE;
  25144. if (pInfo->name != NULL) {
  25145. ma_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1);
  25146. }
  25147. if (pInfo->description != NULL) {
  25148. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1);
  25149. }
  25150. /*
  25151. We're just reporting a single data format here. I think technically PulseAudio might support
  25152. all formats, but I don't trust that PulseAudio will do *anything* right, so I'm just going to
  25153. report the "native" device format.
  25154. */
  25155. pData->pDeviceInfo->nativeDataFormats[0].format = ma_format_from_pulse(pInfo->sample_spec.format);
  25156. pData->pDeviceInfo->nativeDataFormats[0].channels = pInfo->sample_spec.channels;
  25157. pData->pDeviceInfo->nativeDataFormats[0].sampleRate = pInfo->sample_spec.rate;
  25158. pData->pDeviceInfo->nativeDataFormats[0].flags = 0;
  25159. pData->pDeviceInfo->nativeDataFormatCount = 1;
  25160. if (pData->defaultDeviceIndex == pInfo->index) {
  25161. pData->pDeviceInfo->isDefault = MA_TRUE;
  25162. }
  25163. (void)pPulseContext; /* Unused. */
  25164. }
  25165. static ma_result ma_context_get_device_info__pulse(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  25166. {
  25167. ma_result result = MA_SUCCESS;
  25168. ma_context_get_device_info_callback_data__pulse callbackData;
  25169. ma_pa_operation* pOP = NULL;
  25170. const char* pDeviceName = NULL;
  25171. MA_ASSERT(pContext != NULL);
  25172. callbackData.pDeviceInfo = pDeviceInfo;
  25173. callbackData.foundDevice = MA_FALSE;
  25174. if (pDeviceID != NULL) {
  25175. pDeviceName = pDeviceID->pulse;
  25176. } else {
  25177. pDeviceName = NULL;
  25178. }
  25179. result = ma_context_get_default_device_index__pulse(pContext, deviceType, &callbackData.defaultDeviceIndex);
  25180. if (deviceType == ma_device_type_playback) {
  25181. pOP = ((ma_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((ma_pa_context*)(pContext->pulse.pPulseContext), pDeviceName, ma_context_get_device_info_sink_callback__pulse, &callbackData);
  25182. } else {
  25183. pOP = ((ma_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((ma_pa_context*)(pContext->pulse.pPulseContext), pDeviceName, ma_context_get_device_info_source_callback__pulse, &callbackData);
  25184. }
  25185. if (pOP != NULL) {
  25186. ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  25187. } else {
  25188. result = MA_ERROR;
  25189. goto done;
  25190. }
  25191. if (!callbackData.foundDevice) {
  25192. result = MA_NO_DEVICE;
  25193. goto done;
  25194. }
  25195. done:
  25196. return result;
  25197. }
  25198. static ma_result ma_device_uninit__pulse(ma_device* pDevice)
  25199. {
  25200. ma_context* pContext;
  25201. MA_ASSERT(pDevice != NULL);
  25202. pContext = pDevice->pContext;
  25203. MA_ASSERT(pContext != NULL);
  25204. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25205. ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25206. ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25207. }
  25208. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25209. ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25210. ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25211. }
  25212. if (pDevice->type == ma_device_type_duplex) {
  25213. ma_duplex_rb_uninit(&pDevice->duplexRB);
  25214. }
  25215. ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pDevice->pulse.pPulseContext);
  25216. ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pDevice->pulse.pPulseContext);
  25217. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
  25218. return MA_SUCCESS;
  25219. }
  25220. static ma_pa_buffer_attr ma_device__pa_buffer_attr_new(ma_uint32 periodSizeInFrames, ma_uint32 periods, const ma_pa_sample_spec* ss)
  25221. {
  25222. ma_pa_buffer_attr attr;
  25223. attr.maxlength = periodSizeInFrames * periods * ma_get_bytes_per_frame(ma_format_from_pulse(ss->format), ss->channels);
  25224. attr.tlength = attr.maxlength / periods;
  25225. attr.prebuf = (ma_uint32)-1;
  25226. attr.minreq = (ma_uint32)-1;
  25227. attr.fragsize = attr.maxlength / periods;
  25228. return attr;
  25229. }
  25230. static ma_pa_stream* ma_device__pa_stream_new__pulse(ma_device* pDevice, const char* pStreamName, const ma_pa_sample_spec* ss, const ma_pa_channel_map* cmap)
  25231. {
  25232. static int g_StreamCounter = 0;
  25233. char actualStreamName[256];
  25234. if (pStreamName != NULL) {
  25235. ma_strncpy_s(actualStreamName, sizeof(actualStreamName), pStreamName, (size_t)-1);
  25236. } else {
  25237. ma_strcpy_s(actualStreamName, sizeof(actualStreamName), "miniaudio:");
  25238. ma_itoa_s(g_StreamCounter, actualStreamName + 8, sizeof(actualStreamName)-8, 10); /* 8 = strlen("miniaudio:") */
  25239. }
  25240. g_StreamCounter += 1;
  25241. return ((ma_pa_stream_new_proc)pDevice->pContext->pulse.pa_stream_new)((ma_pa_context*)pDevice->pulse.pPulseContext, actualStreamName, ss, cmap);
  25242. }
  25243. static void ma_device_on_read__pulse(ma_pa_stream* pStream, size_t byteCount, void* pUserData)
  25244. {
  25245. ma_device* pDevice = (ma_device*)pUserData;
  25246. ma_uint32 bpf;
  25247. ma_uint32 deviceState;
  25248. ma_uint64 frameCount;
  25249. ma_uint64 framesProcessed;
  25250. MA_ASSERT(pDevice != NULL);
  25251. /*
  25252. Don't do anything if the device isn't initialized yet. Yes, this can happen because PulseAudio
  25253. can fire this callback before the stream has even started. Ridiculous.
  25254. */
  25255. deviceState = ma_device_get_state(pDevice);
  25256. if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) {
  25257. return;
  25258. }
  25259. bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  25260. MA_ASSERT(bpf > 0);
  25261. frameCount = byteCount / bpf;
  25262. framesProcessed = 0;
  25263. while (ma_device_get_state(pDevice) == ma_device_state_started && framesProcessed < frameCount) {
  25264. const void* pMappedPCMFrames;
  25265. size_t bytesMapped;
  25266. ma_uint64 framesMapped;
  25267. int pulseResult = ((ma_pa_stream_peek_proc)pDevice->pContext->pulse.pa_stream_peek)(pStream, &pMappedPCMFrames, &bytesMapped);
  25268. if (pulseResult < 0) {
  25269. break; /* Failed to map. Abort. */
  25270. }
  25271. framesMapped = bytesMapped / bpf;
  25272. if (framesMapped > 0) {
  25273. if (pMappedPCMFrames != NULL) {
  25274. ma_device_handle_backend_data_callback(pDevice, NULL, pMappedPCMFrames, framesMapped);
  25275. } else {
  25276. /* It's a hole. */
  25277. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[PulseAudio] ma_device_on_read__pulse: Hole.\n");
  25278. }
  25279. pulseResult = ((ma_pa_stream_drop_proc)pDevice->pContext->pulse.pa_stream_drop)(pStream);
  25280. if (pulseResult < 0) {
  25281. break; /* Failed to drop the buffer. */
  25282. }
  25283. framesProcessed += framesMapped;
  25284. } else {
  25285. /* Nothing was mapped. Just abort. */
  25286. break;
  25287. }
  25288. }
  25289. }
  25290. static ma_result ma_device_write_to_stream__pulse(ma_device* pDevice, ma_pa_stream* pStream, ma_uint64* pFramesProcessed)
  25291. {
  25292. ma_result result = MA_SUCCESS;
  25293. ma_uint64 framesProcessed = 0;
  25294. size_t bytesMapped;
  25295. ma_uint32 bpf;
  25296. ma_uint32 deviceState;
  25297. MA_ASSERT(pDevice != NULL);
  25298. MA_ASSERT(pStream != NULL);
  25299. bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  25300. MA_ASSERT(bpf > 0);
  25301. deviceState = ma_device_get_state(pDevice);
  25302. bytesMapped = ((ma_pa_stream_writable_size_proc)pDevice->pContext->pulse.pa_stream_writable_size)(pStream);
  25303. if (bytesMapped != (size_t)-1) {
  25304. if (bytesMapped > 0) {
  25305. ma_uint64 framesMapped;
  25306. void* pMappedPCMFrames;
  25307. int pulseResult = ((ma_pa_stream_begin_write_proc)pDevice->pContext->pulse.pa_stream_begin_write)(pStream, &pMappedPCMFrames, &bytesMapped);
  25308. if (pulseResult < 0) {
  25309. result = ma_result_from_pulse(pulseResult);
  25310. goto done;
  25311. }
  25312. framesMapped = bytesMapped / bpf;
  25313. if (deviceState == ma_device_state_started || deviceState == ma_device_state_starting) { /* Check for starting state just in case this is being used to do the initial fill. */
  25314. ma_device_handle_backend_data_callback(pDevice, pMappedPCMFrames, NULL, framesMapped);
  25315. } else {
  25316. /* Device is not started. Write silence. */
  25317. ma_silence_pcm_frames(pMappedPCMFrames, framesMapped, pDevice->playback.format, pDevice->playback.channels);
  25318. }
  25319. pulseResult = ((ma_pa_stream_write_proc)pDevice->pContext->pulse.pa_stream_write)(pStream, pMappedPCMFrames, bytesMapped, NULL, 0, MA_PA_SEEK_RELATIVE);
  25320. if (pulseResult < 0) {
  25321. result = ma_result_from_pulse(pulseResult);
  25322. goto done; /* Failed to write data to stream. */
  25323. }
  25324. framesProcessed += framesMapped;
  25325. } else {
  25326. result = MA_SUCCESS; /* No data available for writing. */
  25327. goto done;
  25328. }
  25329. } else {
  25330. result = MA_ERROR; /* Failed to retrieve the writable size. Abort. */
  25331. goto done;
  25332. }
  25333. done:
  25334. if (pFramesProcessed != NULL) {
  25335. *pFramesProcessed = framesProcessed;
  25336. }
  25337. return result;
  25338. }
  25339. static void ma_device_on_write__pulse(ma_pa_stream* pStream, size_t byteCount, void* pUserData)
  25340. {
  25341. ma_device* pDevice = (ma_device*)pUserData;
  25342. ma_uint32 bpf;
  25343. ma_uint64 frameCount;
  25344. ma_uint64 framesProcessed;
  25345. ma_uint32 deviceState;
  25346. ma_result result;
  25347. MA_ASSERT(pDevice != NULL);
  25348. /*
  25349. Don't do anything if the device isn't initialized yet. Yes, this can happen because PulseAudio
  25350. can fire this callback before the stream has even started. Ridiculous.
  25351. */
  25352. deviceState = ma_device_get_state(pDevice);
  25353. if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) {
  25354. return;
  25355. }
  25356. bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  25357. MA_ASSERT(bpf > 0);
  25358. frameCount = byteCount / bpf;
  25359. framesProcessed = 0;
  25360. while (framesProcessed < frameCount) {
  25361. ma_uint64 framesProcessedThisIteration;
  25362. /* Don't keep trying to process frames if the device isn't started. */
  25363. deviceState = ma_device_get_state(pDevice);
  25364. if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) {
  25365. break;
  25366. }
  25367. result = ma_device_write_to_stream__pulse(pDevice, pStream, &framesProcessedThisIteration);
  25368. if (result != MA_SUCCESS) {
  25369. break;
  25370. }
  25371. framesProcessed += framesProcessedThisIteration;
  25372. }
  25373. }
  25374. static void ma_device_on_suspended__pulse(ma_pa_stream* pStream, void* pUserData)
  25375. {
  25376. ma_device* pDevice = (ma_device*)pUserData;
  25377. int suspended;
  25378. (void)pStream;
  25379. suspended = ((ma_pa_stream_is_suspended_proc)pDevice->pContext->pulse.pa_stream_is_suspended)(pStream);
  25380. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. pa_stream_is_suspended() returned %d.\n", suspended);
  25381. if (suspended < 0) {
  25382. return;
  25383. }
  25384. if (suspended == 1) {
  25385. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. Suspended.\n");
  25386. ma_device__on_notification_stopped(pDevice);
  25387. } else {
  25388. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. Resumed.\n");
  25389. ma_device__on_notification_started(pDevice);
  25390. }
  25391. }
  25392. static void ma_device_on_rerouted__pulse(ma_pa_stream* pStream, void* pUserData)
  25393. {
  25394. ma_device* pDevice = (ma_device*)pUserData;
  25395. (void)pStream;
  25396. (void)pUserData;
  25397. ma_device__on_notification_rerouted(pDevice);
  25398. }
  25399. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__pulse(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  25400. {
  25401. /*
  25402. There have been reports from users where buffers of < ~20ms result glitches when running through
  25403. PipeWire. To work around this we're going to have to use a different default buffer size.
  25404. */
  25405. const ma_uint32 defaultPeriodSizeInMilliseconds_LowLatency = 25;
  25406. const ma_uint32 defaultPeriodSizeInMilliseconds_Conservative = MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE;
  25407. MA_ASSERT(nativeSampleRate != 0);
  25408. if (pDescriptor->periodSizeInFrames == 0) {
  25409. if (pDescriptor->periodSizeInMilliseconds == 0) {
  25410. if (performanceProfile == ma_performance_profile_low_latency) {
  25411. return ma_calculate_buffer_size_in_frames_from_milliseconds(defaultPeriodSizeInMilliseconds_LowLatency, nativeSampleRate);
  25412. } else {
  25413. return ma_calculate_buffer_size_in_frames_from_milliseconds(defaultPeriodSizeInMilliseconds_Conservative, nativeSampleRate);
  25414. }
  25415. } else {
  25416. return ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate);
  25417. }
  25418. } else {
  25419. return pDescriptor->periodSizeInFrames;
  25420. }
  25421. }
  25422. static ma_result ma_device_init__pulse(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  25423. {
  25424. /*
  25425. Notes for PulseAudio:
  25426. - We're always using native format/channels/rate regardless of whether or not PulseAudio
  25427. supports the format directly through their own data conversion system. I'm doing this to
  25428. reduce as much variability from the PulseAudio side as possible because it's seems to be
  25429. extremely unreliable at everything it does.
  25430. - When both the period size in frames and milliseconds are 0, we default to miniaudio's
  25431. default buffer sizes rather than leaving it up to PulseAudio because I don't trust
  25432. PulseAudio to give us any kind of reasonable latency by default.
  25433. - Do not ever, *ever* forget to use MA_PA_STREAM_ADJUST_LATENCY. If you don't specify this
  25434. flag, capture mode will just not work properly until you open another PulseAudio app.
  25435. */
  25436. ma_result result = MA_SUCCESS;
  25437. int error = 0;
  25438. const char* devPlayback = NULL;
  25439. const char* devCapture = NULL;
  25440. ma_format format = ma_format_unknown;
  25441. ma_uint32 channels = 0;
  25442. ma_uint32 sampleRate = 0;
  25443. ma_pa_sink_info sinkInfo;
  25444. ma_pa_source_info sourceInfo;
  25445. ma_pa_sample_spec ss;
  25446. ma_pa_channel_map cmap;
  25447. ma_pa_buffer_attr attr;
  25448. const ma_pa_sample_spec* pActualSS = NULL;
  25449. const ma_pa_buffer_attr* pActualAttr = NULL;
  25450. ma_uint32 iChannel;
  25451. ma_pa_stream_flags_t streamFlags;
  25452. MA_ASSERT(pDevice != NULL);
  25453. MA_ZERO_OBJECT(&pDevice->pulse);
  25454. if (pConfig->deviceType == ma_device_type_loopback) {
  25455. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  25456. }
  25457. /* No exclusive mode with the PulseAudio backend. */
  25458. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) ||
  25459. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) {
  25460. return MA_SHARE_MODE_NOT_SUPPORTED;
  25461. }
  25462. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  25463. if (pDescriptorPlayback->pDeviceID != NULL) {
  25464. devPlayback = pDescriptorPlayback->pDeviceID->pulse;
  25465. }
  25466. format = pDescriptorPlayback->format;
  25467. channels = pDescriptorPlayback->channels;
  25468. sampleRate = pDescriptorPlayback->sampleRate;
  25469. }
  25470. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  25471. if (pDescriptorCapture->pDeviceID != NULL) {
  25472. devCapture = pDescriptorCapture->pDeviceID->pulse;
  25473. }
  25474. format = pDescriptorCapture->format;
  25475. channels = pDescriptorCapture->channels;
  25476. sampleRate = pDescriptorCapture->sampleRate;
  25477. }
  25478. result = ma_init_pa_mainloop_and_pa_context__pulse(pDevice->pContext, pDevice->pContext->pulse.pApplicationName, pDevice->pContext->pulse.pServerName, MA_FALSE, &pDevice->pulse.pMainLoop, &pDevice->pulse.pPulseContext);
  25479. if (result != MA_SUCCESS) {
  25480. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to initialize PA mainloop and context for device.\n");
  25481. return result;
  25482. }
  25483. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  25484. result = ma_context_get_source_info__pulse(pDevice->pContext, devCapture, &sourceInfo);
  25485. if (result != MA_SUCCESS) {
  25486. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve source info for capture device.");
  25487. goto on_error0;
  25488. }
  25489. ss = sourceInfo.sample_spec;
  25490. cmap = sourceInfo.channel_map;
  25491. /* Use the requested channel count if we have one. */
  25492. if (pDescriptorCapture->channels != 0) {
  25493. ss.channels = pDescriptorCapture->channels;
  25494. }
  25495. /* Use a default channel map. */
  25496. ((ma_pa_channel_map_init_extend_proc)pDevice->pContext->pulse.pa_channel_map_init_extend)(&cmap, ss.channels, MA_PA_CHANNEL_MAP_DEFAULT);
  25497. /* Use the requested sample rate if one was specified. */
  25498. if (pDescriptorCapture->sampleRate != 0) {
  25499. ss.rate = pDescriptorCapture->sampleRate;
  25500. }
  25501. if (ma_format_from_pulse(ss.format) == ma_format_unknown) {
  25502. if (ma_is_little_endian()) {
  25503. ss.format = MA_PA_SAMPLE_FLOAT32LE;
  25504. } else {
  25505. ss.format = MA_PA_SAMPLE_FLOAT32BE;
  25506. }
  25507. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.format not supported by miniaudio. Defaulting to PA_SAMPLE_FLOAT32.\n");
  25508. }
  25509. if (ss.rate == 0) {
  25510. ss.rate = MA_DEFAULT_SAMPLE_RATE;
  25511. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.rate = 0. Defaulting to %d.\n", ss.rate);
  25512. }
  25513. if (ss.channels == 0) {
  25514. ss.channels = MA_DEFAULT_CHANNELS;
  25515. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels);
  25516. }
  25517. /* We now have enough information to calculate our actual period size in frames. */
  25518. pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorCapture, ss.rate, pConfig->performanceProfile);
  25519. attr = ma_device__pa_buffer_attr_new(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->periodCount, &ss);
  25520. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Capture attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; periodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDescriptorCapture->periodSizeInFrames);
  25521. pDevice->pulse.pStreamCapture = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNameCapture, &ss, &cmap);
  25522. if (pDevice->pulse.pStreamCapture == NULL) {
  25523. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio capture stream.\n");
  25524. result = MA_ERROR;
  25525. goto on_error0;
  25526. }
  25527. /* The callback needs to be set before connecting the stream. */
  25528. ((ma_pa_stream_set_read_callback_proc)pDevice->pContext->pulse.pa_stream_set_read_callback)((ma_pa_stream*)pDevice->pulse.pStreamCapture, ma_device_on_read__pulse, pDevice);
  25529. /* State callback for checking when the device has been corked. */
  25530. ((ma_pa_stream_set_suspended_callback_proc)pDevice->pContext->pulse.pa_stream_set_suspended_callback)((ma_pa_stream*)pDevice->pulse.pStreamCapture, ma_device_on_suspended__pulse, pDevice);
  25531. /* Rerouting notification. */
  25532. ((ma_pa_stream_set_moved_callback_proc)pDevice->pContext->pulse.pa_stream_set_moved_callback)((ma_pa_stream*)pDevice->pulse.pStreamCapture, ma_device_on_rerouted__pulse, pDevice);
  25533. /* Connect after we've got all of our internal state set up. */
  25534. streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_ADJUST_LATENCY | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS;
  25535. if (devCapture != NULL) {
  25536. streamFlags |= MA_PA_STREAM_DONT_MOVE;
  25537. }
  25538. error = ((ma_pa_stream_connect_record_proc)pDevice->pContext->pulse.pa_stream_connect_record)((ma_pa_stream*)pDevice->pulse.pStreamCapture, devCapture, &attr, streamFlags);
  25539. if (error != MA_PA_OK) {
  25540. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio capture stream.");
  25541. result = ma_result_from_pulse(error);
  25542. goto on_error1;
  25543. }
  25544. result = ma_wait_for_pa_stream_to_connect__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, (ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25545. if (result != MA_SUCCESS) {
  25546. goto on_error2;
  25547. }
  25548. /* Internal format. */
  25549. pActualSS = ((ma_pa_stream_get_sample_spec_proc)pDevice->pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25550. if (pActualSS != NULL) {
  25551. ss = *pActualSS;
  25552. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Capture sample spec: format=%s, channels=%d, rate=%d\n", ma_get_format_name(ma_format_from_pulse(ss.format)), ss.channels, ss.rate);
  25553. } else {
  25554. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Failed to retrieve capture sample spec.\n");
  25555. }
  25556. pDescriptorCapture->format = ma_format_from_pulse(ss.format);
  25557. pDescriptorCapture->channels = ss.channels;
  25558. pDescriptorCapture->sampleRate = ss.rate;
  25559. if (pDescriptorCapture->format == ma_format_unknown || pDescriptorCapture->channels == 0 || pDescriptorCapture->sampleRate == 0) {
  25560. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Capture sample spec is invalid. Device unusable by miniaudio. format=%s, channels=%d, sampleRate=%d.\n", ma_get_format_name(pDescriptorCapture->format), pDescriptorCapture->channels, pDescriptorCapture->sampleRate);
  25561. result = MA_ERROR;
  25562. goto on_error4;
  25563. }
  25564. /* Internal channel map. */
  25565. /*
  25566. Bug in PipeWire. There have been reports that PipeWire is returning AUX channels when reporting
  25567. the channel map. To somewhat workaround this, I'm hacking in a hard coded channel map for mono
  25568. and stereo. In this case it should be safe to assume mono = MONO and stereo = LEFT/RIGHT. For
  25569. all other channel counts we need to just put up with whatever PipeWire reports and hope it gets
  25570. fixed sooner than later. I might remove this hack later.
  25571. */
  25572. if (pDescriptorCapture->channels > 2) {
  25573. for (iChannel = 0; iChannel < pDescriptorCapture->channels; ++iChannel) {
  25574. pDescriptorCapture->channelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]);
  25575. }
  25576. } else {
  25577. /* Hack for mono and stereo. */
  25578. if (pDescriptorCapture->channels == 1) {
  25579. pDescriptorCapture->channelMap[0] = MA_CHANNEL_MONO;
  25580. } else if (pDescriptorCapture->channels == 2) {
  25581. pDescriptorCapture->channelMap[0] = MA_CHANNEL_FRONT_LEFT;
  25582. pDescriptorCapture->channelMap[1] = MA_CHANNEL_FRONT_RIGHT;
  25583. } else {
  25584. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  25585. }
  25586. }
  25587. /* Buffer. */
  25588. pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pDevice->pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25589. if (pActualAttr != NULL) {
  25590. attr = *pActualAttr;
  25591. }
  25592. if (attr.fragsize > 0) {
  25593. pDescriptorCapture->periodCount = ma_max(attr.maxlength / attr.fragsize, 1);
  25594. } else {
  25595. pDescriptorCapture->periodCount = 1;
  25596. }
  25597. pDescriptorCapture->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / pDescriptorCapture->periodCount;
  25598. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Capture actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; periodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDescriptorCapture->periodSizeInFrames);
  25599. }
  25600. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  25601. result = ma_context_get_sink_info__pulse(pDevice->pContext, devPlayback, &sinkInfo);
  25602. if (result != MA_SUCCESS) {
  25603. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve sink info for playback device.\n");
  25604. goto on_error2;
  25605. }
  25606. ss = sinkInfo.sample_spec;
  25607. cmap = sinkInfo.channel_map;
  25608. /* Use the requested channel count if we have one. */
  25609. if (pDescriptorPlayback->channels != 0) {
  25610. ss.channels = pDescriptorPlayback->channels;
  25611. }
  25612. /* Use a default channel map. */
  25613. ((ma_pa_channel_map_init_extend_proc)pDevice->pContext->pulse.pa_channel_map_init_extend)(&cmap, ss.channels, MA_PA_CHANNEL_MAP_DEFAULT);
  25614. /* Use the requested sample rate if one was specified. */
  25615. if (pDescriptorPlayback->sampleRate != 0) {
  25616. ss.rate = pDescriptorPlayback->sampleRate;
  25617. }
  25618. if (ma_format_from_pulse(ss.format) == ma_format_unknown) {
  25619. if (ma_is_little_endian()) {
  25620. ss.format = MA_PA_SAMPLE_FLOAT32LE;
  25621. } else {
  25622. ss.format = MA_PA_SAMPLE_FLOAT32BE;
  25623. }
  25624. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.format not supported by miniaudio. Defaulting to PA_SAMPLE_FLOAT32.\n");
  25625. }
  25626. if (ss.rate == 0) {
  25627. ss.rate = MA_DEFAULT_SAMPLE_RATE;
  25628. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.rate = 0. Defaulting to %d.\n", ss.rate);
  25629. }
  25630. if (ss.channels == 0) {
  25631. ss.channels = MA_DEFAULT_CHANNELS;
  25632. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels);
  25633. }
  25634. /* We now have enough information to calculate the actual buffer size in frames. */
  25635. pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorPlayback, ss.rate, pConfig->performanceProfile);
  25636. attr = ma_device__pa_buffer_attr_new(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->periodCount, &ss);
  25637. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Playback attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; periodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDescriptorPlayback->periodSizeInFrames);
  25638. pDevice->pulse.pStreamPlayback = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNamePlayback, &ss, &cmap);
  25639. if (pDevice->pulse.pStreamPlayback == NULL) {
  25640. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio playback stream.\n");
  25641. result = MA_ERROR;
  25642. goto on_error2;
  25643. }
  25644. /*
  25645. Note that this callback will be fired as soon as the stream is connected, even though it's started as corked. The callback needs to handle a
  25646. device state of ma_device_state_uninitialized.
  25647. */
  25648. ((ma_pa_stream_set_write_callback_proc)pDevice->pContext->pulse.pa_stream_set_write_callback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_device_on_write__pulse, pDevice);
  25649. /* State callback for checking when the device has been corked. */
  25650. ((ma_pa_stream_set_suspended_callback_proc)pDevice->pContext->pulse.pa_stream_set_suspended_callback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_device_on_suspended__pulse, pDevice);
  25651. /* Rerouting notification. */
  25652. ((ma_pa_stream_set_moved_callback_proc)pDevice->pContext->pulse.pa_stream_set_moved_callback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_device_on_rerouted__pulse, pDevice);
  25653. /* Connect after we've got all of our internal state set up. */
  25654. streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_ADJUST_LATENCY | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS;
  25655. if (devPlayback != NULL) {
  25656. streamFlags |= MA_PA_STREAM_DONT_MOVE;
  25657. }
  25658. error = ((ma_pa_stream_connect_playback_proc)pDevice->pContext->pulse.pa_stream_connect_playback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, devPlayback, &attr, streamFlags, NULL, NULL);
  25659. if (error != MA_PA_OK) {
  25660. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio playback stream.");
  25661. result = ma_result_from_pulse(error);
  25662. goto on_error3;
  25663. }
  25664. result = ma_wait_for_pa_stream_to_connect__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, (ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25665. if (result != MA_SUCCESS) {
  25666. goto on_error3;
  25667. }
  25668. /* Internal format. */
  25669. pActualSS = ((ma_pa_stream_get_sample_spec_proc)pDevice->pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25670. if (pActualSS != NULL) {
  25671. ss = *pActualSS;
  25672. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Playback sample spec: format=%s, channels=%d, rate=%d\n", ma_get_format_name(ma_format_from_pulse(ss.format)), ss.channels, ss.rate);
  25673. } else {
  25674. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Failed to retrieve playback sample spec.\n");
  25675. }
  25676. pDescriptorPlayback->format = ma_format_from_pulse(ss.format);
  25677. pDescriptorPlayback->channels = ss.channels;
  25678. pDescriptorPlayback->sampleRate = ss.rate;
  25679. if (pDescriptorPlayback->format == ma_format_unknown || pDescriptorPlayback->channels == 0 || pDescriptorPlayback->sampleRate == 0) {
  25680. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Playback sample spec is invalid. Device unusable by miniaudio. format=%s, channels=%d, sampleRate=%d.\n", ma_get_format_name(pDescriptorPlayback->format), pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate);
  25681. result = MA_ERROR;
  25682. goto on_error4;
  25683. }
  25684. /* Internal channel map. */
  25685. /*
  25686. Bug in PipeWire. There have been reports that PipeWire is returning AUX channels when reporting
  25687. the channel map. To somewhat workaround this, I'm hacking in a hard coded channel map for mono
  25688. and stereo. In this case it should be safe to assume mono = MONO and stereo = LEFT/RIGHT. For
  25689. all other channel counts we need to just put up with whatever PipeWire reports and hope it gets
  25690. fixed sooner than later. I might remove this hack later.
  25691. */
  25692. if (pDescriptorPlayback->channels > 2) {
  25693. for (iChannel = 0; iChannel < pDescriptorPlayback->channels; ++iChannel) {
  25694. pDescriptorPlayback->channelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]);
  25695. }
  25696. } else {
  25697. /* Hack for mono and stereo. */
  25698. if (pDescriptorPlayback->channels == 1) {
  25699. pDescriptorPlayback->channelMap[0] = MA_CHANNEL_MONO;
  25700. } else if (pDescriptorPlayback->channels == 2) {
  25701. pDescriptorPlayback->channelMap[0] = MA_CHANNEL_FRONT_LEFT;
  25702. pDescriptorPlayback->channelMap[1] = MA_CHANNEL_FRONT_RIGHT;
  25703. } else {
  25704. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  25705. }
  25706. }
  25707. /* Buffer. */
  25708. pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pDevice->pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25709. if (pActualAttr != NULL) {
  25710. attr = *pActualAttr;
  25711. }
  25712. if (attr.tlength > 0) {
  25713. pDescriptorPlayback->periodCount = ma_max(attr.maxlength / attr.tlength, 1);
  25714. } else {
  25715. pDescriptorPlayback->periodCount = 1;
  25716. }
  25717. pDescriptorPlayback->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels) / pDescriptorPlayback->periodCount;
  25718. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Playback actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDescriptorPlayback->periodSizeInFrames);
  25719. }
  25720. /*
  25721. We need a ring buffer for handling duplex mode. We can use the main duplex ring buffer in the main
  25722. part of the ma_device struct. We cannot, however, depend on ma_device_init() initializing this for
  25723. us later on because that will only do it if it's a fully asynchronous backend - i.e. the
  25724. onDeviceDataLoop callback is NULL, which is not the case for PulseAudio.
  25725. */
  25726. if (pConfig->deviceType == ma_device_type_duplex) {
  25727. ma_format rbFormat = (format != ma_format_unknown) ? format : pDescriptorCapture->format;
  25728. ma_uint32 rbChannels = (channels > 0) ? channels : pDescriptorCapture->channels;
  25729. ma_uint32 rbSampleRate = (sampleRate > 0) ? sampleRate : pDescriptorCapture->sampleRate;
  25730. result = ma_duplex_rb_init(rbFormat, rbChannels, rbSampleRate, pDescriptorCapture->sampleRate, pDescriptorCapture->periodSizeInFrames, &pDevice->pContext->allocationCallbacks, &pDevice->duplexRB);
  25731. if (result != MA_SUCCESS) {
  25732. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to initialize ring buffer. %s.\n", ma_result_description(result));
  25733. goto on_error4;
  25734. }
  25735. }
  25736. return MA_SUCCESS;
  25737. on_error4:
  25738. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  25739. ((ma_pa_stream_disconnect_proc)pDevice->pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25740. }
  25741. on_error3:
  25742. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  25743. ((ma_pa_stream_unref_proc)pDevice->pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25744. }
  25745. on_error2:
  25746. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  25747. ((ma_pa_stream_disconnect_proc)pDevice->pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25748. }
  25749. on_error1:
  25750. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  25751. ((ma_pa_stream_unref_proc)pDevice->pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25752. }
  25753. on_error0:
  25754. return result;
  25755. }
  25756. static void ma_pulse_operation_complete_callback(ma_pa_stream* pStream, int success, void* pUserData)
  25757. {
  25758. ma_bool32* pIsSuccessful = (ma_bool32*)pUserData;
  25759. MA_ASSERT(pIsSuccessful != NULL);
  25760. *pIsSuccessful = (ma_bool32)success;
  25761. (void)pStream; /* Unused. */
  25762. }
  25763. static ma_result ma_device__cork_stream__pulse(ma_device* pDevice, ma_device_type deviceType, int cork)
  25764. {
  25765. ma_context* pContext = pDevice->pContext;
  25766. ma_bool32 wasSuccessful;
  25767. ma_pa_stream* pStream;
  25768. ma_pa_operation* pOP;
  25769. ma_result result;
  25770. /* This should not be called with a duplex device type. */
  25771. if (deviceType == ma_device_type_duplex) {
  25772. return MA_INVALID_ARGS;
  25773. }
  25774. wasSuccessful = MA_FALSE;
  25775. pStream = (ma_pa_stream*)((deviceType == ma_device_type_capture) ? pDevice->pulse.pStreamCapture : pDevice->pulse.pStreamPlayback);
  25776. MA_ASSERT(pStream != NULL);
  25777. pOP = ((ma_pa_stream_cork_proc)pContext->pulse.pa_stream_cork)(pStream, cork, ma_pulse_operation_complete_callback, &wasSuccessful);
  25778. if (pOP == NULL) {
  25779. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to cork PulseAudio stream.");
  25780. return MA_ERROR;
  25781. }
  25782. result = ma_wait_for_operation_and_unref__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, pOP);
  25783. if (result != MA_SUCCESS) {
  25784. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while waiting for the PulseAudio stream to cork.");
  25785. return result;
  25786. }
  25787. if (!wasSuccessful) {
  25788. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to %s PulseAudio stream.", (cork) ? "stop" : "start");
  25789. return MA_ERROR;
  25790. }
  25791. return MA_SUCCESS;
  25792. }
  25793. static ma_result ma_device_start__pulse(ma_device* pDevice)
  25794. {
  25795. ma_result result;
  25796. MA_ASSERT(pDevice != NULL);
  25797. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25798. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 0);
  25799. if (result != MA_SUCCESS) {
  25800. return result;
  25801. }
  25802. }
  25803. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25804. /*
  25805. We need to fill some data before uncorking. Not doing this will result in the write callback
  25806. never getting fired. We're not going to abort if writing fails because I still want the device
  25807. to get uncorked.
  25808. */
  25809. ma_device_write_to_stream__pulse(pDevice, (ma_pa_stream*)(pDevice->pulse.pStreamPlayback), NULL); /* No need to check the result here. Always want to fall through an uncork.*/
  25810. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 0);
  25811. if (result != MA_SUCCESS) {
  25812. return result;
  25813. }
  25814. }
  25815. return MA_SUCCESS;
  25816. }
  25817. static ma_result ma_device_stop__pulse(ma_device* pDevice)
  25818. {
  25819. ma_result result;
  25820. MA_ASSERT(pDevice != NULL);
  25821. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25822. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 1);
  25823. if (result != MA_SUCCESS) {
  25824. return result;
  25825. }
  25826. }
  25827. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25828. /*
  25829. Ideally we would drain the device here, but there's been cases where PulseAudio seems to be
  25830. broken on some systems to the point where no audio processing seems to happen. When this
  25831. happens, draining never completes and we get stuck here. For now I'm disabling draining of
  25832. the device so we don't just freeze the application.
  25833. */
  25834. #if 0
  25835. ma_pa_operation* pOP = ((ma_pa_stream_drain_proc)pDevice->pContext->pulse.pa_stream_drain)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_pulse_operation_complete_callback, &wasSuccessful);
  25836. ma_wait_for_operation_and_unref__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, pOP);
  25837. #endif
  25838. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 1);
  25839. if (result != MA_SUCCESS) {
  25840. return result;
  25841. }
  25842. }
  25843. return MA_SUCCESS;
  25844. }
  25845. static ma_result ma_device_data_loop__pulse(ma_device* pDevice)
  25846. {
  25847. int resultPA;
  25848. MA_ASSERT(pDevice != NULL);
  25849. /* NOTE: Don't start the device here. It'll be done at a higher level. */
  25850. /*
  25851. All data is handled through callbacks. All we need to do is iterate over the main loop and let
  25852. the callbacks deal with it.
  25853. */
  25854. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  25855. resultPA = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL);
  25856. if (resultPA < 0) {
  25857. break;
  25858. }
  25859. }
  25860. /* NOTE: Don't stop the device here. It'll be done at a higher level. */
  25861. return MA_SUCCESS;
  25862. }
  25863. static ma_result ma_device_data_loop_wakeup__pulse(ma_device* pDevice)
  25864. {
  25865. MA_ASSERT(pDevice != NULL);
  25866. ((ma_pa_mainloop_wakeup_proc)pDevice->pContext->pulse.pa_mainloop_wakeup)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
  25867. return MA_SUCCESS;
  25868. }
  25869. static ma_result ma_context_uninit__pulse(ma_context* pContext)
  25870. {
  25871. MA_ASSERT(pContext != NULL);
  25872. MA_ASSERT(pContext->backend == ma_backend_pulseaudio);
  25873. ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pContext->pulse.pPulseContext);
  25874. ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pContext->pulse.pPulseContext);
  25875. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pContext->pulse.pMainLoop);
  25876. ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
  25877. ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
  25878. #ifndef MA_NO_RUNTIME_LINKING
  25879. ma_dlclose(pContext, pContext->pulse.pulseSO);
  25880. #endif
  25881. return MA_SUCCESS;
  25882. }
  25883. static ma_result ma_context_init__pulse(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  25884. {
  25885. ma_result result;
  25886. #ifndef MA_NO_RUNTIME_LINKING
  25887. const char* libpulseNames[] = {
  25888. "libpulse.so",
  25889. "libpulse.so.0"
  25890. };
  25891. size_t i;
  25892. for (i = 0; i < ma_countof(libpulseNames); ++i) {
  25893. pContext->pulse.pulseSO = ma_dlopen(pContext, libpulseNames[i]);
  25894. if (pContext->pulse.pulseSO != NULL) {
  25895. break;
  25896. }
  25897. }
  25898. if (pContext->pulse.pulseSO == NULL) {
  25899. return MA_NO_BACKEND;
  25900. }
  25901. pContext->pulse.pa_mainloop_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_new");
  25902. pContext->pulse.pa_mainloop_free = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_free");
  25903. pContext->pulse.pa_mainloop_quit = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_quit");
  25904. pContext->pulse.pa_mainloop_get_api = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_get_api");
  25905. pContext->pulse.pa_mainloop_iterate = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_iterate");
  25906. pContext->pulse.pa_mainloop_wakeup = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_wakeup");
  25907. pContext->pulse.pa_threaded_mainloop_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_new");
  25908. pContext->pulse.pa_threaded_mainloop_free = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_free");
  25909. pContext->pulse.pa_threaded_mainloop_start = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_start");
  25910. pContext->pulse.pa_threaded_mainloop_stop = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_stop");
  25911. pContext->pulse.pa_threaded_mainloop_lock = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_lock");
  25912. pContext->pulse.pa_threaded_mainloop_unlock = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_unlock");
  25913. pContext->pulse.pa_threaded_mainloop_wait = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_wait");
  25914. pContext->pulse.pa_threaded_mainloop_signal = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_signal");
  25915. pContext->pulse.pa_threaded_mainloop_accept = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_accept");
  25916. pContext->pulse.pa_threaded_mainloop_get_retval = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_get_retval");
  25917. pContext->pulse.pa_threaded_mainloop_get_api = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_get_api");
  25918. pContext->pulse.pa_threaded_mainloop_in_thread = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_in_thread");
  25919. pContext->pulse.pa_threaded_mainloop_set_name = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_set_name");
  25920. pContext->pulse.pa_context_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_new");
  25921. pContext->pulse.pa_context_unref = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_unref");
  25922. pContext->pulse.pa_context_connect = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_connect");
  25923. pContext->pulse.pa_context_disconnect = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_disconnect");
  25924. pContext->pulse.pa_context_set_state_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_set_state_callback");
  25925. pContext->pulse.pa_context_get_state = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_state");
  25926. pContext->pulse.pa_context_get_sink_info_list = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_sink_info_list");
  25927. pContext->pulse.pa_context_get_source_info_list = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_source_info_list");
  25928. pContext->pulse.pa_context_get_sink_info_by_name = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_sink_info_by_name");
  25929. pContext->pulse.pa_context_get_source_info_by_name = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_source_info_by_name");
  25930. pContext->pulse.pa_operation_unref = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_operation_unref");
  25931. pContext->pulse.pa_operation_get_state = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_operation_get_state");
  25932. pContext->pulse.pa_channel_map_init_extend = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_channel_map_init_extend");
  25933. pContext->pulse.pa_channel_map_valid = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_channel_map_valid");
  25934. pContext->pulse.pa_channel_map_compatible = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_channel_map_compatible");
  25935. pContext->pulse.pa_stream_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_new");
  25936. pContext->pulse.pa_stream_unref = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_unref");
  25937. pContext->pulse.pa_stream_connect_playback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_connect_playback");
  25938. pContext->pulse.pa_stream_connect_record = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_connect_record");
  25939. pContext->pulse.pa_stream_disconnect = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_disconnect");
  25940. pContext->pulse.pa_stream_get_state = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_state");
  25941. pContext->pulse.pa_stream_get_sample_spec = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_sample_spec");
  25942. pContext->pulse.pa_stream_get_channel_map = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_channel_map");
  25943. pContext->pulse.pa_stream_get_buffer_attr = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_buffer_attr");
  25944. pContext->pulse.pa_stream_set_buffer_attr = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_buffer_attr");
  25945. pContext->pulse.pa_stream_get_device_name = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_device_name");
  25946. pContext->pulse.pa_stream_set_write_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_write_callback");
  25947. pContext->pulse.pa_stream_set_read_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_read_callback");
  25948. pContext->pulse.pa_stream_set_suspended_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_suspended_callback");
  25949. pContext->pulse.pa_stream_set_moved_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_moved_callback");
  25950. pContext->pulse.pa_stream_is_suspended = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_is_suspended");
  25951. pContext->pulse.pa_stream_flush = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_flush");
  25952. pContext->pulse.pa_stream_drain = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_drain");
  25953. pContext->pulse.pa_stream_is_corked = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_is_corked");
  25954. pContext->pulse.pa_stream_cork = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_cork");
  25955. pContext->pulse.pa_stream_trigger = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_trigger");
  25956. pContext->pulse.pa_stream_begin_write = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_begin_write");
  25957. pContext->pulse.pa_stream_write = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_write");
  25958. pContext->pulse.pa_stream_peek = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_peek");
  25959. pContext->pulse.pa_stream_drop = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_drop");
  25960. pContext->pulse.pa_stream_writable_size = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_writable_size");
  25961. pContext->pulse.pa_stream_readable_size = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_readable_size");
  25962. #else
  25963. /* This strange assignment system is just for type safety. */
  25964. ma_pa_mainloop_new_proc _pa_mainloop_new = pa_mainloop_new;
  25965. ma_pa_mainloop_free_proc _pa_mainloop_free = pa_mainloop_free;
  25966. ma_pa_mainloop_quit_proc _pa_mainloop_quit = pa_mainloop_quit;
  25967. ma_pa_mainloop_get_api_proc _pa_mainloop_get_api = pa_mainloop_get_api;
  25968. ma_pa_mainloop_iterate_proc _pa_mainloop_iterate = pa_mainloop_iterate;
  25969. ma_pa_mainloop_wakeup_proc _pa_mainloop_wakeup = pa_mainloop_wakeup;
  25970. ma_pa_threaded_mainloop_new_proc _pa_threaded_mainloop_new = pa_threaded_mainloop_new;
  25971. ma_pa_threaded_mainloop_free_proc _pa_threaded_mainloop_free = pa_threaded_mainloop_free;
  25972. ma_pa_threaded_mainloop_start_proc _pa_threaded_mainloop_start = pa_threaded_mainloop_start;
  25973. ma_pa_threaded_mainloop_stop_proc _pa_threaded_mainloop_stop = pa_threaded_mainloop_stop;
  25974. ma_pa_threaded_mainloop_lock_proc _pa_threaded_mainloop_lock = pa_threaded_mainloop_lock;
  25975. ma_pa_threaded_mainloop_unlock_proc _pa_threaded_mainloop_unlock = pa_threaded_mainloop_unlock;
  25976. ma_pa_threaded_mainloop_wait_proc _pa_threaded_mainloop_wait = pa_threaded_mainloop_wait;
  25977. ma_pa_threaded_mainloop_signal_proc _pa_threaded_mainloop_signal = pa_threaded_mainloop_signal;
  25978. ma_pa_threaded_mainloop_accept_proc _pa_threaded_mainloop_accept = pa_threaded_mainloop_accept;
  25979. ma_pa_threaded_mainloop_get_retval_proc _pa_threaded_mainloop_get_retval = pa_threaded_mainloop_get_retval;
  25980. ma_pa_threaded_mainloop_get_api_proc _pa_threaded_mainloop_get_api = pa_threaded_mainloop_get_api;
  25981. ma_pa_threaded_mainloop_in_thread_proc _pa_threaded_mainloop_in_thread = pa_threaded_mainloop_in_thread;
  25982. ma_pa_threaded_mainloop_set_name_proc _pa_threaded_mainloop_set_name = pa_threaded_mainloop_set_name;
  25983. ma_pa_context_new_proc _pa_context_new = pa_context_new;
  25984. ma_pa_context_unref_proc _pa_context_unref = pa_context_unref;
  25985. ma_pa_context_connect_proc _pa_context_connect = pa_context_connect;
  25986. ma_pa_context_disconnect_proc _pa_context_disconnect = pa_context_disconnect;
  25987. ma_pa_context_set_state_callback_proc _pa_context_set_state_callback = pa_context_set_state_callback;
  25988. ma_pa_context_get_state_proc _pa_context_get_state = pa_context_get_state;
  25989. ma_pa_context_get_sink_info_list_proc _pa_context_get_sink_info_list = pa_context_get_sink_info_list;
  25990. ma_pa_context_get_source_info_list_proc _pa_context_get_source_info_list = pa_context_get_source_info_list;
  25991. ma_pa_context_get_sink_info_by_name_proc _pa_context_get_sink_info_by_name = pa_context_get_sink_info_by_name;
  25992. ma_pa_context_get_source_info_by_name_proc _pa_context_get_source_info_by_name= pa_context_get_source_info_by_name;
  25993. ma_pa_operation_unref_proc _pa_operation_unref = pa_operation_unref;
  25994. ma_pa_operation_get_state_proc _pa_operation_get_state = pa_operation_get_state;
  25995. ma_pa_channel_map_init_extend_proc _pa_channel_map_init_extend = pa_channel_map_init_extend;
  25996. ma_pa_channel_map_valid_proc _pa_channel_map_valid = pa_channel_map_valid;
  25997. ma_pa_channel_map_compatible_proc _pa_channel_map_compatible = pa_channel_map_compatible;
  25998. ma_pa_stream_new_proc _pa_stream_new = pa_stream_new;
  25999. ma_pa_stream_unref_proc _pa_stream_unref = pa_stream_unref;
  26000. ma_pa_stream_connect_playback_proc _pa_stream_connect_playback = pa_stream_connect_playback;
  26001. ma_pa_stream_connect_record_proc _pa_stream_connect_record = pa_stream_connect_record;
  26002. ma_pa_stream_disconnect_proc _pa_stream_disconnect = pa_stream_disconnect;
  26003. ma_pa_stream_get_state_proc _pa_stream_get_state = pa_stream_get_state;
  26004. ma_pa_stream_get_sample_spec_proc _pa_stream_get_sample_spec = pa_stream_get_sample_spec;
  26005. ma_pa_stream_get_channel_map_proc _pa_stream_get_channel_map = pa_stream_get_channel_map;
  26006. ma_pa_stream_get_buffer_attr_proc _pa_stream_get_buffer_attr = pa_stream_get_buffer_attr;
  26007. ma_pa_stream_set_buffer_attr_proc _pa_stream_set_buffer_attr = pa_stream_set_buffer_attr;
  26008. ma_pa_stream_get_device_name_proc _pa_stream_get_device_name = pa_stream_get_device_name;
  26009. ma_pa_stream_set_write_callback_proc _pa_stream_set_write_callback = pa_stream_set_write_callback;
  26010. ma_pa_stream_set_read_callback_proc _pa_stream_set_read_callback = pa_stream_set_read_callback;
  26011. ma_pa_stream_set_suspended_callback_proc _pa_stream_set_suspended_callback = pa_stream_set_suspended_callback;
  26012. ma_pa_stream_set_moved_callback_proc _pa_stream_set_moved_callback = pa_stream_set_moved_callback;
  26013. ma_pa_stream_is_suspended_proc _pa_stream_is_suspended = pa_stream_is_suspended;
  26014. ma_pa_stream_flush_proc _pa_stream_flush = pa_stream_flush;
  26015. ma_pa_stream_drain_proc _pa_stream_drain = pa_stream_drain;
  26016. ma_pa_stream_is_corked_proc _pa_stream_is_corked = pa_stream_is_corked;
  26017. ma_pa_stream_cork_proc _pa_stream_cork = pa_stream_cork;
  26018. ma_pa_stream_trigger_proc _pa_stream_trigger = pa_stream_trigger;
  26019. ma_pa_stream_begin_write_proc _pa_stream_begin_write = pa_stream_begin_write;
  26020. ma_pa_stream_write_proc _pa_stream_write = pa_stream_write;
  26021. ma_pa_stream_peek_proc _pa_stream_peek = pa_stream_peek;
  26022. ma_pa_stream_drop_proc _pa_stream_drop = pa_stream_drop;
  26023. ma_pa_stream_writable_size_proc _pa_stream_writable_size = pa_stream_writable_size;
  26024. ma_pa_stream_readable_size_proc _pa_stream_readable_size = pa_stream_readable_size;
  26025. pContext->pulse.pa_mainloop_new = (ma_proc)_pa_mainloop_new;
  26026. pContext->pulse.pa_mainloop_free = (ma_proc)_pa_mainloop_free;
  26027. pContext->pulse.pa_mainloop_quit = (ma_proc)_pa_mainloop_quit;
  26028. pContext->pulse.pa_mainloop_get_api = (ma_proc)_pa_mainloop_get_api;
  26029. pContext->pulse.pa_mainloop_iterate = (ma_proc)_pa_mainloop_iterate;
  26030. pContext->pulse.pa_mainloop_wakeup = (ma_proc)_pa_mainloop_wakeup;
  26031. pContext->pulse.pa_threaded_mainloop_new = (ma_proc)_pa_threaded_mainloop_new;
  26032. pContext->pulse.pa_threaded_mainloop_free = (ma_proc)_pa_threaded_mainloop_free;
  26033. pContext->pulse.pa_threaded_mainloop_start = (ma_proc)_pa_threaded_mainloop_start;
  26034. pContext->pulse.pa_threaded_mainloop_stop = (ma_proc)_pa_threaded_mainloop_stop;
  26035. pContext->pulse.pa_threaded_mainloop_lock = (ma_proc)_pa_threaded_mainloop_lock;
  26036. pContext->pulse.pa_threaded_mainloop_unlock = (ma_proc)_pa_threaded_mainloop_unlock;
  26037. pContext->pulse.pa_threaded_mainloop_wait = (ma_proc)_pa_threaded_mainloop_wait;
  26038. pContext->pulse.pa_threaded_mainloop_signal = (ma_proc)_pa_threaded_mainloop_signal;
  26039. pContext->pulse.pa_threaded_mainloop_accept = (ma_proc)_pa_threaded_mainloop_accept;
  26040. pContext->pulse.pa_threaded_mainloop_get_retval = (ma_proc)_pa_threaded_mainloop_get_retval;
  26041. pContext->pulse.pa_threaded_mainloop_get_api = (ma_proc)_pa_threaded_mainloop_get_api;
  26042. pContext->pulse.pa_threaded_mainloop_in_thread = (ma_proc)_pa_threaded_mainloop_in_thread;
  26043. pContext->pulse.pa_threaded_mainloop_set_name = (ma_proc)_pa_threaded_mainloop_set_name;
  26044. pContext->pulse.pa_context_new = (ma_proc)_pa_context_new;
  26045. pContext->pulse.pa_context_unref = (ma_proc)_pa_context_unref;
  26046. pContext->pulse.pa_context_connect = (ma_proc)_pa_context_connect;
  26047. pContext->pulse.pa_context_disconnect = (ma_proc)_pa_context_disconnect;
  26048. pContext->pulse.pa_context_set_state_callback = (ma_proc)_pa_context_set_state_callback;
  26049. pContext->pulse.pa_context_get_state = (ma_proc)_pa_context_get_state;
  26050. pContext->pulse.pa_context_get_sink_info_list = (ma_proc)_pa_context_get_sink_info_list;
  26051. pContext->pulse.pa_context_get_source_info_list = (ma_proc)_pa_context_get_source_info_list;
  26052. pContext->pulse.pa_context_get_sink_info_by_name = (ma_proc)_pa_context_get_sink_info_by_name;
  26053. pContext->pulse.pa_context_get_source_info_by_name = (ma_proc)_pa_context_get_source_info_by_name;
  26054. pContext->pulse.pa_operation_unref = (ma_proc)_pa_operation_unref;
  26055. pContext->pulse.pa_operation_get_state = (ma_proc)_pa_operation_get_state;
  26056. pContext->pulse.pa_channel_map_init_extend = (ma_proc)_pa_channel_map_init_extend;
  26057. pContext->pulse.pa_channel_map_valid = (ma_proc)_pa_channel_map_valid;
  26058. pContext->pulse.pa_channel_map_compatible = (ma_proc)_pa_channel_map_compatible;
  26059. pContext->pulse.pa_stream_new = (ma_proc)_pa_stream_new;
  26060. pContext->pulse.pa_stream_unref = (ma_proc)_pa_stream_unref;
  26061. pContext->pulse.pa_stream_connect_playback = (ma_proc)_pa_stream_connect_playback;
  26062. pContext->pulse.pa_stream_connect_record = (ma_proc)_pa_stream_connect_record;
  26063. pContext->pulse.pa_stream_disconnect = (ma_proc)_pa_stream_disconnect;
  26064. pContext->pulse.pa_stream_get_state = (ma_proc)_pa_stream_get_state;
  26065. pContext->pulse.pa_stream_get_sample_spec = (ma_proc)_pa_stream_get_sample_spec;
  26066. pContext->pulse.pa_stream_get_channel_map = (ma_proc)_pa_stream_get_channel_map;
  26067. pContext->pulse.pa_stream_get_buffer_attr = (ma_proc)_pa_stream_get_buffer_attr;
  26068. pContext->pulse.pa_stream_set_buffer_attr = (ma_proc)_pa_stream_set_buffer_attr;
  26069. pContext->pulse.pa_stream_get_device_name = (ma_proc)_pa_stream_get_device_name;
  26070. pContext->pulse.pa_stream_set_write_callback = (ma_proc)_pa_stream_set_write_callback;
  26071. pContext->pulse.pa_stream_set_read_callback = (ma_proc)_pa_stream_set_read_callback;
  26072. pContext->pulse.pa_stream_set_suspended_callback = (ma_proc)_pa_stream_set_suspended_callback;
  26073. pContext->pulse.pa_stream_set_moved_callback = (ma_proc)_pa_stream_set_moved_callback;
  26074. pContext->pulse.pa_stream_is_suspended = (ma_proc)_pa_stream_is_suspended;
  26075. pContext->pulse.pa_stream_flush = (ma_proc)_pa_stream_flush;
  26076. pContext->pulse.pa_stream_drain = (ma_proc)_pa_stream_drain;
  26077. pContext->pulse.pa_stream_is_corked = (ma_proc)_pa_stream_is_corked;
  26078. pContext->pulse.pa_stream_cork = (ma_proc)_pa_stream_cork;
  26079. pContext->pulse.pa_stream_trigger = (ma_proc)_pa_stream_trigger;
  26080. pContext->pulse.pa_stream_begin_write = (ma_proc)_pa_stream_begin_write;
  26081. pContext->pulse.pa_stream_write = (ma_proc)_pa_stream_write;
  26082. pContext->pulse.pa_stream_peek = (ma_proc)_pa_stream_peek;
  26083. pContext->pulse.pa_stream_drop = (ma_proc)_pa_stream_drop;
  26084. pContext->pulse.pa_stream_writable_size = (ma_proc)_pa_stream_writable_size;
  26085. pContext->pulse.pa_stream_readable_size = (ma_proc)_pa_stream_readable_size;
  26086. #endif
  26087. /* We need to make a copy of the application and server names so we can pass them to the pa_context of each device. */
  26088. pContext->pulse.pApplicationName = ma_copy_string(pConfig->pulse.pApplicationName, &pContext->allocationCallbacks);
  26089. if (pContext->pulse.pApplicationName == NULL && pConfig->pulse.pApplicationName != NULL) {
  26090. return MA_OUT_OF_MEMORY;
  26091. }
  26092. pContext->pulse.pServerName = ma_copy_string(pConfig->pulse.pServerName, &pContext->allocationCallbacks);
  26093. if (pContext->pulse.pServerName == NULL && pConfig->pulse.pServerName != NULL) {
  26094. ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
  26095. return MA_OUT_OF_MEMORY;
  26096. }
  26097. result = ma_init_pa_mainloop_and_pa_context__pulse(pContext, pConfig->pulse.pApplicationName, pConfig->pulse.pServerName, pConfig->pulse.tryAutoSpawn, &pContext->pulse.pMainLoop, &pContext->pulse.pPulseContext);
  26098. if (result != MA_SUCCESS) {
  26099. ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
  26100. ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
  26101. #ifndef MA_NO_RUNTIME_LINKING
  26102. ma_dlclose(pContext, pContext->pulse.pulseSO);
  26103. #endif
  26104. return result;
  26105. }
  26106. /* With pa_mainloop we run a synchronous backend, but we implement our own main loop. */
  26107. pCallbacks->onContextInit = ma_context_init__pulse;
  26108. pCallbacks->onContextUninit = ma_context_uninit__pulse;
  26109. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__pulse;
  26110. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__pulse;
  26111. pCallbacks->onDeviceInit = ma_device_init__pulse;
  26112. pCallbacks->onDeviceUninit = ma_device_uninit__pulse;
  26113. pCallbacks->onDeviceStart = ma_device_start__pulse;
  26114. pCallbacks->onDeviceStop = ma_device_stop__pulse;
  26115. pCallbacks->onDeviceRead = NULL; /* Not used because we're implementing onDeviceDataLoop. */
  26116. pCallbacks->onDeviceWrite = NULL; /* Not used because we're implementing onDeviceDataLoop. */
  26117. pCallbacks->onDeviceDataLoop = ma_device_data_loop__pulse;
  26118. pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__pulse;
  26119. return MA_SUCCESS;
  26120. }
  26121. #endif
  26122. /******************************************************************************
  26123. JACK Backend
  26124. ******************************************************************************/
  26125. #ifdef MA_HAS_JACK
  26126. /* It is assumed jack.h is available when compile-time linking is being used. */
  26127. #ifdef MA_NO_RUNTIME_LINKING
  26128. #include <jack/jack.h>
  26129. typedef jack_nframes_t ma_jack_nframes_t;
  26130. typedef jack_options_t ma_jack_options_t;
  26131. typedef jack_status_t ma_jack_status_t;
  26132. typedef jack_client_t ma_jack_client_t;
  26133. typedef jack_port_t ma_jack_port_t;
  26134. typedef JackProcessCallback ma_JackProcessCallback;
  26135. typedef JackBufferSizeCallback ma_JackBufferSizeCallback;
  26136. typedef JackShutdownCallback ma_JackShutdownCallback;
  26137. #define MA_JACK_DEFAULT_AUDIO_TYPE JACK_DEFAULT_AUDIO_TYPE
  26138. #define ma_JackNoStartServer JackNoStartServer
  26139. #define ma_JackPortIsInput JackPortIsInput
  26140. #define ma_JackPortIsOutput JackPortIsOutput
  26141. #define ma_JackPortIsPhysical JackPortIsPhysical
  26142. #else
  26143. typedef ma_uint32 ma_jack_nframes_t;
  26144. typedef int ma_jack_options_t;
  26145. typedef int ma_jack_status_t;
  26146. typedef struct ma_jack_client_t ma_jack_client_t;
  26147. typedef struct ma_jack_port_t ma_jack_port_t;
  26148. typedef int (* ma_JackProcessCallback) (ma_jack_nframes_t nframes, void* arg);
  26149. typedef int (* ma_JackBufferSizeCallback)(ma_jack_nframes_t nframes, void* arg);
  26150. typedef void (* ma_JackShutdownCallback) (void* arg);
  26151. #define MA_JACK_DEFAULT_AUDIO_TYPE "32 bit float mono audio"
  26152. #define ma_JackNoStartServer 1
  26153. #define ma_JackPortIsInput 1
  26154. #define ma_JackPortIsOutput 2
  26155. #define ma_JackPortIsPhysical 4
  26156. #endif
  26157. typedef ma_jack_client_t* (* ma_jack_client_open_proc) (const char* client_name, ma_jack_options_t options, ma_jack_status_t* status, ...);
  26158. typedef int (* ma_jack_client_close_proc) (ma_jack_client_t* client);
  26159. typedef int (* ma_jack_client_name_size_proc) (void);
  26160. typedef int (* ma_jack_set_process_callback_proc) (ma_jack_client_t* client, ma_JackProcessCallback process_callback, void* arg);
  26161. typedef int (* ma_jack_set_buffer_size_callback_proc)(ma_jack_client_t* client, ma_JackBufferSizeCallback bufsize_callback, void* arg);
  26162. typedef void (* ma_jack_on_shutdown_proc) (ma_jack_client_t* client, ma_JackShutdownCallback function, void* arg);
  26163. typedef ma_jack_nframes_t (* ma_jack_get_sample_rate_proc) (ma_jack_client_t* client);
  26164. typedef ma_jack_nframes_t (* ma_jack_get_buffer_size_proc) (ma_jack_client_t* client);
  26165. typedef const char** (* ma_jack_get_ports_proc) (ma_jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags);
  26166. typedef int (* ma_jack_activate_proc) (ma_jack_client_t* client);
  26167. typedef int (* ma_jack_deactivate_proc) (ma_jack_client_t* client);
  26168. typedef int (* ma_jack_connect_proc) (ma_jack_client_t* client, const char* source_port, const char* destination_port);
  26169. typedef ma_jack_port_t* (* ma_jack_port_register_proc) (ma_jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size);
  26170. typedef const char* (* ma_jack_port_name_proc) (const ma_jack_port_t* port);
  26171. typedef void* (* ma_jack_port_get_buffer_proc) (ma_jack_port_t* port, ma_jack_nframes_t nframes);
  26172. typedef void (* ma_jack_free_proc) (void* ptr);
  26173. static ma_result ma_context_open_client__jack(ma_context* pContext, ma_jack_client_t** ppClient)
  26174. {
  26175. size_t maxClientNameSize;
  26176. char clientName[256];
  26177. ma_jack_status_t status;
  26178. ma_jack_client_t* pClient;
  26179. MA_ASSERT(pContext != NULL);
  26180. MA_ASSERT(ppClient != NULL);
  26181. if (ppClient) {
  26182. *ppClient = NULL;
  26183. }
  26184. maxClientNameSize = ((ma_jack_client_name_size_proc)pContext->jack.jack_client_name_size)(); /* Includes null terminator. */
  26185. ma_strncpy_s(clientName, ma_min(sizeof(clientName), maxClientNameSize), (pContext->jack.pClientName != NULL) ? pContext->jack.pClientName : "miniaudio", (size_t)-1);
  26186. pClient = ((ma_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->jack.tryStartServer) ? 0 : ma_JackNoStartServer, &status, NULL);
  26187. if (pClient == NULL) {
  26188. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26189. }
  26190. if (ppClient) {
  26191. *ppClient = pClient;
  26192. }
  26193. return MA_SUCCESS;
  26194. }
  26195. static ma_result ma_context_enumerate_devices__jack(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  26196. {
  26197. ma_bool32 cbResult = MA_TRUE;
  26198. MA_ASSERT(pContext != NULL);
  26199. MA_ASSERT(callback != NULL);
  26200. /* Playback. */
  26201. if (cbResult) {
  26202. ma_device_info deviceInfo;
  26203. MA_ZERO_OBJECT(&deviceInfo);
  26204. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  26205. deviceInfo.isDefault = MA_TRUE; /* JACK only uses default devices. */
  26206. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  26207. }
  26208. /* Capture. */
  26209. if (cbResult) {
  26210. ma_device_info deviceInfo;
  26211. MA_ZERO_OBJECT(&deviceInfo);
  26212. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  26213. deviceInfo.isDefault = MA_TRUE; /* JACK only uses default devices. */
  26214. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  26215. }
  26216. (void)cbResult; /* For silencing a static analysis warning. */
  26217. return MA_SUCCESS;
  26218. }
  26219. static ma_result ma_context_get_device_info__jack(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  26220. {
  26221. ma_jack_client_t* pClient;
  26222. ma_result result;
  26223. const char** ppPorts;
  26224. MA_ASSERT(pContext != NULL);
  26225. if (pDeviceID != NULL && pDeviceID->jack != 0) {
  26226. return MA_NO_DEVICE; /* Don't know the device. */
  26227. }
  26228. /* Name / Description */
  26229. if (deviceType == ma_device_type_playback) {
  26230. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  26231. } else {
  26232. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  26233. }
  26234. /* Jack only uses default devices. */
  26235. pDeviceInfo->isDefault = MA_TRUE;
  26236. /* Jack only supports f32 and has a specific channel count and sample rate. */
  26237. pDeviceInfo->nativeDataFormats[0].format = ma_format_f32;
  26238. /* The channel count and sample rate can only be determined by opening the device. */
  26239. result = ma_context_open_client__jack(pContext, &pClient);
  26240. if (result != MA_SUCCESS) {
  26241. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.");
  26242. return result;
  26243. }
  26244. pDeviceInfo->nativeDataFormats[0].sampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pClient);
  26245. pDeviceInfo->nativeDataFormats[0].channels = 0;
  26246. ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ((deviceType == ma_device_type_playback) ? ma_JackPortIsInput : ma_JackPortIsOutput));
  26247. if (ppPorts == NULL) {
  26248. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient);
  26249. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.");
  26250. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26251. }
  26252. while (ppPorts[pDeviceInfo->nativeDataFormats[0].channels] != NULL) {
  26253. pDeviceInfo->nativeDataFormats[0].channels += 1;
  26254. }
  26255. pDeviceInfo->nativeDataFormats[0].flags = 0;
  26256. pDeviceInfo->nativeDataFormatCount = 1;
  26257. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts);
  26258. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient);
  26259. (void)pContext;
  26260. return MA_SUCCESS;
  26261. }
  26262. static ma_result ma_device_uninit__jack(ma_device* pDevice)
  26263. {
  26264. ma_context* pContext;
  26265. MA_ASSERT(pDevice != NULL);
  26266. pContext = pDevice->pContext;
  26267. MA_ASSERT(pContext != NULL);
  26268. if (pDevice->jack.pClient != NULL) {
  26269. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDevice->jack.pClient);
  26270. }
  26271. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  26272. ma_free(pDevice->jack.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks);
  26273. ma_free(pDevice->jack.ppPortsCapture, &pDevice->pContext->allocationCallbacks);
  26274. }
  26275. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  26276. ma_free(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks);
  26277. ma_free(pDevice->jack.ppPortsPlayback, &pDevice->pContext->allocationCallbacks);
  26278. }
  26279. return MA_SUCCESS;
  26280. }
  26281. static void ma_device__jack_shutdown_callback(void* pUserData)
  26282. {
  26283. /* JACK died. Stop the device. */
  26284. ma_device* pDevice = (ma_device*)pUserData;
  26285. MA_ASSERT(pDevice != NULL);
  26286. ma_device_stop(pDevice);
  26287. }
  26288. static int ma_device__jack_buffer_size_callback(ma_jack_nframes_t frameCount, void* pUserData)
  26289. {
  26290. ma_device* pDevice = (ma_device*)pUserData;
  26291. MA_ASSERT(pDevice != NULL);
  26292. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  26293. size_t newBufferSize = frameCount * (pDevice->capture.internalChannels * ma_get_bytes_per_sample(pDevice->capture.internalFormat));
  26294. float* pNewBuffer = (float*)ma_calloc(newBufferSize, &pDevice->pContext->allocationCallbacks);
  26295. if (pNewBuffer == NULL) {
  26296. return MA_OUT_OF_MEMORY;
  26297. }
  26298. ma_free(pDevice->jack.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks);
  26299. pDevice->jack.pIntermediaryBufferCapture = pNewBuffer;
  26300. pDevice->playback.internalPeriodSizeInFrames = frameCount;
  26301. }
  26302. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  26303. size_t newBufferSize = frameCount * (pDevice->playback.internalChannels * ma_get_bytes_per_sample(pDevice->playback.internalFormat));
  26304. float* pNewBuffer = (float*)ma_calloc(newBufferSize, &pDevice->pContext->allocationCallbacks);
  26305. if (pNewBuffer == NULL) {
  26306. return MA_OUT_OF_MEMORY;
  26307. }
  26308. ma_free(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks);
  26309. pDevice->jack.pIntermediaryBufferPlayback = pNewBuffer;
  26310. pDevice->playback.internalPeriodSizeInFrames = frameCount;
  26311. }
  26312. return 0;
  26313. }
  26314. static int ma_device__jack_process_callback(ma_jack_nframes_t frameCount, void* pUserData)
  26315. {
  26316. ma_device* pDevice;
  26317. ma_context* pContext;
  26318. ma_uint32 iChannel;
  26319. pDevice = (ma_device*)pUserData;
  26320. MA_ASSERT(pDevice != NULL);
  26321. pContext = pDevice->pContext;
  26322. MA_ASSERT(pContext != NULL);
  26323. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  26324. /* Channels need to be interleaved. */
  26325. for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
  26326. const float* pSrc = (const float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.ppPortsCapture[iChannel], frameCount);
  26327. if (pSrc != NULL) {
  26328. float* pDst = pDevice->jack.pIntermediaryBufferCapture + iChannel;
  26329. ma_jack_nframes_t iFrame;
  26330. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  26331. *pDst = *pSrc;
  26332. pDst += pDevice->capture.internalChannels;
  26333. pSrc += 1;
  26334. }
  26335. }
  26336. }
  26337. ma_device_handle_backend_data_callback(pDevice, NULL, pDevice->jack.pIntermediaryBufferCapture, frameCount);
  26338. }
  26339. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  26340. ma_device_handle_backend_data_callback(pDevice, pDevice->jack.pIntermediaryBufferPlayback, NULL, frameCount);
  26341. /* Channels need to be deinterleaved. */
  26342. for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) {
  26343. float* pDst = (float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.ppPortsPlayback[iChannel], frameCount);
  26344. if (pDst != NULL) {
  26345. const float* pSrc = pDevice->jack.pIntermediaryBufferPlayback + iChannel;
  26346. ma_jack_nframes_t iFrame;
  26347. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  26348. *pDst = *pSrc;
  26349. pDst += 1;
  26350. pSrc += pDevice->playback.internalChannels;
  26351. }
  26352. }
  26353. }
  26354. }
  26355. return 0;
  26356. }
  26357. static ma_result ma_device_init__jack(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  26358. {
  26359. ma_result result;
  26360. ma_uint32 periodSizeInFrames;
  26361. MA_ASSERT(pConfig != NULL);
  26362. MA_ASSERT(pDevice != NULL);
  26363. if (pConfig->deviceType == ma_device_type_loopback) {
  26364. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Loopback mode not supported.");
  26365. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  26366. }
  26367. /* Only supporting default devices with JACK. */
  26368. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->pDeviceID != NULL && pDescriptorPlayback->pDeviceID->jack != 0) ||
  26369. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->pDeviceID != NULL && pDescriptorCapture->pDeviceID->jack != 0)) {
  26370. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Only default devices are supported.");
  26371. return MA_NO_DEVICE;
  26372. }
  26373. /* No exclusive mode with the JACK backend. */
  26374. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  26375. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  26376. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Exclusive mode not supported.");
  26377. return MA_SHARE_MODE_NOT_SUPPORTED;
  26378. }
  26379. /* Open the client. */
  26380. result = ma_context_open_client__jack(pDevice->pContext, (ma_jack_client_t**)&pDevice->jack.pClient);
  26381. if (result != MA_SUCCESS) {
  26382. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.");
  26383. return result;
  26384. }
  26385. /* Callbacks. */
  26386. if (((ma_jack_set_process_callback_proc)pDevice->pContext->jack.jack_set_process_callback)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_process_callback, pDevice) != 0) {
  26387. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to set process callback.");
  26388. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26389. }
  26390. if (((ma_jack_set_buffer_size_callback_proc)pDevice->pContext->jack.jack_set_buffer_size_callback)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_buffer_size_callback, pDevice) != 0) {
  26391. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to set buffer size callback.");
  26392. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26393. }
  26394. ((ma_jack_on_shutdown_proc)pDevice->pContext->jack.jack_on_shutdown)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_shutdown_callback, pDevice);
  26395. /* The buffer size in frames can change. */
  26396. periodSizeInFrames = ((ma_jack_get_buffer_size_proc)pDevice->pContext->jack.jack_get_buffer_size)((ma_jack_client_t*)pDevice->jack.pClient);
  26397. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  26398. ma_uint32 iPort;
  26399. const char** ppPorts;
  26400. pDescriptorCapture->format = ma_format_f32;
  26401. pDescriptorCapture->channels = 0;
  26402. pDescriptorCapture->sampleRate = ((ma_jack_get_sample_rate_proc)pDevice->pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient);
  26403. ma_channel_map_init_standard(ma_standard_channel_map_alsa, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  26404. ppPorts = ((ma_jack_get_ports_proc)pDevice->pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsOutput);
  26405. if (ppPorts == NULL) {
  26406. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.");
  26407. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26408. }
  26409. /* Need to count the number of ports first so we can allocate some memory. */
  26410. while (ppPorts[pDescriptorCapture->channels] != NULL) {
  26411. pDescriptorCapture->channels += 1;
  26412. }
  26413. pDevice->jack.ppPortsCapture = (ma_ptr*)ma_malloc(sizeof(*pDevice->jack.ppPortsCapture) * pDescriptorCapture->channels, &pDevice->pContext->allocationCallbacks);
  26414. if (pDevice->jack.ppPortsCapture == NULL) {
  26415. return MA_OUT_OF_MEMORY;
  26416. }
  26417. for (iPort = 0; iPort < pDescriptorCapture->channels; iPort += 1) {
  26418. char name[64];
  26419. ma_strcpy_s(name, sizeof(name), "capture");
  26420. ma_itoa_s((int)iPort, name+7, sizeof(name)-7, 10); /* 7 = length of "capture" */
  26421. pDevice->jack.ppPortsCapture[iPort] = ((ma_jack_port_register_proc)pDevice->pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsInput, 0);
  26422. if (pDevice->jack.ppPortsCapture[iPort] == NULL) {
  26423. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  26424. ma_device_uninit__jack(pDevice);
  26425. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.");
  26426. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26427. }
  26428. }
  26429. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  26430. pDescriptorCapture->periodSizeInFrames = periodSizeInFrames;
  26431. pDescriptorCapture->periodCount = 1; /* There's no notion of a period in JACK. Just set to 1. */
  26432. pDevice->jack.pIntermediaryBufferCapture = (float*)ma_calloc(pDescriptorCapture->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels), &pDevice->pContext->allocationCallbacks);
  26433. if (pDevice->jack.pIntermediaryBufferCapture == NULL) {
  26434. ma_device_uninit__jack(pDevice);
  26435. return MA_OUT_OF_MEMORY;
  26436. }
  26437. }
  26438. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  26439. ma_uint32 iPort;
  26440. const char** ppPorts;
  26441. pDescriptorPlayback->format = ma_format_f32;
  26442. pDescriptorPlayback->channels = 0;
  26443. pDescriptorPlayback->sampleRate = ((ma_jack_get_sample_rate_proc)pDevice->pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient);
  26444. ma_channel_map_init_standard(ma_standard_channel_map_alsa, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels);
  26445. ppPorts = ((ma_jack_get_ports_proc)pDevice->pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsInput);
  26446. if (ppPorts == NULL) {
  26447. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.");
  26448. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26449. }
  26450. /* Need to count the number of ports first so we can allocate some memory. */
  26451. while (ppPorts[pDescriptorPlayback->channels] != NULL) {
  26452. pDescriptorPlayback->channels += 1;
  26453. }
  26454. pDevice->jack.ppPortsPlayback = (ma_ptr*)ma_malloc(sizeof(*pDevice->jack.ppPortsPlayback) * pDescriptorPlayback->channels, &pDevice->pContext->allocationCallbacks);
  26455. if (pDevice->jack.ppPortsPlayback == NULL) {
  26456. ma_free(pDevice->jack.ppPortsCapture, &pDevice->pContext->allocationCallbacks);
  26457. return MA_OUT_OF_MEMORY;
  26458. }
  26459. for (iPort = 0; iPort < pDescriptorPlayback->channels; iPort += 1) {
  26460. char name[64];
  26461. ma_strcpy_s(name, sizeof(name), "playback");
  26462. ma_itoa_s((int)iPort, name+8, sizeof(name)-8, 10); /* 8 = length of "playback" */
  26463. pDevice->jack.ppPortsPlayback[iPort] = ((ma_jack_port_register_proc)pDevice->pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsOutput, 0);
  26464. if (pDevice->jack.ppPortsPlayback[iPort] == NULL) {
  26465. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  26466. ma_device_uninit__jack(pDevice);
  26467. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.");
  26468. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26469. }
  26470. }
  26471. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  26472. pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames;
  26473. pDescriptorPlayback->periodCount = 1; /* There's no notion of a period in JACK. Just set to 1. */
  26474. pDevice->jack.pIntermediaryBufferPlayback = (float*)ma_calloc(pDescriptorPlayback->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels), &pDevice->pContext->allocationCallbacks);
  26475. if (pDevice->jack.pIntermediaryBufferPlayback == NULL) {
  26476. ma_device_uninit__jack(pDevice);
  26477. return MA_OUT_OF_MEMORY;
  26478. }
  26479. }
  26480. return MA_SUCCESS;
  26481. }
  26482. static ma_result ma_device_start__jack(ma_device* pDevice)
  26483. {
  26484. ma_context* pContext = pDevice->pContext;
  26485. int resultJACK;
  26486. size_t i;
  26487. resultJACK = ((ma_jack_activate_proc)pContext->jack.jack_activate)((ma_jack_client_t*)pDevice->jack.pClient);
  26488. if (resultJACK != 0) {
  26489. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to activate the JACK client.");
  26490. return MA_FAILED_TO_START_BACKEND_DEVICE;
  26491. }
  26492. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  26493. const char** ppServerPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsOutput);
  26494. if (ppServerPorts == NULL) {
  26495. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  26496. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.");
  26497. return MA_ERROR;
  26498. }
  26499. for (i = 0; ppServerPorts[i] != NULL; ++i) {
  26500. const char* pServerPort = ppServerPorts[i];
  26501. const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.ppPortsCapture[i]);
  26502. resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pServerPort, pClientPort);
  26503. if (resultJACK != 0) {
  26504. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  26505. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  26506. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.");
  26507. return MA_ERROR;
  26508. }
  26509. }
  26510. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  26511. }
  26512. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  26513. const char** ppServerPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsInput);
  26514. if (ppServerPorts == NULL) {
  26515. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  26516. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.");
  26517. return MA_ERROR;
  26518. }
  26519. for (i = 0; ppServerPorts[i] != NULL; ++i) {
  26520. const char* pServerPort = ppServerPorts[i];
  26521. const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.ppPortsPlayback[i]);
  26522. resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pClientPort, pServerPort);
  26523. if (resultJACK != 0) {
  26524. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  26525. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  26526. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.");
  26527. return MA_ERROR;
  26528. }
  26529. }
  26530. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  26531. }
  26532. return MA_SUCCESS;
  26533. }
  26534. static ma_result ma_device_stop__jack(ma_device* pDevice)
  26535. {
  26536. ma_context* pContext = pDevice->pContext;
  26537. if (((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient) != 0) {
  26538. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] An error occurred when deactivating the JACK client.");
  26539. return MA_ERROR;
  26540. }
  26541. ma_device__on_notification_stopped(pDevice);
  26542. return MA_SUCCESS;
  26543. }
  26544. static ma_result ma_context_uninit__jack(ma_context* pContext)
  26545. {
  26546. MA_ASSERT(pContext != NULL);
  26547. MA_ASSERT(pContext->backend == ma_backend_jack);
  26548. ma_free(pContext->jack.pClientName, &pContext->allocationCallbacks);
  26549. pContext->jack.pClientName = NULL;
  26550. #ifndef MA_NO_RUNTIME_LINKING
  26551. ma_dlclose(pContext, pContext->jack.jackSO);
  26552. #endif
  26553. return MA_SUCCESS;
  26554. }
  26555. static ma_result ma_context_init__jack(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  26556. {
  26557. #ifndef MA_NO_RUNTIME_LINKING
  26558. const char* libjackNames[] = {
  26559. #if defined(MA_WIN32)
  26560. "libjack.dll",
  26561. "libjack64.dll"
  26562. #endif
  26563. #if defined(MA_UNIX)
  26564. "libjack.so",
  26565. "libjack.so.0"
  26566. #endif
  26567. };
  26568. size_t i;
  26569. for (i = 0; i < ma_countof(libjackNames); ++i) {
  26570. pContext->jack.jackSO = ma_dlopen(pContext, libjackNames[i]);
  26571. if (pContext->jack.jackSO != NULL) {
  26572. break;
  26573. }
  26574. }
  26575. if (pContext->jack.jackSO == NULL) {
  26576. return MA_NO_BACKEND;
  26577. }
  26578. pContext->jack.jack_client_open = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_client_open");
  26579. pContext->jack.jack_client_close = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_client_close");
  26580. pContext->jack.jack_client_name_size = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_client_name_size");
  26581. pContext->jack.jack_set_process_callback = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_set_process_callback");
  26582. pContext->jack.jack_set_buffer_size_callback = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_set_buffer_size_callback");
  26583. pContext->jack.jack_on_shutdown = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_on_shutdown");
  26584. pContext->jack.jack_get_sample_rate = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_get_sample_rate");
  26585. pContext->jack.jack_get_buffer_size = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_get_buffer_size");
  26586. pContext->jack.jack_get_ports = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_get_ports");
  26587. pContext->jack.jack_activate = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_activate");
  26588. pContext->jack.jack_deactivate = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_deactivate");
  26589. pContext->jack.jack_connect = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_connect");
  26590. pContext->jack.jack_port_register = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_port_register");
  26591. pContext->jack.jack_port_name = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_port_name");
  26592. pContext->jack.jack_port_get_buffer = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_port_get_buffer");
  26593. pContext->jack.jack_free = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_free");
  26594. #else
  26595. /*
  26596. This strange assignment system is here just to ensure type safety of miniaudio's function pointer
  26597. types. If anything differs slightly the compiler should throw a warning.
  26598. */
  26599. ma_jack_client_open_proc _jack_client_open = jack_client_open;
  26600. ma_jack_client_close_proc _jack_client_close = jack_client_close;
  26601. ma_jack_client_name_size_proc _jack_client_name_size = jack_client_name_size;
  26602. ma_jack_set_process_callback_proc _jack_set_process_callback = jack_set_process_callback;
  26603. ma_jack_set_buffer_size_callback_proc _jack_set_buffer_size_callback = jack_set_buffer_size_callback;
  26604. ma_jack_on_shutdown_proc _jack_on_shutdown = jack_on_shutdown;
  26605. ma_jack_get_sample_rate_proc _jack_get_sample_rate = jack_get_sample_rate;
  26606. ma_jack_get_buffer_size_proc _jack_get_buffer_size = jack_get_buffer_size;
  26607. ma_jack_get_ports_proc _jack_get_ports = jack_get_ports;
  26608. ma_jack_activate_proc _jack_activate = jack_activate;
  26609. ma_jack_deactivate_proc _jack_deactivate = jack_deactivate;
  26610. ma_jack_connect_proc _jack_connect = jack_connect;
  26611. ma_jack_port_register_proc _jack_port_register = jack_port_register;
  26612. ma_jack_port_name_proc _jack_port_name = jack_port_name;
  26613. ma_jack_port_get_buffer_proc _jack_port_get_buffer = jack_port_get_buffer;
  26614. ma_jack_free_proc _jack_free = jack_free;
  26615. pContext->jack.jack_client_open = (ma_proc)_jack_client_open;
  26616. pContext->jack.jack_client_close = (ma_proc)_jack_client_close;
  26617. pContext->jack.jack_client_name_size = (ma_proc)_jack_client_name_size;
  26618. pContext->jack.jack_set_process_callback = (ma_proc)_jack_set_process_callback;
  26619. pContext->jack.jack_set_buffer_size_callback = (ma_proc)_jack_set_buffer_size_callback;
  26620. pContext->jack.jack_on_shutdown = (ma_proc)_jack_on_shutdown;
  26621. pContext->jack.jack_get_sample_rate = (ma_proc)_jack_get_sample_rate;
  26622. pContext->jack.jack_get_buffer_size = (ma_proc)_jack_get_buffer_size;
  26623. pContext->jack.jack_get_ports = (ma_proc)_jack_get_ports;
  26624. pContext->jack.jack_activate = (ma_proc)_jack_activate;
  26625. pContext->jack.jack_deactivate = (ma_proc)_jack_deactivate;
  26626. pContext->jack.jack_connect = (ma_proc)_jack_connect;
  26627. pContext->jack.jack_port_register = (ma_proc)_jack_port_register;
  26628. pContext->jack.jack_port_name = (ma_proc)_jack_port_name;
  26629. pContext->jack.jack_port_get_buffer = (ma_proc)_jack_port_get_buffer;
  26630. pContext->jack.jack_free = (ma_proc)_jack_free;
  26631. #endif
  26632. if (pConfig->jack.pClientName != NULL) {
  26633. pContext->jack.pClientName = ma_copy_string(pConfig->jack.pClientName, &pContext->allocationCallbacks);
  26634. }
  26635. pContext->jack.tryStartServer = pConfig->jack.tryStartServer;
  26636. /*
  26637. Getting here means the JACK library is installed, but it doesn't necessarily mean it's usable. We need to quickly test this by connecting
  26638. a temporary client.
  26639. */
  26640. {
  26641. ma_jack_client_t* pDummyClient;
  26642. ma_result result = ma_context_open_client__jack(pContext, &pDummyClient);
  26643. if (result != MA_SUCCESS) {
  26644. ma_free(pContext->jack.pClientName, &pContext->allocationCallbacks);
  26645. #ifndef MA_NO_RUNTIME_LINKING
  26646. ma_dlclose(pContext, pContext->jack.jackSO);
  26647. #endif
  26648. return MA_NO_BACKEND;
  26649. }
  26650. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDummyClient);
  26651. }
  26652. pCallbacks->onContextInit = ma_context_init__jack;
  26653. pCallbacks->onContextUninit = ma_context_uninit__jack;
  26654. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__jack;
  26655. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__jack;
  26656. pCallbacks->onDeviceInit = ma_device_init__jack;
  26657. pCallbacks->onDeviceUninit = ma_device_uninit__jack;
  26658. pCallbacks->onDeviceStart = ma_device_start__jack;
  26659. pCallbacks->onDeviceStop = ma_device_stop__jack;
  26660. pCallbacks->onDeviceRead = NULL; /* Not used because JACK is asynchronous. */
  26661. pCallbacks->onDeviceWrite = NULL; /* Not used because JACK is asynchronous. */
  26662. pCallbacks->onDeviceDataLoop = NULL; /* Not used because JACK is asynchronous. */
  26663. return MA_SUCCESS;
  26664. }
  26665. #endif /* JACK */
  26666. /******************************************************************************
  26667. Core Audio Backend
  26668. References
  26669. ==========
  26670. - Technical Note TN2091: Device input using the HAL Output Audio Unit
  26671. https://developer.apple.com/library/archive/technotes/tn2091/_index.html
  26672. ******************************************************************************/
  26673. #ifdef MA_HAS_COREAUDIO
  26674. #include <TargetConditionals.h>
  26675. #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1
  26676. #define MA_APPLE_MOBILE
  26677. #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
  26678. #define MA_APPLE_TV
  26679. #endif
  26680. #if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
  26681. #define MA_APPLE_WATCH
  26682. #endif
  26683. #if __has_feature(objc_arc)
  26684. #define MA_BRIDGE_TRANSFER __bridge_transfer
  26685. #define MA_BRIDGE_RETAINED __bridge_retained
  26686. #else
  26687. #define MA_BRIDGE_TRANSFER
  26688. #define MA_BRIDGE_RETAINED
  26689. #endif
  26690. #else
  26691. #define MA_APPLE_DESKTOP
  26692. #endif
  26693. #if defined(MA_APPLE_DESKTOP)
  26694. #include <CoreAudio/CoreAudio.h>
  26695. #else
  26696. #include <AVFoundation/AVFoundation.h>
  26697. #endif
  26698. #include <AudioToolbox/AudioToolbox.h>
  26699. /* CoreFoundation */
  26700. typedef Boolean (* ma_CFStringGetCString_proc)(CFStringRef theString, char* buffer, CFIndex bufferSize, CFStringEncoding encoding);
  26701. typedef void (* ma_CFRelease_proc)(CFTypeRef cf);
  26702. /* CoreAudio */
  26703. #if defined(MA_APPLE_DESKTOP)
  26704. typedef OSStatus (* ma_AudioObjectGetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* ioDataSize, void* outData);
  26705. typedef OSStatus (* ma_AudioObjectGetPropertyDataSize_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* outDataSize);
  26706. typedef OSStatus (* ma_AudioObjectSetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, const void* inData);
  26707. typedef OSStatus (* ma_AudioObjectAddPropertyListener_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, AudioObjectPropertyListenerProc inListener, void* inClientData);
  26708. typedef OSStatus (* ma_AudioObjectRemovePropertyListener_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, AudioObjectPropertyListenerProc inListener, void* inClientData);
  26709. #endif
  26710. /* AudioToolbox */
  26711. typedef AudioComponent (* ma_AudioComponentFindNext_proc)(AudioComponent inComponent, const AudioComponentDescription* inDesc);
  26712. typedef OSStatus (* ma_AudioComponentInstanceDispose_proc)(AudioComponentInstance inInstance);
  26713. typedef OSStatus (* ma_AudioComponentInstanceNew_proc)(AudioComponent inComponent, AudioComponentInstance* outInstance);
  26714. typedef OSStatus (* ma_AudioOutputUnitStart_proc)(AudioUnit inUnit);
  26715. typedef OSStatus (* ma_AudioOutputUnitStop_proc)(AudioUnit inUnit);
  26716. typedef OSStatus (* ma_AudioUnitAddPropertyListener_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitPropertyListenerProc inProc, void* inProcUserData);
  26717. typedef OSStatus (* ma_AudioUnitGetPropertyInfo_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32* outDataSize, Boolean* outWriteable);
  26718. typedef OSStatus (* ma_AudioUnitGetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void* outData, UInt32* ioDataSize);
  26719. typedef OSStatus (* ma_AudioUnitSetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, const void* inData, UInt32 inDataSize);
  26720. typedef OSStatus (* ma_AudioUnitInitialize_proc)(AudioUnit inUnit);
  26721. typedef OSStatus (* ma_AudioUnitRender_proc)(AudioUnit inUnit, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inOutputBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData);
  26722. #define MA_COREAUDIO_OUTPUT_BUS 0
  26723. #define MA_COREAUDIO_INPUT_BUS 1
  26724. #if defined(MA_APPLE_DESKTOP)
  26725. static ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit);
  26726. #endif
  26727. /*
  26728. Core Audio
  26729. So far, Core Audio has been the worst backend to work with due to being both unintuitive and having almost no documentation
  26730. apart from comments in the headers (which admittedly are quite good). For my own purposes, and for anybody out there whose
  26731. needing to figure out how this darn thing works, I'm going to outline a few things here.
  26732. Since miniaudio is a fairly low-level API, one of the things it needs is control over specific devices, and it needs to be
  26733. able to identify whether or not it can be used as playback and/or capture. The AudioObject API is the only one I've seen
  26734. that supports this level of detail. There was some public domain sample code I stumbled across that used the AudioComponent
  26735. and AudioUnit APIs, but I couldn't see anything that gave low-level control over device selection and capabilities (the
  26736. distinction between playback and capture in particular). Therefore, miniaudio is using the AudioObject API.
  26737. Most (all?) functions in the AudioObject API take a AudioObjectID as it's input. This is the device identifier. When
  26738. retrieving global information, such as the device list, you use kAudioObjectSystemObject. When retrieving device-specific
  26739. data, you pass in the ID for that device. In order to retrieve device-specific IDs you need to enumerate over each of the
  26740. devices. This is done using the AudioObjectGetPropertyDataSize() and AudioObjectGetPropertyData() APIs which seem to be
  26741. the central APIs for retrieving information about the system and specific devices.
  26742. To use the AudioObjectGetPropertyData() API you need to use the notion of a property address. A property address is a
  26743. structure with three variables and is used to identify which property you are getting or setting. The first is the "selector"
  26744. which is basically the specific property that you're wanting to retrieve or set. The second is the "scope", which is
  26745. typically set to kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeInput for input-specific properties and
  26746. kAudioObjectPropertyScopeOutput for output-specific properties. The last is the "element" which is always set to
  26747. kAudioObjectPropertyElementMain in miniaudio's case. I don't know of any cases where this would be set to anything different.
  26748. Back to the earlier issue of device retrieval, you first use the AudioObjectGetPropertyDataSize() API to retrieve the size
  26749. of the raw data which is just a list of AudioDeviceID's. You use the kAudioObjectSystemObject AudioObjectID, and a property
  26750. address with the kAudioHardwarePropertyDevices selector and the kAudioObjectPropertyScopeGlobal scope. Once you have the
  26751. size, allocate a block of memory of that size and then call AudioObjectGetPropertyData(). The data is just a list of
  26752. AudioDeviceID's so just do "dataSize/sizeof(AudioDeviceID)" to know the device count.
  26753. */
  26754. static ma_result ma_result_from_OSStatus(OSStatus status)
  26755. {
  26756. switch (status)
  26757. {
  26758. case noErr: return MA_SUCCESS;
  26759. #if defined(MA_APPLE_DESKTOP)
  26760. case kAudioHardwareNotRunningError: return MA_DEVICE_NOT_STARTED;
  26761. case kAudioHardwareUnspecifiedError: return MA_ERROR;
  26762. case kAudioHardwareUnknownPropertyError: return MA_INVALID_ARGS;
  26763. case kAudioHardwareBadPropertySizeError: return MA_INVALID_OPERATION;
  26764. case kAudioHardwareIllegalOperationError: return MA_INVALID_OPERATION;
  26765. case kAudioHardwareBadObjectError: return MA_INVALID_ARGS;
  26766. case kAudioHardwareBadDeviceError: return MA_INVALID_ARGS;
  26767. case kAudioHardwareBadStreamError: return MA_INVALID_ARGS;
  26768. case kAudioHardwareUnsupportedOperationError: return MA_INVALID_OPERATION;
  26769. case kAudioDeviceUnsupportedFormatError: return MA_FORMAT_NOT_SUPPORTED;
  26770. case kAudioDevicePermissionsError: return MA_ACCESS_DENIED;
  26771. #endif
  26772. default: return MA_ERROR;
  26773. }
  26774. }
  26775. #if 0
  26776. static ma_channel ma_channel_from_AudioChannelBitmap(AudioChannelBitmap bit)
  26777. {
  26778. switch (bit)
  26779. {
  26780. case kAudioChannelBit_Left: return MA_CHANNEL_LEFT;
  26781. case kAudioChannelBit_Right: return MA_CHANNEL_RIGHT;
  26782. case kAudioChannelBit_Center: return MA_CHANNEL_FRONT_CENTER;
  26783. case kAudioChannelBit_LFEScreen: return MA_CHANNEL_LFE;
  26784. case kAudioChannelBit_LeftSurround: return MA_CHANNEL_BACK_LEFT;
  26785. case kAudioChannelBit_RightSurround: return MA_CHANNEL_BACK_RIGHT;
  26786. case kAudioChannelBit_LeftCenter: return MA_CHANNEL_FRONT_LEFT_CENTER;
  26787. case kAudioChannelBit_RightCenter: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  26788. case kAudioChannelBit_CenterSurround: return MA_CHANNEL_BACK_CENTER;
  26789. case kAudioChannelBit_LeftSurroundDirect: return MA_CHANNEL_SIDE_LEFT;
  26790. case kAudioChannelBit_RightSurroundDirect: return MA_CHANNEL_SIDE_RIGHT;
  26791. case kAudioChannelBit_TopCenterSurround: return MA_CHANNEL_TOP_CENTER;
  26792. case kAudioChannelBit_VerticalHeightLeft: return MA_CHANNEL_TOP_FRONT_LEFT;
  26793. case kAudioChannelBit_VerticalHeightCenter: return MA_CHANNEL_TOP_FRONT_CENTER;
  26794. case kAudioChannelBit_VerticalHeightRight: return MA_CHANNEL_TOP_FRONT_RIGHT;
  26795. case kAudioChannelBit_TopBackLeft: return MA_CHANNEL_TOP_BACK_LEFT;
  26796. case kAudioChannelBit_TopBackCenter: return MA_CHANNEL_TOP_BACK_CENTER;
  26797. case kAudioChannelBit_TopBackRight: return MA_CHANNEL_TOP_BACK_RIGHT;
  26798. default: return MA_CHANNEL_NONE;
  26799. }
  26800. }
  26801. #endif
  26802. static ma_result ma_format_from_AudioStreamBasicDescription(const AudioStreamBasicDescription* pDescription, ma_format* pFormatOut)
  26803. {
  26804. MA_ASSERT(pDescription != NULL);
  26805. MA_ASSERT(pFormatOut != NULL);
  26806. *pFormatOut = ma_format_unknown; /* Safety. */
  26807. /* There's a few things miniaudio doesn't support. */
  26808. if (pDescription->mFormatID != kAudioFormatLinearPCM) {
  26809. return MA_FORMAT_NOT_SUPPORTED;
  26810. }
  26811. /* We don't support any non-packed formats that are aligned high. */
  26812. if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsAlignedHigh) != 0) {
  26813. return MA_FORMAT_NOT_SUPPORTED;
  26814. }
  26815. /* Only supporting native-endian. */
  26816. if ((ma_is_little_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) != 0) || (ma_is_big_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) == 0)) {
  26817. return MA_FORMAT_NOT_SUPPORTED;
  26818. }
  26819. /* We are not currently supporting non-interleaved formats (this will be added in a future version of miniaudio). */
  26820. /*if ((pDescription->mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0) {
  26821. return MA_FORMAT_NOT_SUPPORTED;
  26822. }*/
  26823. if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsFloat) != 0) {
  26824. if (pDescription->mBitsPerChannel == 32) {
  26825. *pFormatOut = ma_format_f32;
  26826. return MA_SUCCESS;
  26827. }
  26828. } else {
  26829. if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsSignedInteger) != 0) {
  26830. if (pDescription->mBitsPerChannel == 16) {
  26831. *pFormatOut = ma_format_s16;
  26832. return MA_SUCCESS;
  26833. } else if (pDescription->mBitsPerChannel == 24) {
  26834. if (pDescription->mBytesPerFrame == (pDescription->mBitsPerChannel/8 * pDescription->mChannelsPerFrame)) {
  26835. *pFormatOut = ma_format_s24;
  26836. return MA_SUCCESS;
  26837. } else {
  26838. if (pDescription->mBytesPerFrame/pDescription->mChannelsPerFrame == sizeof(ma_int32)) {
  26839. /* TODO: Implement ma_format_s24_32. */
  26840. /**pFormatOut = ma_format_s24_32;*/
  26841. /*return MA_SUCCESS;*/
  26842. return MA_FORMAT_NOT_SUPPORTED;
  26843. }
  26844. }
  26845. } else if (pDescription->mBitsPerChannel == 32) {
  26846. *pFormatOut = ma_format_s32;
  26847. return MA_SUCCESS;
  26848. }
  26849. } else {
  26850. if (pDescription->mBitsPerChannel == 8) {
  26851. *pFormatOut = ma_format_u8;
  26852. return MA_SUCCESS;
  26853. }
  26854. }
  26855. }
  26856. /* Getting here means the format is not supported. */
  26857. return MA_FORMAT_NOT_SUPPORTED;
  26858. }
  26859. #if defined(MA_APPLE_DESKTOP)
  26860. static ma_channel ma_channel_from_AudioChannelLabel(AudioChannelLabel label)
  26861. {
  26862. switch (label)
  26863. {
  26864. case kAudioChannelLabel_Unknown: return MA_CHANNEL_NONE;
  26865. case kAudioChannelLabel_Unused: return MA_CHANNEL_NONE;
  26866. case kAudioChannelLabel_UseCoordinates: return MA_CHANNEL_NONE;
  26867. case kAudioChannelLabel_Left: return MA_CHANNEL_LEFT;
  26868. case kAudioChannelLabel_Right: return MA_CHANNEL_RIGHT;
  26869. case kAudioChannelLabel_Center: return MA_CHANNEL_FRONT_CENTER;
  26870. case kAudioChannelLabel_LFEScreen: return MA_CHANNEL_LFE;
  26871. case kAudioChannelLabel_LeftSurround: return MA_CHANNEL_BACK_LEFT;
  26872. case kAudioChannelLabel_RightSurround: return MA_CHANNEL_BACK_RIGHT;
  26873. case kAudioChannelLabel_LeftCenter: return MA_CHANNEL_FRONT_LEFT_CENTER;
  26874. case kAudioChannelLabel_RightCenter: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  26875. case kAudioChannelLabel_CenterSurround: return MA_CHANNEL_BACK_CENTER;
  26876. case kAudioChannelLabel_LeftSurroundDirect: return MA_CHANNEL_SIDE_LEFT;
  26877. case kAudioChannelLabel_RightSurroundDirect: return MA_CHANNEL_SIDE_RIGHT;
  26878. case kAudioChannelLabel_TopCenterSurround: return MA_CHANNEL_TOP_CENTER;
  26879. case kAudioChannelLabel_VerticalHeightLeft: return MA_CHANNEL_TOP_FRONT_LEFT;
  26880. case kAudioChannelLabel_VerticalHeightCenter: return MA_CHANNEL_TOP_FRONT_CENTER;
  26881. case kAudioChannelLabel_VerticalHeightRight: return MA_CHANNEL_TOP_FRONT_RIGHT;
  26882. case kAudioChannelLabel_TopBackLeft: return MA_CHANNEL_TOP_BACK_LEFT;
  26883. case kAudioChannelLabel_TopBackCenter: return MA_CHANNEL_TOP_BACK_CENTER;
  26884. case kAudioChannelLabel_TopBackRight: return MA_CHANNEL_TOP_BACK_RIGHT;
  26885. case kAudioChannelLabel_RearSurroundLeft: return MA_CHANNEL_BACK_LEFT;
  26886. case kAudioChannelLabel_RearSurroundRight: return MA_CHANNEL_BACK_RIGHT;
  26887. case kAudioChannelLabel_LeftWide: return MA_CHANNEL_SIDE_LEFT;
  26888. case kAudioChannelLabel_RightWide: return MA_CHANNEL_SIDE_RIGHT;
  26889. case kAudioChannelLabel_LFE2: return MA_CHANNEL_LFE;
  26890. case kAudioChannelLabel_LeftTotal: return MA_CHANNEL_LEFT;
  26891. case kAudioChannelLabel_RightTotal: return MA_CHANNEL_RIGHT;
  26892. case kAudioChannelLabel_HearingImpaired: return MA_CHANNEL_NONE;
  26893. case kAudioChannelLabel_Narration: return MA_CHANNEL_MONO;
  26894. case kAudioChannelLabel_Mono: return MA_CHANNEL_MONO;
  26895. case kAudioChannelLabel_DialogCentricMix: return MA_CHANNEL_MONO;
  26896. case kAudioChannelLabel_CenterSurroundDirect: return MA_CHANNEL_BACK_CENTER;
  26897. case kAudioChannelLabel_Haptic: return MA_CHANNEL_NONE;
  26898. case kAudioChannelLabel_Ambisonic_W: return MA_CHANNEL_NONE;
  26899. case kAudioChannelLabel_Ambisonic_X: return MA_CHANNEL_NONE;
  26900. case kAudioChannelLabel_Ambisonic_Y: return MA_CHANNEL_NONE;
  26901. case kAudioChannelLabel_Ambisonic_Z: return MA_CHANNEL_NONE;
  26902. case kAudioChannelLabel_MS_Mid: return MA_CHANNEL_LEFT;
  26903. case kAudioChannelLabel_MS_Side: return MA_CHANNEL_RIGHT;
  26904. case kAudioChannelLabel_XY_X: return MA_CHANNEL_LEFT;
  26905. case kAudioChannelLabel_XY_Y: return MA_CHANNEL_RIGHT;
  26906. case kAudioChannelLabel_HeadphonesLeft: return MA_CHANNEL_LEFT;
  26907. case kAudioChannelLabel_HeadphonesRight: return MA_CHANNEL_RIGHT;
  26908. case kAudioChannelLabel_ClickTrack: return MA_CHANNEL_NONE;
  26909. case kAudioChannelLabel_ForeignLanguage: return MA_CHANNEL_NONE;
  26910. case kAudioChannelLabel_Discrete: return MA_CHANNEL_NONE;
  26911. case kAudioChannelLabel_Discrete_0: return MA_CHANNEL_AUX_0;
  26912. case kAudioChannelLabel_Discrete_1: return MA_CHANNEL_AUX_1;
  26913. case kAudioChannelLabel_Discrete_2: return MA_CHANNEL_AUX_2;
  26914. case kAudioChannelLabel_Discrete_3: return MA_CHANNEL_AUX_3;
  26915. case kAudioChannelLabel_Discrete_4: return MA_CHANNEL_AUX_4;
  26916. case kAudioChannelLabel_Discrete_5: return MA_CHANNEL_AUX_5;
  26917. case kAudioChannelLabel_Discrete_6: return MA_CHANNEL_AUX_6;
  26918. case kAudioChannelLabel_Discrete_7: return MA_CHANNEL_AUX_7;
  26919. case kAudioChannelLabel_Discrete_8: return MA_CHANNEL_AUX_8;
  26920. case kAudioChannelLabel_Discrete_9: return MA_CHANNEL_AUX_9;
  26921. case kAudioChannelLabel_Discrete_10: return MA_CHANNEL_AUX_10;
  26922. case kAudioChannelLabel_Discrete_11: return MA_CHANNEL_AUX_11;
  26923. case kAudioChannelLabel_Discrete_12: return MA_CHANNEL_AUX_12;
  26924. case kAudioChannelLabel_Discrete_13: return MA_CHANNEL_AUX_13;
  26925. case kAudioChannelLabel_Discrete_14: return MA_CHANNEL_AUX_14;
  26926. case kAudioChannelLabel_Discrete_15: return MA_CHANNEL_AUX_15;
  26927. case kAudioChannelLabel_Discrete_65535: return MA_CHANNEL_NONE;
  26928. #if 0 /* Introduced in a later version of macOS. */
  26929. case kAudioChannelLabel_HOA_ACN: return MA_CHANNEL_NONE;
  26930. case kAudioChannelLabel_HOA_ACN_0: return MA_CHANNEL_AUX_0;
  26931. case kAudioChannelLabel_HOA_ACN_1: return MA_CHANNEL_AUX_1;
  26932. case kAudioChannelLabel_HOA_ACN_2: return MA_CHANNEL_AUX_2;
  26933. case kAudioChannelLabel_HOA_ACN_3: return MA_CHANNEL_AUX_3;
  26934. case kAudioChannelLabel_HOA_ACN_4: return MA_CHANNEL_AUX_4;
  26935. case kAudioChannelLabel_HOA_ACN_5: return MA_CHANNEL_AUX_5;
  26936. case kAudioChannelLabel_HOA_ACN_6: return MA_CHANNEL_AUX_6;
  26937. case kAudioChannelLabel_HOA_ACN_7: return MA_CHANNEL_AUX_7;
  26938. case kAudioChannelLabel_HOA_ACN_8: return MA_CHANNEL_AUX_8;
  26939. case kAudioChannelLabel_HOA_ACN_9: return MA_CHANNEL_AUX_9;
  26940. case kAudioChannelLabel_HOA_ACN_10: return MA_CHANNEL_AUX_10;
  26941. case kAudioChannelLabel_HOA_ACN_11: return MA_CHANNEL_AUX_11;
  26942. case kAudioChannelLabel_HOA_ACN_12: return MA_CHANNEL_AUX_12;
  26943. case kAudioChannelLabel_HOA_ACN_13: return MA_CHANNEL_AUX_13;
  26944. case kAudioChannelLabel_HOA_ACN_14: return MA_CHANNEL_AUX_14;
  26945. case kAudioChannelLabel_HOA_ACN_15: return MA_CHANNEL_AUX_15;
  26946. case kAudioChannelLabel_HOA_ACN_65024: return MA_CHANNEL_NONE;
  26947. #endif
  26948. default: return MA_CHANNEL_NONE;
  26949. }
  26950. }
  26951. static ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChannelLayout, ma_channel* pChannelMap, size_t channelMapCap)
  26952. {
  26953. MA_ASSERT(pChannelLayout != NULL);
  26954. if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) {
  26955. UInt32 iChannel;
  26956. for (iChannel = 0; iChannel < pChannelLayout->mNumberChannelDescriptions && iChannel < channelMapCap; ++iChannel) {
  26957. pChannelMap[iChannel] = ma_channel_from_AudioChannelLabel(pChannelLayout->mChannelDescriptions[iChannel].mChannelLabel);
  26958. }
  26959. } else
  26960. #if 0
  26961. if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
  26962. /* This is the same kind of system that's used by Windows audio APIs. */
  26963. UInt32 iChannel = 0;
  26964. UInt32 iBit;
  26965. AudioChannelBitmap bitmap = pChannelLayout->mChannelBitmap;
  26966. for (iBit = 0; iBit < 32 && iChannel < channelMapCap; ++iBit) {
  26967. AudioChannelBitmap bit = bitmap & (1 << iBit);
  26968. if (bit != 0) {
  26969. pChannelMap[iChannel++] = ma_channel_from_AudioChannelBit(bit);
  26970. }
  26971. }
  26972. } else
  26973. #endif
  26974. {
  26975. /*
  26976. Need to use the tag to determine the channel map. For now I'm just assuming a default channel map, but later on this should
  26977. be updated to determine the mapping based on the tag.
  26978. */
  26979. UInt32 channelCount;
  26980. /* Our channel map retrieval APIs below take 32-bit integers, so we'll want to clamp the channel map capacity. */
  26981. if (channelMapCap > 0xFFFFFFFF) {
  26982. channelMapCap = 0xFFFFFFFF;
  26983. }
  26984. channelCount = ma_min(AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag), (UInt32)channelMapCap);
  26985. switch (pChannelLayout->mChannelLayoutTag)
  26986. {
  26987. case kAudioChannelLayoutTag_Mono:
  26988. case kAudioChannelLayoutTag_Stereo:
  26989. case kAudioChannelLayoutTag_StereoHeadphones:
  26990. case kAudioChannelLayoutTag_MatrixStereo:
  26991. case kAudioChannelLayoutTag_MidSide:
  26992. case kAudioChannelLayoutTag_XY:
  26993. case kAudioChannelLayoutTag_Binaural:
  26994. case kAudioChannelLayoutTag_Ambisonic_B_Format:
  26995. {
  26996. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount);
  26997. } break;
  26998. case kAudioChannelLayoutTag_Octagonal:
  26999. {
  27000. pChannelMap[7] = MA_CHANNEL_SIDE_RIGHT;
  27001. pChannelMap[6] = MA_CHANNEL_SIDE_LEFT;
  27002. } MA_FALLTHROUGH; /* Intentional fallthrough. */
  27003. case kAudioChannelLayoutTag_Hexagonal:
  27004. {
  27005. pChannelMap[5] = MA_CHANNEL_BACK_CENTER;
  27006. } MA_FALLTHROUGH; /* Intentional fallthrough. */
  27007. case kAudioChannelLayoutTag_Pentagonal:
  27008. {
  27009. pChannelMap[4] = MA_CHANNEL_FRONT_CENTER;
  27010. } MA_FALLTHROUGH; /* Intentional fallthrough. */
  27011. case kAudioChannelLayoutTag_Quadraphonic:
  27012. {
  27013. pChannelMap[3] = MA_CHANNEL_BACK_RIGHT;
  27014. pChannelMap[2] = MA_CHANNEL_BACK_LEFT;
  27015. pChannelMap[1] = MA_CHANNEL_RIGHT;
  27016. pChannelMap[0] = MA_CHANNEL_LEFT;
  27017. } break;
  27018. /* TODO: Add support for more tags here. */
  27019. default:
  27020. {
  27021. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount);
  27022. } break;
  27023. }
  27024. }
  27025. return MA_SUCCESS;
  27026. }
  27027. #if (defined(MAC_OS_VERSION_12_0) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_12_0) || \
  27028. (defined(__IPHONE_15_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_0)
  27029. #define AUDIO_OBJECT_PROPERTY_ELEMENT kAudioObjectPropertyElementMain
  27030. #else
  27031. /* kAudioObjectPropertyElementMaster is deprecated. */
  27032. #define AUDIO_OBJECT_PROPERTY_ELEMENT kAudioObjectPropertyElementMaster
  27033. #endif
  27034. static ma_result ma_get_device_object_ids__coreaudio(ma_context* pContext, UInt32* pDeviceCount, AudioObjectID** ppDeviceObjectIDs) /* NOTE: Free the returned buffer with ma_free(). */
  27035. {
  27036. AudioObjectPropertyAddress propAddressDevices;
  27037. UInt32 deviceObjectsDataSize;
  27038. OSStatus status;
  27039. AudioObjectID* pDeviceObjectIDs;
  27040. MA_ASSERT(pContext != NULL);
  27041. MA_ASSERT(pDeviceCount != NULL);
  27042. MA_ASSERT(ppDeviceObjectIDs != NULL);
  27043. /* Safety. */
  27044. *pDeviceCount = 0;
  27045. *ppDeviceObjectIDs = NULL;
  27046. propAddressDevices.mSelector = kAudioHardwarePropertyDevices;
  27047. propAddressDevices.mScope = kAudioObjectPropertyScopeGlobal;
  27048. propAddressDevices.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27049. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize);
  27050. if (status != noErr) {
  27051. return ma_result_from_OSStatus(status);
  27052. }
  27053. pDeviceObjectIDs = (AudioObjectID*)ma_malloc(deviceObjectsDataSize, &pContext->allocationCallbacks);
  27054. if (pDeviceObjectIDs == NULL) {
  27055. return MA_OUT_OF_MEMORY;
  27056. }
  27057. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize, pDeviceObjectIDs);
  27058. if (status != noErr) {
  27059. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27060. return ma_result_from_OSStatus(status);
  27061. }
  27062. *pDeviceCount = deviceObjectsDataSize / sizeof(AudioObjectID);
  27063. *ppDeviceObjectIDs = pDeviceObjectIDs;
  27064. return MA_SUCCESS;
  27065. }
  27066. static ma_result ma_get_AudioObject_uid_as_CFStringRef(ma_context* pContext, AudioObjectID objectID, CFStringRef* pUID)
  27067. {
  27068. AudioObjectPropertyAddress propAddress;
  27069. UInt32 dataSize;
  27070. OSStatus status;
  27071. MA_ASSERT(pContext != NULL);
  27072. propAddress.mSelector = kAudioDevicePropertyDeviceUID;
  27073. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  27074. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27075. dataSize = sizeof(*pUID);
  27076. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, pUID);
  27077. if (status != noErr) {
  27078. return ma_result_from_OSStatus(status);
  27079. }
  27080. return MA_SUCCESS;
  27081. }
  27082. static ma_result ma_get_AudioObject_uid(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut)
  27083. {
  27084. CFStringRef uid;
  27085. ma_result result;
  27086. MA_ASSERT(pContext != NULL);
  27087. result = ma_get_AudioObject_uid_as_CFStringRef(pContext, objectID, &uid);
  27088. if (result != MA_SUCCESS) {
  27089. return result;
  27090. }
  27091. if (!((ma_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(uid, bufferOut, bufferSize, kCFStringEncodingUTF8)) {
  27092. return MA_ERROR;
  27093. }
  27094. ((ma_CFRelease_proc)pContext->coreaudio.CFRelease)(uid);
  27095. return MA_SUCCESS;
  27096. }
  27097. static ma_result ma_get_AudioObject_name(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut)
  27098. {
  27099. AudioObjectPropertyAddress propAddress;
  27100. CFStringRef deviceName = NULL;
  27101. UInt32 dataSize;
  27102. OSStatus status;
  27103. MA_ASSERT(pContext != NULL);
  27104. propAddress.mSelector = kAudioDevicePropertyDeviceNameCFString;
  27105. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  27106. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27107. dataSize = sizeof(deviceName);
  27108. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, &deviceName);
  27109. if (status != noErr) {
  27110. return ma_result_from_OSStatus(status);
  27111. }
  27112. if (!((ma_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(deviceName, bufferOut, bufferSize, kCFStringEncodingUTF8)) {
  27113. return MA_ERROR;
  27114. }
  27115. ((ma_CFRelease_proc)pContext->coreaudio.CFRelease)(deviceName);
  27116. return MA_SUCCESS;
  27117. }
  27118. static ma_bool32 ma_does_AudioObject_support_scope(ma_context* pContext, AudioObjectID deviceObjectID, AudioObjectPropertyScope scope)
  27119. {
  27120. AudioObjectPropertyAddress propAddress;
  27121. UInt32 dataSize;
  27122. OSStatus status;
  27123. AudioBufferList* pBufferList;
  27124. ma_bool32 isSupported;
  27125. MA_ASSERT(pContext != NULL);
  27126. /* To know whether or not a device is an input device we need ot look at the stream configuration. If it has an output channel it's a playback device. */
  27127. propAddress.mSelector = kAudioDevicePropertyStreamConfiguration;
  27128. propAddress.mScope = scope;
  27129. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27130. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  27131. if (status != noErr) {
  27132. return MA_FALSE;
  27133. }
  27134. pBufferList = (AudioBufferList*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  27135. if (pBufferList == NULL) {
  27136. return MA_FALSE; /* Out of memory. */
  27137. }
  27138. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pBufferList);
  27139. if (status != noErr) {
  27140. ma_free(pBufferList, &pContext->allocationCallbacks);
  27141. return MA_FALSE;
  27142. }
  27143. isSupported = MA_FALSE;
  27144. if (pBufferList->mNumberBuffers > 0) {
  27145. isSupported = MA_TRUE;
  27146. }
  27147. ma_free(pBufferList, &pContext->allocationCallbacks);
  27148. return isSupported;
  27149. }
  27150. static ma_bool32 ma_does_AudioObject_support_playback(ma_context* pContext, AudioObjectID deviceObjectID)
  27151. {
  27152. return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeOutput);
  27153. }
  27154. static ma_bool32 ma_does_AudioObject_support_capture(ma_context* pContext, AudioObjectID deviceObjectID)
  27155. {
  27156. return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeInput);
  27157. }
  27158. static ma_result ma_get_AudioObject_stream_descriptions(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, UInt32* pDescriptionCount, AudioStreamRangedDescription** ppDescriptions) /* NOTE: Free the returned pointer with ma_free(). */
  27159. {
  27160. AudioObjectPropertyAddress propAddress;
  27161. UInt32 dataSize;
  27162. OSStatus status;
  27163. AudioStreamRangedDescription* pDescriptions;
  27164. MA_ASSERT(pContext != NULL);
  27165. MA_ASSERT(pDescriptionCount != NULL);
  27166. MA_ASSERT(ppDescriptions != NULL);
  27167. /*
  27168. TODO: Experiment with kAudioStreamPropertyAvailablePhysicalFormats instead of (or in addition to) kAudioStreamPropertyAvailableVirtualFormats. My
  27169. MacBook Pro uses s24/32 format, however, which miniaudio does not currently support.
  27170. */
  27171. propAddress.mSelector = kAudioStreamPropertyAvailableVirtualFormats; /*kAudioStreamPropertyAvailablePhysicalFormats;*/
  27172. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27173. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27174. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  27175. if (status != noErr) {
  27176. return ma_result_from_OSStatus(status);
  27177. }
  27178. pDescriptions = (AudioStreamRangedDescription*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  27179. if (pDescriptions == NULL) {
  27180. return MA_OUT_OF_MEMORY;
  27181. }
  27182. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pDescriptions);
  27183. if (status != noErr) {
  27184. ma_free(pDescriptions, &pContext->allocationCallbacks);
  27185. return ma_result_from_OSStatus(status);
  27186. }
  27187. *pDescriptionCount = dataSize / sizeof(*pDescriptions);
  27188. *ppDescriptions = pDescriptions;
  27189. return MA_SUCCESS;
  27190. }
  27191. static ma_result ma_get_AudioObject_channel_layout(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, AudioChannelLayout** ppChannelLayout) /* NOTE: Free the returned pointer with ma_free(). */
  27192. {
  27193. AudioObjectPropertyAddress propAddress;
  27194. UInt32 dataSize;
  27195. OSStatus status;
  27196. AudioChannelLayout* pChannelLayout;
  27197. MA_ASSERT(pContext != NULL);
  27198. MA_ASSERT(ppChannelLayout != NULL);
  27199. *ppChannelLayout = NULL; /* Safety. */
  27200. propAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout;
  27201. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27202. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27203. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  27204. if (status != noErr) {
  27205. return ma_result_from_OSStatus(status);
  27206. }
  27207. pChannelLayout = (AudioChannelLayout*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  27208. if (pChannelLayout == NULL) {
  27209. return MA_OUT_OF_MEMORY;
  27210. }
  27211. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pChannelLayout);
  27212. if (status != noErr) {
  27213. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27214. return ma_result_from_OSStatus(status);
  27215. }
  27216. *ppChannelLayout = pChannelLayout;
  27217. return MA_SUCCESS;
  27218. }
  27219. static ma_result ma_get_AudioObject_channel_count(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pChannelCount)
  27220. {
  27221. AudioChannelLayout* pChannelLayout;
  27222. ma_result result;
  27223. MA_ASSERT(pContext != NULL);
  27224. MA_ASSERT(pChannelCount != NULL);
  27225. *pChannelCount = 0; /* Safety. */
  27226. result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout);
  27227. if (result != MA_SUCCESS) {
  27228. return result;
  27229. }
  27230. if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) {
  27231. *pChannelCount = pChannelLayout->mNumberChannelDescriptions;
  27232. } else if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
  27233. *pChannelCount = ma_count_set_bits(pChannelLayout->mChannelBitmap);
  27234. } else {
  27235. *pChannelCount = AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag);
  27236. }
  27237. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27238. return MA_SUCCESS;
  27239. }
  27240. #if 0
  27241. static ma_result ma_get_AudioObject_channel_map(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_channel* pChannelMap, size_t channelMapCap)
  27242. {
  27243. AudioChannelLayout* pChannelLayout;
  27244. ma_result result;
  27245. MA_ASSERT(pContext != NULL);
  27246. result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout);
  27247. if (result != MA_SUCCESS) {
  27248. return result; /* Rather than always failing here, would it be more robust to simply assume a default? */
  27249. }
  27250. result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, pChannelMap, channelMapCap);
  27251. if (result != MA_SUCCESS) {
  27252. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27253. return result;
  27254. }
  27255. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27256. return result;
  27257. }
  27258. #endif
  27259. static ma_result ma_get_AudioObject_sample_rates(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, UInt32* pSampleRateRangesCount, AudioValueRange** ppSampleRateRanges) /* NOTE: Free the returned pointer with ma_free(). */
  27260. {
  27261. AudioObjectPropertyAddress propAddress;
  27262. UInt32 dataSize;
  27263. OSStatus status;
  27264. AudioValueRange* pSampleRateRanges;
  27265. MA_ASSERT(pContext != NULL);
  27266. MA_ASSERT(pSampleRateRangesCount != NULL);
  27267. MA_ASSERT(ppSampleRateRanges != NULL);
  27268. /* Safety. */
  27269. *pSampleRateRangesCount = 0;
  27270. *ppSampleRateRanges = NULL;
  27271. propAddress.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  27272. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27273. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27274. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  27275. if (status != noErr) {
  27276. return ma_result_from_OSStatus(status);
  27277. }
  27278. pSampleRateRanges = (AudioValueRange*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  27279. if (pSampleRateRanges == NULL) {
  27280. return MA_OUT_OF_MEMORY;
  27281. }
  27282. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pSampleRateRanges);
  27283. if (status != noErr) {
  27284. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27285. return ma_result_from_OSStatus(status);
  27286. }
  27287. *pSampleRateRangesCount = dataSize / sizeof(*pSampleRateRanges);
  27288. *ppSampleRateRanges = pSampleRateRanges;
  27289. return MA_SUCCESS;
  27290. }
  27291. #if 0
  27292. static ma_result ma_get_AudioObject_get_closest_sample_rate(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32 sampleRateIn, ma_uint32* pSampleRateOut)
  27293. {
  27294. UInt32 sampleRateRangeCount;
  27295. AudioValueRange* pSampleRateRanges;
  27296. ma_result result;
  27297. MA_ASSERT(pContext != NULL);
  27298. MA_ASSERT(pSampleRateOut != NULL);
  27299. *pSampleRateOut = 0; /* Safety. */
  27300. result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges);
  27301. if (result != MA_SUCCESS) {
  27302. return result;
  27303. }
  27304. if (sampleRateRangeCount == 0) {
  27305. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27306. return MA_ERROR; /* Should never hit this case should we? */
  27307. }
  27308. if (sampleRateIn == 0) {
  27309. /* Search in order of miniaudio's preferred priority. */
  27310. UInt32 iMALSampleRate;
  27311. for (iMALSampleRate = 0; iMALSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iMALSampleRate) {
  27312. ma_uint32 malSampleRate = g_maStandardSampleRatePriorities[iMALSampleRate];
  27313. UInt32 iCASampleRate;
  27314. for (iCASampleRate = 0; iCASampleRate < sampleRateRangeCount; ++iCASampleRate) {
  27315. AudioValueRange caSampleRate = pSampleRateRanges[iCASampleRate];
  27316. if (caSampleRate.mMinimum <= malSampleRate && caSampleRate.mMaximum >= malSampleRate) {
  27317. *pSampleRateOut = malSampleRate;
  27318. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27319. return MA_SUCCESS;
  27320. }
  27321. }
  27322. }
  27323. /*
  27324. If we get here it means none of miniaudio's standard sample rates matched any of the supported sample rates from the device. In this
  27325. case we just fall back to the first one reported by Core Audio.
  27326. */
  27327. MA_ASSERT(sampleRateRangeCount > 0);
  27328. *pSampleRateOut = pSampleRateRanges[0].mMinimum;
  27329. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27330. return MA_SUCCESS;
  27331. } else {
  27332. /* Find the closest match to this sample rate. */
  27333. UInt32 currentAbsoluteDifference = INT32_MAX;
  27334. UInt32 iCurrentClosestRange = (UInt32)-1;
  27335. UInt32 iRange;
  27336. for (iRange = 0; iRange < sampleRateRangeCount; ++iRange) {
  27337. if (pSampleRateRanges[iRange].mMinimum <= sampleRateIn && pSampleRateRanges[iRange].mMaximum >= sampleRateIn) {
  27338. *pSampleRateOut = sampleRateIn;
  27339. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27340. return MA_SUCCESS;
  27341. } else {
  27342. UInt32 absoluteDifference;
  27343. if (pSampleRateRanges[iRange].mMinimum > sampleRateIn) {
  27344. absoluteDifference = pSampleRateRanges[iRange].mMinimum - sampleRateIn;
  27345. } else {
  27346. absoluteDifference = sampleRateIn - pSampleRateRanges[iRange].mMaximum;
  27347. }
  27348. if (currentAbsoluteDifference > absoluteDifference) {
  27349. currentAbsoluteDifference = absoluteDifference;
  27350. iCurrentClosestRange = iRange;
  27351. }
  27352. }
  27353. }
  27354. MA_ASSERT(iCurrentClosestRange != (UInt32)-1);
  27355. *pSampleRateOut = pSampleRateRanges[iCurrentClosestRange].mMinimum;
  27356. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27357. return MA_SUCCESS;
  27358. }
  27359. /* Should never get here, but it would mean we weren't able to find any suitable sample rates. */
  27360. /*ma_free(pSampleRateRanges, &pContext->allocationCallbacks);*/
  27361. /*return MA_ERROR;*/
  27362. }
  27363. #endif
  27364. static ma_result ma_get_AudioObject_closest_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32 bufferSizeInFramesIn, ma_uint32* pBufferSizeInFramesOut)
  27365. {
  27366. AudioObjectPropertyAddress propAddress;
  27367. AudioValueRange bufferSizeRange;
  27368. UInt32 dataSize;
  27369. OSStatus status;
  27370. MA_ASSERT(pContext != NULL);
  27371. MA_ASSERT(pBufferSizeInFramesOut != NULL);
  27372. *pBufferSizeInFramesOut = 0; /* Safety. */
  27373. propAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  27374. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27375. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27376. dataSize = sizeof(bufferSizeRange);
  27377. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &bufferSizeRange);
  27378. if (status != noErr) {
  27379. return ma_result_from_OSStatus(status);
  27380. }
  27381. /* This is just a clamp. */
  27382. if (bufferSizeInFramesIn < bufferSizeRange.mMinimum) {
  27383. *pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMinimum;
  27384. } else if (bufferSizeInFramesIn > bufferSizeRange.mMaximum) {
  27385. *pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMaximum;
  27386. } else {
  27387. *pBufferSizeInFramesOut = bufferSizeInFramesIn;
  27388. }
  27389. return MA_SUCCESS;
  27390. }
  27391. static ma_result ma_set_AudioObject_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pPeriodSizeInOut)
  27392. {
  27393. ma_result result;
  27394. ma_uint32 chosenBufferSizeInFrames;
  27395. AudioObjectPropertyAddress propAddress;
  27396. UInt32 dataSize;
  27397. OSStatus status;
  27398. MA_ASSERT(pContext != NULL);
  27399. result = ma_get_AudioObject_closest_buffer_size_in_frames(pContext, deviceObjectID, deviceType, *pPeriodSizeInOut, &chosenBufferSizeInFrames);
  27400. if (result != MA_SUCCESS) {
  27401. return result;
  27402. }
  27403. /* Try setting the size of the buffer... If this fails we just use whatever is currently set. */
  27404. propAddress.mSelector = kAudioDevicePropertyBufferFrameSize;
  27405. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27406. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27407. ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(chosenBufferSizeInFrames), &chosenBufferSizeInFrames);
  27408. /* Get the actual size of the buffer. */
  27409. dataSize = sizeof(*pPeriodSizeInOut);
  27410. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &chosenBufferSizeInFrames);
  27411. if (status != noErr) {
  27412. return ma_result_from_OSStatus(status);
  27413. }
  27414. *pPeriodSizeInOut = chosenBufferSizeInFrames;
  27415. return MA_SUCCESS;
  27416. }
  27417. static ma_result ma_find_default_AudioObjectID(ma_context* pContext, ma_device_type deviceType, AudioObjectID* pDeviceObjectID)
  27418. {
  27419. AudioObjectPropertyAddress propAddressDefaultDevice;
  27420. UInt32 defaultDeviceObjectIDSize = sizeof(AudioObjectID);
  27421. AudioObjectID defaultDeviceObjectID;
  27422. OSStatus status;
  27423. MA_ASSERT(pContext != NULL);
  27424. MA_ASSERT(pDeviceObjectID != NULL);
  27425. /* Safety. */
  27426. *pDeviceObjectID = 0;
  27427. propAddressDefaultDevice.mScope = kAudioObjectPropertyScopeGlobal;
  27428. propAddressDefaultDevice.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27429. if (deviceType == ma_device_type_playback) {
  27430. propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  27431. } else {
  27432. propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  27433. }
  27434. defaultDeviceObjectIDSize = sizeof(AudioObjectID);
  27435. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDefaultDevice, 0, NULL, &defaultDeviceObjectIDSize, &defaultDeviceObjectID);
  27436. if (status == noErr) {
  27437. *pDeviceObjectID = defaultDeviceObjectID;
  27438. return MA_SUCCESS;
  27439. }
  27440. /* If we get here it means we couldn't find the device. */
  27441. return MA_NO_DEVICE;
  27442. }
  27443. static ma_result ma_find_AudioObjectID(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, AudioObjectID* pDeviceObjectID)
  27444. {
  27445. MA_ASSERT(pContext != NULL);
  27446. MA_ASSERT(pDeviceObjectID != NULL);
  27447. /* Safety. */
  27448. *pDeviceObjectID = 0;
  27449. if (pDeviceID == NULL) {
  27450. /* Default device. */
  27451. return ma_find_default_AudioObjectID(pContext, deviceType, pDeviceObjectID);
  27452. } else {
  27453. /* Explicit device. */
  27454. UInt32 deviceCount;
  27455. AudioObjectID* pDeviceObjectIDs;
  27456. ma_result result;
  27457. UInt32 iDevice;
  27458. result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs);
  27459. if (result != MA_SUCCESS) {
  27460. return result;
  27461. }
  27462. for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
  27463. AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice];
  27464. char uid[256];
  27465. if (ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(uid), uid) != MA_SUCCESS) {
  27466. continue;
  27467. }
  27468. if (deviceType == ma_device_type_playback) {
  27469. if (ma_does_AudioObject_support_playback(pContext, deviceObjectID)) {
  27470. if (strcmp(uid, pDeviceID->coreaudio) == 0) {
  27471. *pDeviceObjectID = deviceObjectID;
  27472. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27473. return MA_SUCCESS;
  27474. }
  27475. }
  27476. } else {
  27477. if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) {
  27478. if (strcmp(uid, pDeviceID->coreaudio) == 0) {
  27479. *pDeviceObjectID = deviceObjectID;
  27480. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27481. return MA_SUCCESS;
  27482. }
  27483. }
  27484. }
  27485. }
  27486. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27487. }
  27488. /* If we get here it means we couldn't find the device. */
  27489. return MA_NO_DEVICE;
  27490. }
  27491. static ma_result ma_find_best_format__coreaudio(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const AudioStreamBasicDescription* pOrigFormat, AudioStreamBasicDescription* pFormat)
  27492. {
  27493. UInt32 deviceFormatDescriptionCount;
  27494. AudioStreamRangedDescription* pDeviceFormatDescriptions;
  27495. ma_result result;
  27496. ma_uint32 desiredSampleRate;
  27497. ma_uint32 desiredChannelCount;
  27498. ma_format desiredFormat;
  27499. AudioStreamBasicDescription bestDeviceFormatSoFar;
  27500. ma_bool32 hasSupportedFormat;
  27501. UInt32 iFormat;
  27502. result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &deviceFormatDescriptionCount, &pDeviceFormatDescriptions);
  27503. if (result != MA_SUCCESS) {
  27504. return result;
  27505. }
  27506. desiredSampleRate = sampleRate;
  27507. if (desiredSampleRate == 0) {
  27508. desiredSampleRate = pOrigFormat->mSampleRate;
  27509. }
  27510. desiredChannelCount = channels;
  27511. if (desiredChannelCount == 0) {
  27512. desiredChannelCount = pOrigFormat->mChannelsPerFrame;
  27513. }
  27514. desiredFormat = format;
  27515. if (desiredFormat == ma_format_unknown) {
  27516. result = ma_format_from_AudioStreamBasicDescription(pOrigFormat, &desiredFormat);
  27517. if (result != MA_SUCCESS || desiredFormat == ma_format_unknown) {
  27518. desiredFormat = g_maFormatPriorities[0];
  27519. }
  27520. }
  27521. /*
  27522. If we get here it means we don't have an exact match to what the client is asking for. We'll need to find the closest one. The next
  27523. loop will check for formats that have the same sample rate to what we're asking for. If there is, we prefer that one in all cases.
  27524. */
  27525. MA_ZERO_OBJECT(&bestDeviceFormatSoFar);
  27526. hasSupportedFormat = MA_FALSE;
  27527. for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) {
  27528. ma_format format;
  27529. ma_result formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &format);
  27530. if (formatResult == MA_SUCCESS && format != ma_format_unknown) {
  27531. hasSupportedFormat = MA_TRUE;
  27532. bestDeviceFormatSoFar = pDeviceFormatDescriptions[iFormat].mFormat;
  27533. break;
  27534. }
  27535. }
  27536. if (!hasSupportedFormat) {
  27537. ma_free(pDeviceFormatDescriptions, &pContext->allocationCallbacks);
  27538. return MA_FORMAT_NOT_SUPPORTED;
  27539. }
  27540. for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) {
  27541. AudioStreamBasicDescription thisDeviceFormat = pDeviceFormatDescriptions[iFormat].mFormat;
  27542. ma_format thisSampleFormat;
  27543. ma_result formatResult;
  27544. ma_format bestSampleFormatSoFar;
  27545. /* If the format is not supported by miniaudio we need to skip this one entirely. */
  27546. formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &thisSampleFormat);
  27547. if (formatResult != MA_SUCCESS || thisSampleFormat == ma_format_unknown) {
  27548. continue; /* The format is not supported by miniaudio. Skip. */
  27549. }
  27550. ma_format_from_AudioStreamBasicDescription(&bestDeviceFormatSoFar, &bestSampleFormatSoFar);
  27551. /* Getting here means the format is supported by miniaudio which makes this format a candidate. */
  27552. if (thisDeviceFormat.mSampleRate != desiredSampleRate) {
  27553. /*
  27554. The sample rate does not match, but this format could still be usable, although it's a very low priority. If the best format
  27555. so far has an equal sample rate we can just ignore this one.
  27556. */
  27557. if (bestDeviceFormatSoFar.mSampleRate == desiredSampleRate) {
  27558. continue; /* The best sample rate so far has the same sample rate as what we requested which means it's still the best so far. Skip this format. */
  27559. } else {
  27560. /* In this case, neither the best format so far nor this one have the same sample rate. Check the channel count next. */
  27561. if (thisDeviceFormat.mChannelsPerFrame != desiredChannelCount) {
  27562. /* This format has a different sample rate _and_ a different channel count. */
  27563. if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) {
  27564. continue; /* No change to the best format. */
  27565. } else {
  27566. /*
  27567. Both this format and the best so far have different sample rates and different channel counts. Whichever has the
  27568. best format is the new best.
  27569. */
  27570. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  27571. bestDeviceFormatSoFar = thisDeviceFormat;
  27572. continue;
  27573. } else {
  27574. continue; /* No change to the best format. */
  27575. }
  27576. }
  27577. } else {
  27578. /* This format has a different sample rate but the desired channel count. */
  27579. if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) {
  27580. /* Both this format and the best so far have the desired channel count. Whichever has the best format is the new best. */
  27581. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  27582. bestDeviceFormatSoFar = thisDeviceFormat;
  27583. continue;
  27584. } else {
  27585. continue; /* No change to the best format for now. */
  27586. }
  27587. } else {
  27588. /* This format has the desired channel count, but the best so far does not. We have a new best. */
  27589. bestDeviceFormatSoFar = thisDeviceFormat;
  27590. continue;
  27591. }
  27592. }
  27593. }
  27594. } else {
  27595. /*
  27596. The sample rates match which makes this format a very high priority contender. If the best format so far has a different
  27597. sample rate it needs to be replaced with this one.
  27598. */
  27599. if (bestDeviceFormatSoFar.mSampleRate != desiredSampleRate) {
  27600. bestDeviceFormatSoFar = thisDeviceFormat;
  27601. continue;
  27602. } else {
  27603. /* In this case both this format and the best format so far have the same sample rate. Check the channel count next. */
  27604. if (thisDeviceFormat.mChannelsPerFrame == desiredChannelCount) {
  27605. /*
  27606. In this case this format has the same channel count as what the client is requesting. If the best format so far has
  27607. a different count, this one becomes the new best.
  27608. */
  27609. if (bestDeviceFormatSoFar.mChannelsPerFrame != desiredChannelCount) {
  27610. bestDeviceFormatSoFar = thisDeviceFormat;
  27611. continue;
  27612. } else {
  27613. /* In this case both this format and the best so far have the ideal sample rate and channel count. Check the format. */
  27614. if (thisSampleFormat == desiredFormat) {
  27615. bestDeviceFormatSoFar = thisDeviceFormat;
  27616. break; /* Found the exact match. */
  27617. } else {
  27618. /* The formats are different. The new best format is the one with the highest priority format according to miniaudio. */
  27619. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  27620. bestDeviceFormatSoFar = thisDeviceFormat;
  27621. continue;
  27622. } else {
  27623. continue; /* No change to the best format for now. */
  27624. }
  27625. }
  27626. }
  27627. } else {
  27628. /*
  27629. In this case the channel count is different to what the client has requested. If the best so far has the same channel
  27630. count as the requested count then it remains the best.
  27631. */
  27632. if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) {
  27633. continue;
  27634. } else {
  27635. /*
  27636. This is the case where both have the same sample rate (good) but different channel counts. Right now both have about
  27637. the same priority, but we need to compare the format now.
  27638. */
  27639. if (thisSampleFormat == bestSampleFormatSoFar) {
  27640. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  27641. bestDeviceFormatSoFar = thisDeviceFormat;
  27642. continue;
  27643. } else {
  27644. continue; /* No change to the best format for now. */
  27645. }
  27646. }
  27647. }
  27648. }
  27649. }
  27650. }
  27651. }
  27652. *pFormat = bestDeviceFormatSoFar;
  27653. ma_free(pDeviceFormatDescriptions, &pContext->allocationCallbacks);
  27654. return MA_SUCCESS;
  27655. }
  27656. static ma_result ma_get_AudioUnit_channel_map(ma_context* pContext, AudioUnit audioUnit, ma_device_type deviceType, ma_channel* pChannelMap, size_t channelMapCap)
  27657. {
  27658. AudioUnitScope deviceScope;
  27659. AudioUnitElement deviceBus;
  27660. UInt32 channelLayoutSize;
  27661. OSStatus status;
  27662. AudioChannelLayout* pChannelLayout;
  27663. ma_result result;
  27664. MA_ASSERT(pContext != NULL);
  27665. if (deviceType == ma_device_type_playback) {
  27666. deviceScope = kAudioUnitScope_Input;
  27667. deviceBus = MA_COREAUDIO_OUTPUT_BUS;
  27668. } else {
  27669. deviceScope = kAudioUnitScope_Output;
  27670. deviceBus = MA_COREAUDIO_INPUT_BUS;
  27671. }
  27672. status = ((ma_AudioUnitGetPropertyInfo_proc)pContext->coreaudio.AudioUnitGetPropertyInfo)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, &channelLayoutSize, NULL);
  27673. if (status != noErr) {
  27674. return ma_result_from_OSStatus(status);
  27675. }
  27676. pChannelLayout = (AudioChannelLayout*)ma_malloc(channelLayoutSize, &pContext->allocationCallbacks);
  27677. if (pChannelLayout == NULL) {
  27678. return MA_OUT_OF_MEMORY;
  27679. }
  27680. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, pChannelLayout, &channelLayoutSize);
  27681. if (status != noErr) {
  27682. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27683. return ma_result_from_OSStatus(status);
  27684. }
  27685. result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, pChannelMap, channelMapCap);
  27686. if (result != MA_SUCCESS) {
  27687. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27688. return result;
  27689. }
  27690. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27691. return MA_SUCCESS;
  27692. }
  27693. #endif /* MA_APPLE_DESKTOP */
  27694. #if !defined(MA_APPLE_DESKTOP)
  27695. static void ma_AVAudioSessionPortDescription_to_device_info(AVAudioSessionPortDescription* pPortDesc, ma_device_info* pInfo)
  27696. {
  27697. MA_ZERO_OBJECT(pInfo);
  27698. ma_strncpy_s(pInfo->name, sizeof(pInfo->name), [pPortDesc.portName UTF8String], (size_t)-1);
  27699. ma_strncpy_s(pInfo->id.coreaudio, sizeof(pInfo->id.coreaudio), [pPortDesc.UID UTF8String], (size_t)-1);
  27700. }
  27701. #endif
  27702. static ma_result ma_context_enumerate_devices__coreaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  27703. {
  27704. #if defined(MA_APPLE_DESKTOP)
  27705. UInt32 deviceCount;
  27706. AudioObjectID* pDeviceObjectIDs;
  27707. AudioObjectID defaultDeviceObjectIDPlayback;
  27708. AudioObjectID defaultDeviceObjectIDCapture;
  27709. ma_result result;
  27710. UInt32 iDevice;
  27711. ma_find_default_AudioObjectID(pContext, ma_device_type_playback, &defaultDeviceObjectIDPlayback); /* OK if this fails. */
  27712. ma_find_default_AudioObjectID(pContext, ma_device_type_capture, &defaultDeviceObjectIDCapture); /* OK if this fails. */
  27713. result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs);
  27714. if (result != MA_SUCCESS) {
  27715. return result;
  27716. }
  27717. for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
  27718. AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice];
  27719. ma_device_info info;
  27720. MA_ZERO_OBJECT(&info);
  27721. if (ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(info.id.coreaudio), info.id.coreaudio) != MA_SUCCESS) {
  27722. continue;
  27723. }
  27724. if (ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(info.name), info.name) != MA_SUCCESS) {
  27725. continue;
  27726. }
  27727. if (ma_does_AudioObject_support_playback(pContext, deviceObjectID)) {
  27728. if (deviceObjectID == defaultDeviceObjectIDPlayback) {
  27729. info.isDefault = MA_TRUE;
  27730. }
  27731. if (!callback(pContext, ma_device_type_playback, &info, pUserData)) {
  27732. break;
  27733. }
  27734. }
  27735. if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) {
  27736. if (deviceObjectID == defaultDeviceObjectIDCapture) {
  27737. info.isDefault = MA_TRUE;
  27738. }
  27739. if (!callback(pContext, ma_device_type_capture, &info, pUserData)) {
  27740. break;
  27741. }
  27742. }
  27743. }
  27744. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27745. #else
  27746. ma_device_info info;
  27747. NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs];
  27748. NSArray *pOutputs = [[[AVAudioSession sharedInstance] currentRoute] outputs];
  27749. for (AVAudioSessionPortDescription* pPortDesc in pOutputs) {
  27750. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, &info);
  27751. if (!callback(pContext, ma_device_type_playback, &info, pUserData)) {
  27752. return MA_SUCCESS;
  27753. }
  27754. }
  27755. for (AVAudioSessionPortDescription* pPortDesc in pInputs) {
  27756. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, &info);
  27757. if (!callback(pContext, ma_device_type_capture, &info, pUserData)) {
  27758. return MA_SUCCESS;
  27759. }
  27760. }
  27761. #endif
  27762. return MA_SUCCESS;
  27763. }
  27764. static ma_result ma_context_get_device_info__coreaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  27765. {
  27766. ma_result result;
  27767. MA_ASSERT(pContext != NULL);
  27768. #if defined(MA_APPLE_DESKTOP)
  27769. /* Desktop */
  27770. {
  27771. AudioObjectID deviceObjectID;
  27772. AudioObjectID defaultDeviceObjectID;
  27773. UInt32 streamDescriptionCount;
  27774. AudioStreamRangedDescription* pStreamDescriptions;
  27775. UInt32 iStreamDescription;
  27776. UInt32 sampleRateRangeCount;
  27777. AudioValueRange* pSampleRateRanges;
  27778. ma_find_default_AudioObjectID(pContext, deviceType, &defaultDeviceObjectID); /* OK if this fails. */
  27779. result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID);
  27780. if (result != MA_SUCCESS) {
  27781. return result;
  27782. }
  27783. result = ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(pDeviceInfo->id.coreaudio), pDeviceInfo->id.coreaudio);
  27784. if (result != MA_SUCCESS) {
  27785. return result;
  27786. }
  27787. result = ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pDeviceInfo->name), pDeviceInfo->name);
  27788. if (result != MA_SUCCESS) {
  27789. return result;
  27790. }
  27791. if (deviceObjectID == defaultDeviceObjectID) {
  27792. pDeviceInfo->isDefault = MA_TRUE;
  27793. }
  27794. /*
  27795. There could be a large number of permutations here. Fortunately there is only a single channel count
  27796. being reported which reduces this quite a bit. For sample rates we're only reporting those that are
  27797. one of miniaudio's recognized "standard" rates. If there are still more formats than can fit into
  27798. our fixed sized array we'll just need to truncate them. This is unlikely and will probably only happen
  27799. if some driver performs software data conversion and therefore reports every possible format and
  27800. sample rate.
  27801. */
  27802. pDeviceInfo->nativeDataFormatCount = 0;
  27803. /* Formats. */
  27804. {
  27805. ma_format uniqueFormats[ma_format_count];
  27806. ma_uint32 uniqueFormatCount = 0;
  27807. ma_uint32 channels;
  27808. /* Channels. */
  27809. result = ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &channels);
  27810. if (result != MA_SUCCESS) {
  27811. return result;
  27812. }
  27813. /* Formats. */
  27814. result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &streamDescriptionCount, &pStreamDescriptions);
  27815. if (result != MA_SUCCESS) {
  27816. return result;
  27817. }
  27818. for (iStreamDescription = 0; iStreamDescription < streamDescriptionCount; ++iStreamDescription) {
  27819. ma_format format;
  27820. ma_bool32 hasFormatBeenHandled = MA_FALSE;
  27821. ma_uint32 iOutputFormat;
  27822. ma_uint32 iSampleRate;
  27823. result = ma_format_from_AudioStreamBasicDescription(&pStreamDescriptions[iStreamDescription].mFormat, &format);
  27824. if (result != MA_SUCCESS) {
  27825. continue;
  27826. }
  27827. MA_ASSERT(format != ma_format_unknown);
  27828. /* Make sure the format isn't already in the output list. */
  27829. for (iOutputFormat = 0; iOutputFormat < uniqueFormatCount; ++iOutputFormat) {
  27830. if (uniqueFormats[iOutputFormat] == format) {
  27831. hasFormatBeenHandled = MA_TRUE;
  27832. break;
  27833. }
  27834. }
  27835. /* If we've already handled this format just skip it. */
  27836. if (hasFormatBeenHandled) {
  27837. continue;
  27838. }
  27839. uniqueFormats[uniqueFormatCount] = format;
  27840. uniqueFormatCount += 1;
  27841. /* Sample Rates */
  27842. result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges);
  27843. if (result != MA_SUCCESS) {
  27844. return result;
  27845. }
  27846. /*
  27847. Annoyingly Core Audio reports a sample rate range. We just get all the standard rates that are
  27848. between this range.
  27849. */
  27850. for (iSampleRate = 0; iSampleRate < sampleRateRangeCount; ++iSampleRate) {
  27851. ma_uint32 iStandardSampleRate;
  27852. for (iStandardSampleRate = 0; iStandardSampleRate < ma_countof(g_maStandardSampleRatePriorities); iStandardSampleRate += 1) {
  27853. ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iStandardSampleRate];
  27854. if (standardSampleRate >= pSampleRateRanges[iSampleRate].mMinimum && standardSampleRate <= pSampleRateRanges[iSampleRate].mMaximum) {
  27855. /* We have a new data format. Add it to the list. */
  27856. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  27857. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  27858. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = standardSampleRate;
  27859. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  27860. pDeviceInfo->nativeDataFormatCount += 1;
  27861. if (pDeviceInfo->nativeDataFormatCount >= ma_countof(pDeviceInfo->nativeDataFormats)) {
  27862. break; /* No more room for any more formats. */
  27863. }
  27864. }
  27865. }
  27866. }
  27867. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27868. if (pDeviceInfo->nativeDataFormatCount >= ma_countof(pDeviceInfo->nativeDataFormats)) {
  27869. break; /* No more room for any more formats. */
  27870. }
  27871. }
  27872. ma_free(pStreamDescriptions, &pContext->allocationCallbacks);
  27873. }
  27874. }
  27875. #else
  27876. /* Mobile */
  27877. {
  27878. AudioComponentDescription desc;
  27879. AudioComponent component;
  27880. AudioUnit audioUnit;
  27881. OSStatus status;
  27882. AudioUnitScope formatScope;
  27883. AudioUnitElement formatElement;
  27884. AudioStreamBasicDescription bestFormat;
  27885. UInt32 propSize;
  27886. /* We want to ensure we use a consistent device name to device enumeration. */
  27887. if (pDeviceID != NULL && pDeviceID->coreaudio[0] != '\0') {
  27888. ma_bool32 found = MA_FALSE;
  27889. if (deviceType == ma_device_type_playback) {
  27890. NSArray *pOutputs = [[[AVAudioSession sharedInstance] currentRoute] outputs];
  27891. for (AVAudioSessionPortDescription* pPortDesc in pOutputs) {
  27892. if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) {
  27893. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, pDeviceInfo);
  27894. found = MA_TRUE;
  27895. break;
  27896. }
  27897. }
  27898. } else {
  27899. NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs];
  27900. for (AVAudioSessionPortDescription* pPortDesc in pInputs) {
  27901. if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) {
  27902. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, pDeviceInfo);
  27903. found = MA_TRUE;
  27904. break;
  27905. }
  27906. }
  27907. }
  27908. if (!found) {
  27909. return MA_DOES_NOT_EXIST;
  27910. }
  27911. } else {
  27912. if (deviceType == ma_device_type_playback) {
  27913. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  27914. } else {
  27915. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  27916. }
  27917. }
  27918. /*
  27919. Retrieving device information is more annoying on mobile than desktop. For simplicity I'm locking this down to whatever format is
  27920. reported on a temporary I/O unit. The problem, however, is that this doesn't return a value for the sample rate which we need to
  27921. retrieve from the AVAudioSession shared instance.
  27922. */
  27923. desc.componentType = kAudioUnitType_Output;
  27924. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  27925. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  27926. desc.componentFlags = 0;
  27927. desc.componentFlagsMask = 0;
  27928. component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc);
  27929. if (component == NULL) {
  27930. return MA_FAILED_TO_INIT_BACKEND;
  27931. }
  27932. status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(component, &audioUnit);
  27933. if (status != noErr) {
  27934. return ma_result_from_OSStatus(status);
  27935. }
  27936. formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output;
  27937. formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS;
  27938. propSize = sizeof(bestFormat);
  27939. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize);
  27940. if (status != noErr) {
  27941. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit);
  27942. return ma_result_from_OSStatus(status);
  27943. }
  27944. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit);
  27945. audioUnit = NULL;
  27946. /* Only a single format is being reported for iOS. */
  27947. pDeviceInfo->nativeDataFormatCount = 1;
  27948. result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pDeviceInfo->nativeDataFormats[0].format);
  27949. if (result != MA_SUCCESS) {
  27950. return result;
  27951. }
  27952. pDeviceInfo->nativeDataFormats[0].channels = bestFormat.mChannelsPerFrame;
  27953. /*
  27954. It looks like Apple are wanting to push the whole AVAudioSession thing. Thus, we need to use that to determine device settings. To do
  27955. this we just get the shared instance and inspect.
  27956. */
  27957. @autoreleasepool {
  27958. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  27959. MA_ASSERT(pAudioSession != NULL);
  27960. pDeviceInfo->nativeDataFormats[0].sampleRate = (ma_uint32)pAudioSession.sampleRate;
  27961. }
  27962. }
  27963. #endif
  27964. (void)pDeviceInfo; /* Unused. */
  27965. return MA_SUCCESS;
  27966. }
  27967. static AudioBufferList* ma_allocate_AudioBufferList__coreaudio(ma_uint32 sizeInFrames, ma_format format, ma_uint32 channels, ma_stream_layout layout, const ma_allocation_callbacks* pAllocationCallbacks)
  27968. {
  27969. AudioBufferList* pBufferList;
  27970. UInt32 audioBufferSizeInBytes;
  27971. size_t allocationSize;
  27972. MA_ASSERT(sizeInFrames > 0);
  27973. MA_ASSERT(format != ma_format_unknown);
  27974. MA_ASSERT(channels > 0);
  27975. allocationSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); /* Subtract sizeof(AudioBuffer) because that part is dynamically sized. */
  27976. if (layout == ma_stream_layout_interleaved) {
  27977. /* Interleaved case. This is the simple case because we just have one buffer. */
  27978. allocationSize += sizeof(AudioBuffer) * 1;
  27979. } else {
  27980. /* Non-interleaved case. This is the more complex case because there's more than one buffer. */
  27981. allocationSize += sizeof(AudioBuffer) * channels;
  27982. }
  27983. allocationSize += sizeInFrames * ma_get_bytes_per_frame(format, channels);
  27984. pBufferList = (AudioBufferList*)ma_malloc(allocationSize, pAllocationCallbacks);
  27985. if (pBufferList == NULL) {
  27986. return NULL;
  27987. }
  27988. audioBufferSizeInBytes = (UInt32)(sizeInFrames * ma_get_bytes_per_sample(format));
  27989. if (layout == ma_stream_layout_interleaved) {
  27990. pBufferList->mNumberBuffers = 1;
  27991. pBufferList->mBuffers[0].mNumberChannels = channels;
  27992. pBufferList->mBuffers[0].mDataByteSize = audioBufferSizeInBytes * channels;
  27993. pBufferList->mBuffers[0].mData = (ma_uint8*)pBufferList + sizeof(AudioBufferList);
  27994. } else {
  27995. ma_uint32 iBuffer;
  27996. pBufferList->mNumberBuffers = channels;
  27997. for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) {
  27998. pBufferList->mBuffers[iBuffer].mNumberChannels = 1;
  27999. pBufferList->mBuffers[iBuffer].mDataByteSize = audioBufferSizeInBytes;
  28000. pBufferList->mBuffers[iBuffer].mData = (ma_uint8*)pBufferList + ((sizeof(AudioBufferList) - sizeof(AudioBuffer)) + (sizeof(AudioBuffer) * channels)) + (audioBufferSizeInBytes * iBuffer);
  28001. }
  28002. }
  28003. return pBufferList;
  28004. }
  28005. static ma_result ma_device_realloc_AudioBufferList__coreaudio(ma_device* pDevice, ma_uint32 sizeInFrames, ma_format format, ma_uint32 channels, ma_stream_layout layout)
  28006. {
  28007. MA_ASSERT(pDevice != NULL);
  28008. MA_ASSERT(format != ma_format_unknown);
  28009. MA_ASSERT(channels > 0);
  28010. /* Only resize the buffer if necessary. */
  28011. if (pDevice->coreaudio.audioBufferCapInFrames < sizeInFrames) {
  28012. AudioBufferList* pNewAudioBufferList;
  28013. pNewAudioBufferList = ma_allocate_AudioBufferList__coreaudio(sizeInFrames, format, channels, layout, &pDevice->pContext->allocationCallbacks);
  28014. if (pNewAudioBufferList == NULL) {
  28015. return MA_OUT_OF_MEMORY;
  28016. }
  28017. /* At this point we'll have a new AudioBufferList and we can free the old one. */
  28018. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  28019. pDevice->coreaudio.pAudioBufferList = pNewAudioBufferList;
  28020. pDevice->coreaudio.audioBufferCapInFrames = sizeInFrames;
  28021. }
  28022. /* Getting here means the capacity of the audio is fine. */
  28023. return MA_SUCCESS;
  28024. }
  28025. static OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pBufferList)
  28026. {
  28027. ma_device* pDevice = (ma_device*)pUserData;
  28028. ma_stream_layout layout;
  28029. MA_ASSERT(pDevice != NULL);
  28030. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "INFO: Output Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", (int)busNumber, (int)frameCount, (int)pBufferList->mNumberBuffers);*/
  28031. /* We need to check whether or not we are outputting interleaved or non-interleaved samples. The way we do this is slightly different for each type. */
  28032. layout = ma_stream_layout_interleaved;
  28033. if (pBufferList->mBuffers[0].mNumberChannels != pDevice->playback.internalChannels) {
  28034. layout = ma_stream_layout_deinterleaved;
  28035. }
  28036. if (layout == ma_stream_layout_interleaved) {
  28037. /* For now we can assume everything is interleaved. */
  28038. UInt32 iBuffer;
  28039. for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) {
  28040. if (pBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->playback.internalChannels) {
  28041. ma_uint32 frameCountForThisBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  28042. if (frameCountForThisBuffer > 0) {
  28043. ma_device_handle_backend_data_callback(pDevice, pBufferList->mBuffers[iBuffer].mData, NULL, frameCountForThisBuffer);
  28044. }
  28045. /*a_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", (int)frameCount, (int)pBufferList->mBuffers[iBuffer].mNumberChannels, (int)pBufferList->mBuffers[iBuffer].mDataByteSize);*/
  28046. } else {
  28047. /*
  28048. This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's
  28049. not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. We just
  28050. output silence here.
  28051. */
  28052. MA_ZERO_MEMORY(pBufferList->mBuffers[iBuffer].mData, pBufferList->mBuffers[iBuffer].mDataByteSize);
  28053. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", (int)frameCount, (int)pBufferList->mBuffers[iBuffer].mNumberChannels, (int)pBufferList->mBuffers[iBuffer].mDataByteSize);*/
  28054. }
  28055. }
  28056. } else {
  28057. /* This is the deinterleaved case. We need to update each buffer in groups of internalChannels. This assumes each buffer is the same size. */
  28058. MA_ASSERT(pDevice->playback.internalChannels <= MA_MAX_CHANNELS); /* This should heve been validated at initialization time. */
  28059. /*
  28060. For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something
  28061. very strange has happened and we're not going to support it.
  28062. */
  28063. if ((pBufferList->mNumberBuffers % pDevice->playback.internalChannels) == 0) {
  28064. ma_uint8 tempBuffer[4096];
  28065. UInt32 iBuffer;
  28066. for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; iBuffer += pDevice->playback.internalChannels) {
  28067. ma_uint32 frameCountPerBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_sample(pDevice->playback.internalFormat);
  28068. ma_uint32 framesRemaining = frameCountPerBuffer;
  28069. while (framesRemaining > 0) {
  28070. void* ppDeinterleavedBuffers[MA_MAX_CHANNELS];
  28071. ma_uint32 iChannel;
  28072. ma_uint32 framesToRead = sizeof(tempBuffer) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  28073. if (framesToRead > framesRemaining) {
  28074. framesToRead = framesRemaining;
  28075. }
  28076. ma_device_handle_backend_data_callback(pDevice, tempBuffer, NULL, framesToRead);
  28077. for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) {
  28078. ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pBufferList->mBuffers[iBuffer+iChannel].mData, (frameCountPerBuffer - framesRemaining) * ma_get_bytes_per_sample(pDevice->playback.internalFormat));
  28079. }
  28080. ma_deinterleave_pcm_frames(pDevice->playback.internalFormat, pDevice->playback.internalChannels, framesToRead, tempBuffer, ppDeinterleavedBuffers);
  28081. framesRemaining -= framesToRead;
  28082. }
  28083. }
  28084. }
  28085. }
  28086. (void)pActionFlags;
  28087. (void)pTimeStamp;
  28088. (void)busNumber;
  28089. (void)frameCount;
  28090. return noErr;
  28091. }
  28092. static OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pUnusedBufferList)
  28093. {
  28094. ma_device* pDevice = (ma_device*)pUserData;
  28095. AudioBufferList* pRenderedBufferList;
  28096. ma_result result;
  28097. ma_stream_layout layout;
  28098. ma_uint32 iBuffer;
  28099. OSStatus status;
  28100. MA_ASSERT(pDevice != NULL);
  28101. pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList;
  28102. MA_ASSERT(pRenderedBufferList);
  28103. /* We need to check whether or not we are outputting interleaved or non-interleaved samples. The way we do this is slightly different for each type. */
  28104. layout = ma_stream_layout_interleaved;
  28105. if (pRenderedBufferList->mBuffers[0].mNumberChannels != pDevice->capture.internalChannels) {
  28106. layout = ma_stream_layout_deinterleaved;
  28107. }
  28108. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "INFO: Input Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", (int)busNumber, (int)frameCount, (int)pRenderedBufferList->mNumberBuffers);*/
  28109. /*
  28110. There has been a situation reported where frame count passed into this function is greater than the capacity of
  28111. our capture buffer. There doesn't seem to be a reliable way to determine what the maximum frame count will be,
  28112. so we need to instead resort to dynamically reallocating our buffer to ensure it's large enough to capture the
  28113. number of frames requested by this callback.
  28114. */
  28115. result = ma_device_realloc_AudioBufferList__coreaudio(pDevice, frameCount, pDevice->capture.internalFormat, pDevice->capture.internalChannels, layout);
  28116. if (result != MA_SUCCESS) {
  28117. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "Failed to allocate AudioBufferList for capture.\n");
  28118. return noErr;
  28119. }
  28120. pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList;
  28121. MA_ASSERT(pRenderedBufferList);
  28122. /*
  28123. When you call AudioUnitRender(), Core Audio tries to be helpful by setting the mDataByteSize to the number of bytes
  28124. that were actually rendered. The problem with this is that the next call can fail with -50 due to the size no longer
  28125. being set to the capacity of the buffer, but instead the size in bytes of the previous render. This will cause a
  28126. problem when a future call to this callback specifies a larger number of frames.
  28127. To work around this we need to explicitly set the size of each buffer to their respective size in bytes.
  28128. */
  28129. for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) {
  28130. pRenderedBufferList->mBuffers[iBuffer].mDataByteSize = pDevice->coreaudio.audioBufferCapInFrames * ma_get_bytes_per_sample(pDevice->capture.internalFormat) * pRenderedBufferList->mBuffers[iBuffer].mNumberChannels;
  28131. }
  28132. status = ((ma_AudioUnitRender_proc)pDevice->pContext->coreaudio.AudioUnitRender)((AudioUnit)pDevice->coreaudio.audioUnitCapture, pActionFlags, pTimeStamp, busNumber, frameCount, pRenderedBufferList);
  28133. if (status != noErr) {
  28134. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " ERROR: AudioUnitRender() failed with %d.\n", (int)status);
  28135. return status;
  28136. }
  28137. if (layout == ma_stream_layout_interleaved) {
  28138. for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) {
  28139. if (pRenderedBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->capture.internalChannels) {
  28140. ma_device_handle_backend_data_callback(pDevice, NULL, pRenderedBufferList->mBuffers[iBuffer].mData, frameCount);
  28141. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " mDataByteSize=%d.\n", (int)pRenderedBufferList->mBuffers[iBuffer].mDataByteSize);*/
  28142. } else {
  28143. /*
  28144. This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's
  28145. not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams.
  28146. */
  28147. ma_uint8 silentBuffer[4096];
  28148. ma_uint32 framesRemaining;
  28149. MA_ZERO_MEMORY(silentBuffer, sizeof(silentBuffer));
  28150. framesRemaining = frameCount;
  28151. while (framesRemaining > 0) {
  28152. ma_uint32 framesToSend = sizeof(silentBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  28153. if (framesToSend > framesRemaining) {
  28154. framesToSend = framesRemaining;
  28155. }
  28156. ma_device_handle_backend_data_callback(pDevice, NULL, silentBuffer, framesToSend);
  28157. framesRemaining -= framesToSend;
  28158. }
  28159. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", (int)frameCount, (int)pRenderedBufferList->mBuffers[iBuffer].mNumberChannels, (int)pRenderedBufferList->mBuffers[iBuffer].mDataByteSize);*/
  28160. }
  28161. }
  28162. } else {
  28163. /* This is the deinterleaved case. We need to interleave the audio data before sending it to the client. This assumes each buffer is the same size. */
  28164. MA_ASSERT(pDevice->capture.internalChannels <= MA_MAX_CHANNELS); /* This should have been validated at initialization time. */
  28165. /*
  28166. For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something
  28167. very strange has happened and we're not going to support it.
  28168. */
  28169. if ((pRenderedBufferList->mNumberBuffers % pDevice->capture.internalChannels) == 0) {
  28170. ma_uint8 tempBuffer[4096];
  28171. for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; iBuffer += pDevice->capture.internalChannels) {
  28172. ma_uint32 framesRemaining = frameCount;
  28173. while (framesRemaining > 0) {
  28174. void* ppDeinterleavedBuffers[MA_MAX_CHANNELS];
  28175. ma_uint32 iChannel;
  28176. ma_uint32 framesToSend = sizeof(tempBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  28177. if (framesToSend > framesRemaining) {
  28178. framesToSend = framesRemaining;
  28179. }
  28180. for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
  28181. ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pRenderedBufferList->mBuffers[iBuffer+iChannel].mData, (frameCount - framesRemaining) * ma_get_bytes_per_sample(pDevice->capture.internalFormat));
  28182. }
  28183. ma_interleave_pcm_frames(pDevice->capture.internalFormat, pDevice->capture.internalChannels, framesToSend, (const void**)ppDeinterleavedBuffers, tempBuffer);
  28184. ma_device_handle_backend_data_callback(pDevice, NULL, tempBuffer, framesToSend);
  28185. framesRemaining -= framesToSend;
  28186. }
  28187. }
  28188. }
  28189. }
  28190. (void)pActionFlags;
  28191. (void)pTimeStamp;
  28192. (void)busNumber;
  28193. (void)frameCount;
  28194. (void)pUnusedBufferList;
  28195. return noErr;
  28196. }
  28197. static void on_start_stop__coreaudio(void* pUserData, AudioUnit audioUnit, AudioUnitPropertyID propertyID, AudioUnitScope scope, AudioUnitElement element)
  28198. {
  28199. ma_device* pDevice = (ma_device*)pUserData;
  28200. MA_ASSERT(pDevice != NULL);
  28201. /* Don't do anything if it looks like we're just reinitializing due to a device switch. */
  28202. if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) ||
  28203. ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) {
  28204. return;
  28205. }
  28206. /*
  28207. There's been a report of a deadlock here when triggered by ma_device_uninit(). It looks like
  28208. AudioUnitGetProprty (called below) and AudioComponentInstanceDispose (called in ma_device_uninit)
  28209. can try waiting on the same lock. I'm going to try working around this by not calling any Core
  28210. Audio APIs in the callback when the device has been stopped or uninitialized.
  28211. */
  28212. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized || ma_device_get_state(pDevice) == ma_device_state_stopping || ma_device_get_state(pDevice) == ma_device_state_stopped) {
  28213. ma_device__on_notification_stopped(pDevice);
  28214. } else {
  28215. UInt32 isRunning;
  28216. UInt32 isRunningSize = sizeof(isRunning);
  28217. OSStatus status = ((ma_AudioUnitGetProperty_proc)pDevice->pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioOutputUnitProperty_IsRunning, scope, element, &isRunning, &isRunningSize);
  28218. if (status != noErr) {
  28219. goto done; /* Don't really know what to do in this case... just ignore it, I suppose... */
  28220. }
  28221. if (!isRunning) {
  28222. /*
  28223. The stop event is a bit annoying in Core Audio because it will be called when we automatically switch the default device. Some scenarios to consider:
  28224. 1) When the device is unplugged, this will be called _before_ the default device change notification.
  28225. 2) When the device is changed via the default device change notification, this will be called _after_ the switch.
  28226. For case #1, we just check if there's a new default device available. If so, we just ignore the stop event. For case #2 we check a flag.
  28227. */
  28228. if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isDefaultPlaybackDevice) ||
  28229. ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isDefaultCaptureDevice)) {
  28230. /*
  28231. It looks like the device is switching through an external event, such as the user unplugging the device or changing the default device
  28232. via the operating system's sound settings. If we're re-initializing the device, we just terminate because we want the stopping of the
  28233. device to be seamless to the client (we don't want them receiving the stopped event and thinking that the device has stopped when it
  28234. hasn't!).
  28235. */
  28236. if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) ||
  28237. ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) {
  28238. goto done;
  28239. }
  28240. /*
  28241. Getting here means the device is not reinitializing which means it may have been unplugged. From what I can see, it looks like Core Audio
  28242. will try switching to the new default device seamlessly. We need to somehow find a way to determine whether or not Core Audio will most
  28243. likely be successful in switching to the new device.
  28244. TODO: Try to predict if Core Audio will switch devices. If not, the stopped callback needs to be posted.
  28245. */
  28246. goto done;
  28247. }
  28248. /* Getting here means we need to stop the device. */
  28249. ma_device__on_notification_stopped(pDevice);
  28250. }
  28251. }
  28252. (void)propertyID; /* Unused. */
  28253. done:
  28254. /* Always signal the stop event. It's possible for the "else" case to get hit which can happen during an interruption. */
  28255. ma_event_signal(&pDevice->coreaudio.stopEvent);
  28256. }
  28257. #if defined(MA_APPLE_DESKTOP)
  28258. static ma_spinlock g_DeviceTrackingInitLock_CoreAudio = 0; /* A spinlock for mutal exclusion of the init/uninit of the global tracking data. Initialization to 0 is what we need. */
  28259. static ma_uint32 g_DeviceTrackingInitCounter_CoreAudio = 0;
  28260. static ma_mutex g_DeviceTrackingMutex_CoreAudio;
  28261. static ma_device** g_ppTrackedDevices_CoreAudio = NULL;
  28262. static ma_uint32 g_TrackedDeviceCap_CoreAudio = 0;
  28263. static ma_uint32 g_TrackedDeviceCount_CoreAudio = 0;
  28264. static OSStatus ma_default_device_changed__coreaudio(AudioObjectID objectID, UInt32 addressCount, const AudioObjectPropertyAddress* pAddresses, void* pUserData)
  28265. {
  28266. ma_device_type deviceType;
  28267. /* Not sure if I really need to check this, but it makes me feel better. */
  28268. if (addressCount == 0) {
  28269. return noErr;
  28270. }
  28271. if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultOutputDevice) {
  28272. deviceType = ma_device_type_playback;
  28273. } else if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultInputDevice) {
  28274. deviceType = ma_device_type_capture;
  28275. } else {
  28276. return noErr; /* Should never hit this. */
  28277. }
  28278. ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio);
  28279. {
  28280. ma_uint32 iDevice;
  28281. for (iDevice = 0; iDevice < g_TrackedDeviceCount_CoreAudio; iDevice += 1) {
  28282. ma_result reinitResult;
  28283. ma_device* pDevice;
  28284. pDevice = g_ppTrackedDevices_CoreAudio[iDevice];
  28285. if (pDevice->type == deviceType || pDevice->type == ma_device_type_duplex) {
  28286. if (deviceType == ma_device_type_playback) {
  28287. pDevice->coreaudio.isSwitchingPlaybackDevice = MA_TRUE;
  28288. reinitResult = ma_device_reinit_internal__coreaudio(pDevice, deviceType, MA_TRUE);
  28289. pDevice->coreaudio.isSwitchingPlaybackDevice = MA_FALSE;
  28290. } else {
  28291. pDevice->coreaudio.isSwitchingCaptureDevice = MA_TRUE;
  28292. reinitResult = ma_device_reinit_internal__coreaudio(pDevice, deviceType, MA_TRUE);
  28293. pDevice->coreaudio.isSwitchingCaptureDevice = MA_FALSE;
  28294. }
  28295. if (reinitResult == MA_SUCCESS) {
  28296. ma_device__post_init_setup(pDevice, deviceType);
  28297. /* Restart the device if required. If this fails we need to stop the device entirely. */
  28298. if (ma_device_get_state(pDevice) == ma_device_state_started) {
  28299. OSStatus status;
  28300. if (deviceType == ma_device_type_playback) {
  28301. status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28302. if (status != noErr) {
  28303. if (pDevice->type == ma_device_type_duplex) {
  28304. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28305. }
  28306. ma_device__set_state(pDevice, ma_device_state_stopped);
  28307. }
  28308. } else if (deviceType == ma_device_type_capture) {
  28309. status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28310. if (status != noErr) {
  28311. if (pDevice->type == ma_device_type_duplex) {
  28312. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28313. }
  28314. ma_device__set_state(pDevice, ma_device_state_stopped);
  28315. }
  28316. }
  28317. }
  28318. ma_device__on_notification_rerouted(pDevice);
  28319. }
  28320. }
  28321. }
  28322. }
  28323. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  28324. /* Unused parameters. */
  28325. (void)objectID;
  28326. (void)pUserData;
  28327. return noErr;
  28328. }
  28329. static ma_result ma_context__init_device_tracking__coreaudio(ma_context* pContext)
  28330. {
  28331. MA_ASSERT(pContext != NULL);
  28332. ma_spinlock_lock(&g_DeviceTrackingInitLock_CoreAudio);
  28333. {
  28334. /* Don't do anything if we've already initializd device tracking. */
  28335. if (g_DeviceTrackingInitCounter_CoreAudio == 0) {
  28336. AudioObjectPropertyAddress propAddress;
  28337. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  28338. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  28339. ma_mutex_init(&g_DeviceTrackingMutex_CoreAudio);
  28340. propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  28341. ((ma_AudioObjectAddPropertyListener_proc)pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  28342. propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  28343. ((ma_AudioObjectAddPropertyListener_proc)pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  28344. }
  28345. g_DeviceTrackingInitCounter_CoreAudio += 1;
  28346. }
  28347. ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio);
  28348. return MA_SUCCESS;
  28349. }
  28350. static ma_result ma_context__uninit_device_tracking__coreaudio(ma_context* pContext)
  28351. {
  28352. MA_ASSERT(pContext != NULL);
  28353. ma_spinlock_lock(&g_DeviceTrackingInitLock_CoreAudio);
  28354. {
  28355. if (g_DeviceTrackingInitCounter_CoreAudio > 0)
  28356. g_DeviceTrackingInitCounter_CoreAudio -= 1;
  28357. if (g_DeviceTrackingInitCounter_CoreAudio == 0) {
  28358. AudioObjectPropertyAddress propAddress;
  28359. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  28360. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  28361. propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  28362. ((ma_AudioObjectRemovePropertyListener_proc)pContext->coreaudio.AudioObjectRemovePropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  28363. propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  28364. ((ma_AudioObjectRemovePropertyListener_proc)pContext->coreaudio.AudioObjectRemovePropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  28365. /* At this point there should be no tracked devices. If not there's an error somewhere. */
  28366. if (g_ppTrackedDevices_CoreAudio != NULL) {
  28367. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "You have uninitialized all contexts while an associated device is still active.");
  28368. ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio);
  28369. return MA_INVALID_OPERATION;
  28370. }
  28371. ma_mutex_uninit(&g_DeviceTrackingMutex_CoreAudio);
  28372. }
  28373. }
  28374. ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio);
  28375. return MA_SUCCESS;
  28376. }
  28377. static ma_result ma_device__track__coreaudio(ma_device* pDevice)
  28378. {
  28379. MA_ASSERT(pDevice != NULL);
  28380. ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio);
  28381. {
  28382. /* Allocate memory if required. */
  28383. if (g_TrackedDeviceCap_CoreAudio <= g_TrackedDeviceCount_CoreAudio) {
  28384. ma_uint32 newCap;
  28385. ma_device** ppNewDevices;
  28386. newCap = g_TrackedDeviceCap_CoreAudio * 2;
  28387. if (newCap == 0) {
  28388. newCap = 1;
  28389. }
  28390. ppNewDevices = (ma_device**)ma_realloc(g_ppTrackedDevices_CoreAudio, sizeof(*g_ppTrackedDevices_CoreAudio)*newCap, &pDevice->pContext->allocationCallbacks);
  28391. if (ppNewDevices == NULL) {
  28392. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  28393. return MA_OUT_OF_MEMORY;
  28394. }
  28395. g_ppTrackedDevices_CoreAudio = ppNewDevices;
  28396. g_TrackedDeviceCap_CoreAudio = newCap;
  28397. }
  28398. g_ppTrackedDevices_CoreAudio[g_TrackedDeviceCount_CoreAudio] = pDevice;
  28399. g_TrackedDeviceCount_CoreAudio += 1;
  28400. }
  28401. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  28402. return MA_SUCCESS;
  28403. }
  28404. static ma_result ma_device__untrack__coreaudio(ma_device* pDevice)
  28405. {
  28406. MA_ASSERT(pDevice != NULL);
  28407. ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio);
  28408. {
  28409. ma_uint32 iDevice;
  28410. for (iDevice = 0; iDevice < g_TrackedDeviceCount_CoreAudio; iDevice += 1) {
  28411. if (g_ppTrackedDevices_CoreAudio[iDevice] == pDevice) {
  28412. /* We've found the device. We now need to remove it from the list. */
  28413. ma_uint32 jDevice;
  28414. for (jDevice = iDevice; jDevice < g_TrackedDeviceCount_CoreAudio-1; jDevice += 1) {
  28415. g_ppTrackedDevices_CoreAudio[jDevice] = g_ppTrackedDevices_CoreAudio[jDevice+1];
  28416. }
  28417. g_TrackedDeviceCount_CoreAudio -= 1;
  28418. /* If there's nothing else in the list we need to free memory. */
  28419. if (g_TrackedDeviceCount_CoreAudio == 0) {
  28420. ma_free(g_ppTrackedDevices_CoreAudio, &pDevice->pContext->allocationCallbacks);
  28421. g_ppTrackedDevices_CoreAudio = NULL;
  28422. g_TrackedDeviceCap_CoreAudio = 0;
  28423. }
  28424. break;
  28425. }
  28426. }
  28427. }
  28428. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  28429. return MA_SUCCESS;
  28430. }
  28431. #endif
  28432. #if defined(MA_APPLE_MOBILE)
  28433. @interface ma_ios_notification_handler:NSObject {
  28434. ma_device* m_pDevice;
  28435. }
  28436. @end
  28437. @implementation ma_ios_notification_handler
  28438. -(id)init:(ma_device*)pDevice
  28439. {
  28440. self = [super init];
  28441. m_pDevice = pDevice;
  28442. /* For route changes. */
  28443. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_route_change:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
  28444. /* For interruptions. */
  28445. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_interruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
  28446. return self;
  28447. }
  28448. -(void)dealloc
  28449. {
  28450. [self remove_handler];
  28451. #if defined(__has_feature)
  28452. #if !__has_feature(objc_arc)
  28453. [super dealloc];
  28454. #endif
  28455. #endif
  28456. }
  28457. -(void)remove_handler
  28458. {
  28459. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil];
  28460. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil];
  28461. }
  28462. -(void)handle_interruption:(NSNotification*)pNotification
  28463. {
  28464. NSInteger type = [[[pNotification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue];
  28465. switch (type)
  28466. {
  28467. case AVAudioSessionInterruptionTypeBegan:
  28468. {
  28469. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Interruption: AVAudioSessionInterruptionTypeBegan\n");
  28470. /*
  28471. Core Audio will have stopped the internal device automatically, but we need explicitly
  28472. stop it at a higher level to ensure miniaudio-specific state is updated for consistency.
  28473. */
  28474. ma_device_stop(m_pDevice);
  28475. /*
  28476. Fire the notification after the device has been stopped to ensure it's in the correct
  28477. state when the notification handler is invoked.
  28478. */
  28479. ma_device__on_notification_interruption_began(m_pDevice);
  28480. } break;
  28481. case AVAudioSessionInterruptionTypeEnded:
  28482. {
  28483. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Interruption: AVAudioSessionInterruptionTypeEnded\n");
  28484. ma_device__on_notification_interruption_ended(m_pDevice);
  28485. } break;
  28486. }
  28487. }
  28488. -(void)handle_route_change:(NSNotification*)pNotification
  28489. {
  28490. AVAudioSession* pSession = [AVAudioSession sharedInstance];
  28491. NSInteger reason = [[[pNotification userInfo] objectForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  28492. switch (reason)
  28493. {
  28494. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
  28495. {
  28496. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonOldDeviceUnavailable\n");
  28497. } break;
  28498. case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
  28499. {
  28500. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonNewDeviceAvailable\n");
  28501. } break;
  28502. case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory:
  28503. {
  28504. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory\n");
  28505. } break;
  28506. case AVAudioSessionRouteChangeReasonWakeFromSleep:
  28507. {
  28508. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonWakeFromSleep\n");
  28509. } break;
  28510. case AVAudioSessionRouteChangeReasonOverride:
  28511. {
  28512. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonOverride\n");
  28513. } break;
  28514. case AVAudioSessionRouteChangeReasonCategoryChange:
  28515. {
  28516. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonCategoryChange\n");
  28517. } break;
  28518. case AVAudioSessionRouteChangeReasonUnknown:
  28519. default:
  28520. {
  28521. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonUnknown\n");
  28522. } break;
  28523. }
  28524. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_DEBUG, "[Core Audio] Changing Route. inputNumberChannels=%d; outputNumberOfChannels=%d\n", (int)pSession.inputNumberOfChannels, (int)pSession.outputNumberOfChannels);
  28525. /* Let the application know about the route change. */
  28526. ma_device__on_notification_rerouted(m_pDevice);
  28527. }
  28528. @end
  28529. #endif
  28530. static ma_result ma_device_uninit__coreaudio(ma_device* pDevice)
  28531. {
  28532. MA_ASSERT(pDevice != NULL);
  28533. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_uninitialized);
  28534. #if defined(MA_APPLE_DESKTOP)
  28535. /*
  28536. Make sure we're no longer tracking the device. It doesn't matter if we call this for a non-default device because it'll
  28537. just gracefully ignore it.
  28538. */
  28539. ma_device__untrack__coreaudio(pDevice);
  28540. #endif
  28541. #if defined(MA_APPLE_MOBILE)
  28542. if (pDevice->coreaudio.pNotificationHandler != NULL) {
  28543. ma_ios_notification_handler* pNotificationHandler = (MA_BRIDGE_TRANSFER ma_ios_notification_handler*)pDevice->coreaudio.pNotificationHandler;
  28544. [pNotificationHandler remove_handler];
  28545. }
  28546. #endif
  28547. if (pDevice->coreaudio.audioUnitCapture != NULL) {
  28548. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28549. }
  28550. if (pDevice->coreaudio.audioUnitPlayback != NULL) {
  28551. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28552. }
  28553. if (pDevice->coreaudio.pAudioBufferList) {
  28554. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  28555. }
  28556. return MA_SUCCESS;
  28557. }
  28558. typedef struct
  28559. {
  28560. ma_bool32 allowNominalSampleRateChange;
  28561. /* Input. */
  28562. ma_format formatIn;
  28563. ma_uint32 channelsIn;
  28564. ma_uint32 sampleRateIn;
  28565. ma_channel channelMapIn[MA_MAX_CHANNELS];
  28566. ma_uint32 periodSizeInFramesIn;
  28567. ma_uint32 periodSizeInMillisecondsIn;
  28568. ma_uint32 periodsIn;
  28569. ma_share_mode shareMode;
  28570. ma_performance_profile performanceProfile;
  28571. ma_bool32 registerStopEvent;
  28572. /* Output. */
  28573. #if defined(MA_APPLE_DESKTOP)
  28574. AudioObjectID deviceObjectID;
  28575. #endif
  28576. AudioComponent component;
  28577. AudioUnit audioUnit;
  28578. AudioBufferList* pAudioBufferList; /* Only used for input devices. */
  28579. ma_format formatOut;
  28580. ma_uint32 channelsOut;
  28581. ma_uint32 sampleRateOut;
  28582. ma_channel channelMapOut[MA_MAX_CHANNELS];
  28583. ma_uint32 periodSizeInFramesOut;
  28584. ma_uint32 periodsOut;
  28585. char deviceName[256];
  28586. } ma_device_init_internal_data__coreaudio;
  28587. static ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_init_internal_data__coreaudio* pData, void* pDevice_DoNotReference) /* <-- pDevice is typed as void* intentionally so as to avoid accidentally referencing it. */
  28588. {
  28589. ma_result result;
  28590. OSStatus status;
  28591. UInt32 enableIOFlag;
  28592. AudioStreamBasicDescription bestFormat;
  28593. UInt32 actualPeriodSizeInFrames;
  28594. AURenderCallbackStruct callbackInfo;
  28595. #if defined(MA_APPLE_DESKTOP)
  28596. AudioObjectID deviceObjectID;
  28597. #endif
  28598. /* This API should only be used for a single device type: playback or capture. No full-duplex mode. */
  28599. if (deviceType == ma_device_type_duplex) {
  28600. return MA_INVALID_ARGS;
  28601. }
  28602. MA_ASSERT(pContext != NULL);
  28603. MA_ASSERT(deviceType == ma_device_type_playback || deviceType == ma_device_type_capture);
  28604. #if defined(MA_APPLE_DESKTOP)
  28605. pData->deviceObjectID = 0;
  28606. #endif
  28607. pData->component = NULL;
  28608. pData->audioUnit = NULL;
  28609. pData->pAudioBufferList = NULL;
  28610. #if defined(MA_APPLE_DESKTOP)
  28611. result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID);
  28612. if (result != MA_SUCCESS) {
  28613. return result;
  28614. }
  28615. pData->deviceObjectID = deviceObjectID;
  28616. #endif
  28617. /* Core audio doesn't really use the notion of a period so we can leave this unmodified, but not too over the top. */
  28618. pData->periodsOut = pData->periodsIn;
  28619. if (pData->periodsOut == 0) {
  28620. pData->periodsOut = MA_DEFAULT_PERIODS;
  28621. }
  28622. if (pData->periodsOut > 16) {
  28623. pData->periodsOut = 16;
  28624. }
  28625. /* Audio unit. */
  28626. status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)((AudioComponent)pContext->coreaudio.component, (AudioUnit*)&pData->audioUnit);
  28627. if (status != noErr) {
  28628. return ma_result_from_OSStatus(status);
  28629. }
  28630. /* The input/output buses need to be explicitly enabled and disabled. We set the flag based on the output unit first, then we just swap it for input. */
  28631. enableIOFlag = 1;
  28632. if (deviceType == ma_device_type_capture) {
  28633. enableIOFlag = 0;
  28634. }
  28635. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, MA_COREAUDIO_OUTPUT_BUS, &enableIOFlag, sizeof(enableIOFlag));
  28636. if (status != noErr) {
  28637. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28638. return ma_result_from_OSStatus(status);
  28639. }
  28640. enableIOFlag = (enableIOFlag == 0) ? 1 : 0;
  28641. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, MA_COREAUDIO_INPUT_BUS, &enableIOFlag, sizeof(enableIOFlag));
  28642. if (status != noErr) {
  28643. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28644. return ma_result_from_OSStatus(status);
  28645. }
  28646. /* Set the device to use with this audio unit. This is only used on desktop since we are using defaults on mobile. */
  28647. #if defined(MA_APPLE_DESKTOP)
  28648. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &deviceObjectID, sizeof(deviceObjectID));
  28649. if (status != noErr) {
  28650. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28651. return ma_result_from_OSStatus(result);
  28652. }
  28653. #else
  28654. /*
  28655. For some reason it looks like Apple is only allowing selection of the input device. There does not appear to be any way to change
  28656. the default output route. I have no idea why this is like this, but for now we'll only be able to configure capture devices.
  28657. */
  28658. if (pDeviceID != NULL) {
  28659. if (deviceType == ma_device_type_capture) {
  28660. ma_bool32 found = MA_FALSE;
  28661. NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs];
  28662. for (AVAudioSessionPortDescription* pPortDesc in pInputs) {
  28663. if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) {
  28664. [[AVAudioSession sharedInstance] setPreferredInput:pPortDesc error:nil];
  28665. found = MA_TRUE;
  28666. break;
  28667. }
  28668. }
  28669. if (found == MA_FALSE) {
  28670. return MA_DOES_NOT_EXIST;
  28671. }
  28672. }
  28673. }
  28674. #endif
  28675. /*
  28676. Format. This is the hardest part of initialization because there's a few variables to take into account.
  28677. 1) The format must be supported by the device.
  28678. 2) The format must be supported miniaudio.
  28679. 3) There's a priority that miniaudio prefers.
  28680. Ideally we would like to use a format that's as close to the hardware as possible so we can get as close to a passthrough as possible. The
  28681. most important property is the sample rate. miniaudio can do format conversion for any sample rate and channel count, but cannot do the same
  28682. for the sample data format. If the sample data format is not supported by miniaudio it must be ignored completely.
  28683. On mobile platforms this is a bit different. We just force the use of whatever the audio unit's current format is set to.
  28684. */
  28685. {
  28686. AudioStreamBasicDescription origFormat;
  28687. UInt32 origFormatSize = sizeof(origFormat);
  28688. AudioUnitScope formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output;
  28689. AudioUnitElement formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS;
  28690. if (deviceType == ma_device_type_playback) {
  28691. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, MA_COREAUDIO_OUTPUT_BUS, &origFormat, &origFormatSize);
  28692. } else {
  28693. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, MA_COREAUDIO_INPUT_BUS, &origFormat, &origFormatSize);
  28694. }
  28695. if (status != noErr) {
  28696. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28697. return ma_result_from_OSStatus(status);
  28698. }
  28699. #if defined(MA_APPLE_DESKTOP)
  28700. result = ma_find_best_format__coreaudio(pContext, deviceObjectID, deviceType, pData->formatIn, pData->channelsIn, pData->sampleRateIn, &origFormat, &bestFormat);
  28701. if (result != MA_SUCCESS) {
  28702. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28703. return result;
  28704. }
  28705. /*
  28706. Technical Note TN2091: Device input using the HAL Output Audio Unit
  28707. https://developer.apple.com/library/archive/technotes/tn2091/_index.html
  28708. This documentation says the following:
  28709. The internal AudioConverter can handle any *simple* conversion. Typically, this means that a client can specify ANY
  28710. variant of the PCM formats. Consequently, the device's sample rate should match the desired sample rate. If sample rate
  28711. conversion is needed, it can be accomplished by buffering the input and converting the data on a separate thread with
  28712. another AudioConverter.
  28713. The important part here is the mention that it can handle *simple* conversions, which does *not* include sample rate. We
  28714. therefore want to ensure the sample rate stays consistent. This document is specifically for input, but I'm going to play it
  28715. safe and apply the same rule to output as well.
  28716. I have tried going against the documentation by setting the sample rate anyway, but this just results in AudioUnitRender()
  28717. returning a result code of -10863. I have also tried changing the format directly on the input scope on the input bus, but
  28718. this just results in `ca_require: IsStreamFormatWritable(inScope, inElement) NotWritable` when trying to set the format.
  28719. Something that does seem to work, however, has been setting the nominal sample rate on the deivce object. The problem with
  28720. this, however, is that it actually changes the sample rate at the operating system level and not just the application. This
  28721. could be intrusive to the user, however, so I don't think it's wise to make this the default. Instead I'm making this a
  28722. configuration option. When the `coreaudio.allowNominalSampleRateChange` config option is set to true, changing the sample
  28723. rate will be allowed. Otherwise it'll be fixed to the current sample rate. To check the system-defined sample rate, run
  28724. the Audio MIDI Setup program that comes installed on macOS and observe how the sample rate changes as the sample rate is
  28725. changed by miniaudio.
  28726. */
  28727. if (pData->allowNominalSampleRateChange) {
  28728. AudioValueRange sampleRateRange;
  28729. AudioObjectPropertyAddress propAddress;
  28730. sampleRateRange.mMinimum = bestFormat.mSampleRate;
  28731. sampleRateRange.mMaximum = bestFormat.mSampleRate;
  28732. propAddress.mSelector = kAudioDevicePropertyNominalSampleRate;
  28733. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  28734. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  28735. status = ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(sampleRateRange), &sampleRateRange);
  28736. if (status != noErr) {
  28737. bestFormat.mSampleRate = origFormat.mSampleRate;
  28738. }
  28739. } else {
  28740. bestFormat.mSampleRate = origFormat.mSampleRate;
  28741. }
  28742. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat));
  28743. if (status != noErr) {
  28744. /* We failed to set the format, so fall back to the current format of the audio unit. */
  28745. bestFormat = origFormat;
  28746. }
  28747. #else
  28748. bestFormat = origFormat;
  28749. /*
  28750. Sample rate is a little different here because for some reason kAudioUnitProperty_StreamFormat returns 0... Oh well. We need to instead try
  28751. setting the sample rate to what the user has requested and then just see the results of it. Need to use some Objective-C here for this since
  28752. it depends on Apple's AVAudioSession API. To do this we just get the shared AVAudioSession instance and then set it. Note that from what I
  28753. can tell, it looks like the sample rate is shared between playback and capture for everything.
  28754. */
  28755. @autoreleasepool {
  28756. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  28757. MA_ASSERT(pAudioSession != NULL);
  28758. [pAudioSession setPreferredSampleRate:(double)pData->sampleRateIn error:nil];
  28759. bestFormat.mSampleRate = pAudioSession.sampleRate;
  28760. /*
  28761. I've had a report that the channel count returned by AudioUnitGetProperty above is inconsistent with
  28762. AVAudioSession outputNumberOfChannels. I'm going to try using the AVAudioSession values instead.
  28763. */
  28764. if (deviceType == ma_device_type_playback) {
  28765. bestFormat.mChannelsPerFrame = (UInt32)pAudioSession.outputNumberOfChannels;
  28766. }
  28767. if (deviceType == ma_device_type_capture) {
  28768. bestFormat.mChannelsPerFrame = (UInt32)pAudioSession.inputNumberOfChannels;
  28769. }
  28770. }
  28771. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat));
  28772. if (status != noErr) {
  28773. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28774. return ma_result_from_OSStatus(status);
  28775. }
  28776. #endif
  28777. result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pData->formatOut);
  28778. if (result != MA_SUCCESS) {
  28779. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28780. return result;
  28781. }
  28782. if (pData->formatOut == ma_format_unknown) {
  28783. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28784. return MA_FORMAT_NOT_SUPPORTED;
  28785. }
  28786. pData->channelsOut = bestFormat.mChannelsPerFrame;
  28787. pData->sampleRateOut = bestFormat.mSampleRate;
  28788. }
  28789. /* Clamp the channel count for safety. */
  28790. if (pData->channelsOut > MA_MAX_CHANNELS) {
  28791. pData->channelsOut = MA_MAX_CHANNELS;
  28792. }
  28793. /*
  28794. Internal channel map. This is weird in my testing. If I use the AudioObject to get the
  28795. channel map, the channel descriptions are set to "Unknown" for some reason. To work around
  28796. this it looks like retrieving it from the AudioUnit will work. However, and this is where
  28797. it gets weird, it doesn't seem to work with capture devices, nor at all on iOS... Therefore
  28798. I'm going to fall back to a default assumption in these cases.
  28799. */
  28800. #if defined(MA_APPLE_DESKTOP)
  28801. result = ma_get_AudioUnit_channel_map(pContext, pData->audioUnit, deviceType, pData->channelMapOut, pData->channelsOut);
  28802. if (result != MA_SUCCESS) {
  28803. #if 0
  28804. /* Try falling back to the channel map from the AudioObject. */
  28805. result = ma_get_AudioObject_channel_map(pContext, deviceObjectID, deviceType, pData->channelMapOut, pData->channelsOut);
  28806. if (result != MA_SUCCESS) {
  28807. return result;
  28808. }
  28809. #else
  28810. /* Fall back to default assumptions. */
  28811. ma_channel_map_init_standard(ma_standard_channel_map_default, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut);
  28812. #endif
  28813. }
  28814. #else
  28815. /* TODO: Figure out how to get the channel map using AVAudioSession. */
  28816. ma_channel_map_init_standard(ma_standard_channel_map_default, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut);
  28817. #endif
  28818. /* Buffer size. Not allowing this to be configurable on iOS. */
  28819. if (pData->periodSizeInFramesIn == 0) {
  28820. if (pData->periodSizeInMillisecondsIn == 0) {
  28821. if (pData->performanceProfile == ma_performance_profile_low_latency) {
  28822. actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, pData->sampleRateOut);
  28823. } else {
  28824. actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, pData->sampleRateOut);
  28825. }
  28826. } else {
  28827. actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, pData->sampleRateOut);
  28828. }
  28829. } else {
  28830. actualPeriodSizeInFrames = pData->periodSizeInFramesIn;
  28831. }
  28832. #if defined(MA_APPLE_DESKTOP)
  28833. result = ma_set_AudioObject_buffer_size_in_frames(pContext, deviceObjectID, deviceType, &actualPeriodSizeInFrames);
  28834. if (result != MA_SUCCESS) {
  28835. return result;
  28836. }
  28837. #else
  28838. /*
  28839. On iOS, the size of the IO buffer needs to be specified in seconds and is a floating point
  28840. number. I don't trust any potential truncation errors due to converting from float to integer
  28841. so I'm going to explicitly set the actual period size to the next power of 2.
  28842. */
  28843. @autoreleasepool {
  28844. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  28845. MA_ASSERT(pAudioSession != NULL);
  28846. [pAudioSession setPreferredIOBufferDuration:((float)actualPeriodSizeInFrames / pAudioSession.sampleRate) error:nil];
  28847. actualPeriodSizeInFrames = ma_next_power_of_2((ma_uint32)(pAudioSession.IOBufferDuration * pAudioSession.sampleRate));
  28848. }
  28849. #endif
  28850. /*
  28851. During testing I discovered that the buffer size can be too big. You'll get an error like this:
  28852. kAudioUnitErr_TooManyFramesToProcess : inFramesToProcess=4096, mMaxFramesPerSlice=512
  28853. Note how inFramesToProcess is smaller than mMaxFramesPerSlice. To fix, we need to set kAudioUnitProperty_MaximumFramesPerSlice to that
  28854. of the size of our buffer, or do it the other way around and set our buffer size to the kAudioUnitProperty_MaximumFramesPerSlice.
  28855. */
  28856. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &actualPeriodSizeInFrames, sizeof(actualPeriodSizeInFrames));
  28857. if (status != noErr) {
  28858. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28859. return ma_result_from_OSStatus(status);
  28860. }
  28861. pData->periodSizeInFramesOut = (ma_uint32)actualPeriodSizeInFrames;
  28862. /* We need a buffer list if this is an input device. We render into this in the input callback. */
  28863. if (deviceType == ma_device_type_capture) {
  28864. ma_bool32 isInterleaved = (bestFormat.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0;
  28865. AudioBufferList* pBufferList;
  28866. pBufferList = ma_allocate_AudioBufferList__coreaudio(pData->periodSizeInFramesOut, pData->formatOut, pData->channelsOut, (isInterleaved) ? ma_stream_layout_interleaved : ma_stream_layout_deinterleaved, &pContext->allocationCallbacks);
  28867. if (pBufferList == NULL) {
  28868. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28869. return MA_OUT_OF_MEMORY;
  28870. }
  28871. pData->pAudioBufferList = pBufferList;
  28872. }
  28873. /* Callbacks. */
  28874. callbackInfo.inputProcRefCon = pDevice_DoNotReference;
  28875. if (deviceType == ma_device_type_playback) {
  28876. callbackInfo.inputProc = ma_on_output__coreaudio;
  28877. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, 0, &callbackInfo, sizeof(callbackInfo));
  28878. if (status != noErr) {
  28879. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28880. return ma_result_from_OSStatus(status);
  28881. }
  28882. } else {
  28883. callbackInfo.inputProc = ma_on_input__coreaudio;
  28884. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &callbackInfo, sizeof(callbackInfo));
  28885. if (status != noErr) {
  28886. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28887. return ma_result_from_OSStatus(status);
  28888. }
  28889. }
  28890. /* We need to listen for stop events. */
  28891. if (pData->registerStopEvent) {
  28892. status = ((ma_AudioUnitAddPropertyListener_proc)pContext->coreaudio.AudioUnitAddPropertyListener)(pData->audioUnit, kAudioOutputUnitProperty_IsRunning, on_start_stop__coreaudio, pDevice_DoNotReference);
  28893. if (status != noErr) {
  28894. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28895. return ma_result_from_OSStatus(status);
  28896. }
  28897. }
  28898. /* Initialize the audio unit. */
  28899. status = ((ma_AudioUnitInitialize_proc)pContext->coreaudio.AudioUnitInitialize)(pData->audioUnit);
  28900. if (status != noErr) {
  28901. ma_free(pData->pAudioBufferList, &pContext->allocationCallbacks);
  28902. pData->pAudioBufferList = NULL;
  28903. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28904. return ma_result_from_OSStatus(status);
  28905. }
  28906. /* Grab the name. */
  28907. #if defined(MA_APPLE_DESKTOP)
  28908. ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pData->deviceName), pData->deviceName);
  28909. #else
  28910. if (deviceType == ma_device_type_playback) {
  28911. ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_PLAYBACK_DEVICE_NAME);
  28912. } else {
  28913. ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_CAPTURE_DEVICE_NAME);
  28914. }
  28915. #endif
  28916. return result;
  28917. }
  28918. #if defined(MA_APPLE_DESKTOP)
  28919. static ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit)
  28920. {
  28921. ma_device_init_internal_data__coreaudio data;
  28922. ma_result result;
  28923. /* This should only be called for playback or capture, not duplex. */
  28924. if (deviceType == ma_device_type_duplex) {
  28925. return MA_INVALID_ARGS;
  28926. }
  28927. data.allowNominalSampleRateChange = MA_FALSE; /* Don't change the nominal sample rate when switching devices. */
  28928. if (deviceType == ma_device_type_capture) {
  28929. data.formatIn = pDevice->capture.format;
  28930. data.channelsIn = pDevice->capture.channels;
  28931. data.sampleRateIn = pDevice->sampleRate;
  28932. MA_COPY_MEMORY(data.channelMapIn, pDevice->capture.channelMap, sizeof(pDevice->capture.channelMap));
  28933. data.shareMode = pDevice->capture.shareMode;
  28934. data.performanceProfile = pDevice->coreaudio.originalPerformanceProfile;
  28935. data.registerStopEvent = MA_TRUE;
  28936. if (disposePreviousAudioUnit) {
  28937. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28938. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28939. }
  28940. if (pDevice->coreaudio.pAudioBufferList) {
  28941. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  28942. }
  28943. } else if (deviceType == ma_device_type_playback) {
  28944. data.formatIn = pDevice->playback.format;
  28945. data.channelsIn = pDevice->playback.channels;
  28946. data.sampleRateIn = pDevice->sampleRate;
  28947. MA_COPY_MEMORY(data.channelMapIn, pDevice->playback.channelMap, sizeof(pDevice->playback.channelMap));
  28948. data.shareMode = pDevice->playback.shareMode;
  28949. data.performanceProfile = pDevice->coreaudio.originalPerformanceProfile;
  28950. data.registerStopEvent = (pDevice->type != ma_device_type_duplex);
  28951. if (disposePreviousAudioUnit) {
  28952. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28953. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28954. }
  28955. }
  28956. data.periodSizeInFramesIn = pDevice->coreaudio.originalPeriodSizeInFrames;
  28957. data.periodSizeInMillisecondsIn = pDevice->coreaudio.originalPeriodSizeInMilliseconds;
  28958. data.periodsIn = pDevice->coreaudio.originalPeriods;
  28959. /* Need at least 3 periods for duplex. */
  28960. if (data.periodsIn < 3 && pDevice->type == ma_device_type_duplex) {
  28961. data.periodsIn = 3;
  28962. }
  28963. result = ma_device_init_internal__coreaudio(pDevice->pContext, deviceType, NULL, &data, (void*)pDevice);
  28964. if (result != MA_SUCCESS) {
  28965. return result;
  28966. }
  28967. if (deviceType == ma_device_type_capture) {
  28968. #if defined(MA_APPLE_DESKTOP)
  28969. pDevice->coreaudio.deviceObjectIDCapture = (ma_uint32)data.deviceObjectID;
  28970. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDCapture, sizeof(pDevice->capture.id.coreaudio), pDevice->capture.id.coreaudio);
  28971. #endif
  28972. pDevice->coreaudio.audioUnitCapture = (ma_ptr)data.audioUnit;
  28973. pDevice->coreaudio.pAudioBufferList = (ma_ptr)data.pAudioBufferList;
  28974. pDevice->coreaudio.audioBufferCapInFrames = data.periodSizeInFramesOut;
  28975. pDevice->capture.internalFormat = data.formatOut;
  28976. pDevice->capture.internalChannels = data.channelsOut;
  28977. pDevice->capture.internalSampleRate = data.sampleRateOut;
  28978. MA_COPY_MEMORY(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  28979. pDevice->capture.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  28980. pDevice->capture.internalPeriods = data.periodsOut;
  28981. } else if (deviceType == ma_device_type_playback) {
  28982. #if defined(MA_APPLE_DESKTOP)
  28983. pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID;
  28984. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDPlayback, sizeof(pDevice->playback.id.coreaudio), pDevice->playback.id.coreaudio);
  28985. #endif
  28986. pDevice->coreaudio.audioUnitPlayback = (ma_ptr)data.audioUnit;
  28987. pDevice->playback.internalFormat = data.formatOut;
  28988. pDevice->playback.internalChannels = data.channelsOut;
  28989. pDevice->playback.internalSampleRate = data.sampleRateOut;
  28990. MA_COPY_MEMORY(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  28991. pDevice->playback.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  28992. pDevice->playback.internalPeriods = data.periodsOut;
  28993. }
  28994. return MA_SUCCESS;
  28995. }
  28996. #endif /* MA_APPLE_DESKTOP */
  28997. static ma_result ma_device_init__coreaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  28998. {
  28999. ma_result result;
  29000. MA_ASSERT(pDevice != NULL);
  29001. MA_ASSERT(pConfig != NULL);
  29002. if (pConfig->deviceType == ma_device_type_loopback) {
  29003. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  29004. }
  29005. /* No exclusive mode with the Core Audio backend for now. */
  29006. if (((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive) ||
  29007. ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive)) {
  29008. return MA_SHARE_MODE_NOT_SUPPORTED;
  29009. }
  29010. /* Capture needs to be initialized first. */
  29011. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  29012. ma_device_init_internal_data__coreaudio data;
  29013. data.allowNominalSampleRateChange = pConfig->coreaudio.allowNominalSampleRateChange;
  29014. data.formatIn = pDescriptorCapture->format;
  29015. data.channelsIn = pDescriptorCapture->channels;
  29016. data.sampleRateIn = pDescriptorCapture->sampleRate;
  29017. MA_COPY_MEMORY(data.channelMapIn, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
  29018. data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
  29019. data.periodSizeInMillisecondsIn = pDescriptorCapture->periodSizeInMilliseconds;
  29020. data.periodsIn = pDescriptorCapture->periodCount;
  29021. data.shareMode = pDescriptorCapture->shareMode;
  29022. data.performanceProfile = pConfig->performanceProfile;
  29023. data.registerStopEvent = MA_TRUE;
  29024. /* Need at least 3 periods for duplex. */
  29025. if (data.periodsIn < 3 && pConfig->deviceType == ma_device_type_duplex) {
  29026. data.periodsIn = 3;
  29027. }
  29028. result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_capture, pDescriptorCapture->pDeviceID, &data, (void*)pDevice);
  29029. if (result != MA_SUCCESS) {
  29030. return result;
  29031. }
  29032. pDevice->coreaudio.isDefaultCaptureDevice = (pConfig->capture.pDeviceID == NULL);
  29033. #if defined(MA_APPLE_DESKTOP)
  29034. pDevice->coreaudio.deviceObjectIDCapture = (ma_uint32)data.deviceObjectID;
  29035. #endif
  29036. pDevice->coreaudio.audioUnitCapture = (ma_ptr)data.audioUnit;
  29037. pDevice->coreaudio.pAudioBufferList = (ma_ptr)data.pAudioBufferList;
  29038. pDevice->coreaudio.audioBufferCapInFrames = data.periodSizeInFramesOut;
  29039. pDevice->coreaudio.originalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
  29040. pDevice->coreaudio.originalPeriodSizeInMilliseconds = pDescriptorCapture->periodSizeInMilliseconds;
  29041. pDevice->coreaudio.originalPeriods = pDescriptorCapture->periodCount;
  29042. pDevice->coreaudio.originalPerformanceProfile = pConfig->performanceProfile;
  29043. pDescriptorCapture->format = data.formatOut;
  29044. pDescriptorCapture->channels = data.channelsOut;
  29045. pDescriptorCapture->sampleRate = data.sampleRateOut;
  29046. MA_COPY_MEMORY(pDescriptorCapture->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  29047. pDescriptorCapture->periodSizeInFrames = data.periodSizeInFramesOut;
  29048. pDescriptorCapture->periodCount = data.periodsOut;
  29049. #if defined(MA_APPLE_DESKTOP)
  29050. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDCapture, sizeof(pDevice->capture.id.coreaudio), pDevice->capture.id.coreaudio);
  29051. /*
  29052. If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly
  29053. switch the device in the background.
  29054. */
  29055. if (pConfig->capture.pDeviceID == NULL) {
  29056. ma_device__track__coreaudio(pDevice);
  29057. }
  29058. #endif
  29059. }
  29060. /* Playback. */
  29061. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  29062. ma_device_init_internal_data__coreaudio data;
  29063. data.allowNominalSampleRateChange = pConfig->coreaudio.allowNominalSampleRateChange;
  29064. data.formatIn = pDescriptorPlayback->format;
  29065. data.channelsIn = pDescriptorPlayback->channels;
  29066. data.sampleRateIn = pDescriptorPlayback->sampleRate;
  29067. MA_COPY_MEMORY(data.channelMapIn, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
  29068. data.shareMode = pDescriptorPlayback->shareMode;
  29069. data.performanceProfile = pConfig->performanceProfile;
  29070. /* In full-duplex mode we want the playback buffer to be the same size as the capture buffer. */
  29071. if (pConfig->deviceType == ma_device_type_duplex) {
  29072. data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
  29073. data.periodsIn = pDescriptorCapture->periodCount;
  29074. data.registerStopEvent = MA_FALSE;
  29075. } else {
  29076. data.periodSizeInFramesIn = pDescriptorPlayback->periodSizeInFrames;
  29077. data.periodSizeInMillisecondsIn = pDescriptorPlayback->periodSizeInMilliseconds;
  29078. data.periodsIn = pDescriptorPlayback->periodCount;
  29079. data.registerStopEvent = MA_TRUE;
  29080. }
  29081. result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_playback, pDescriptorPlayback->pDeviceID, &data, (void*)pDevice);
  29082. if (result != MA_SUCCESS) {
  29083. if (pConfig->deviceType == ma_device_type_duplex) {
  29084. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  29085. if (pDevice->coreaudio.pAudioBufferList) {
  29086. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  29087. }
  29088. }
  29089. return result;
  29090. }
  29091. pDevice->coreaudio.isDefaultPlaybackDevice = (pConfig->playback.pDeviceID == NULL);
  29092. #if defined(MA_APPLE_DESKTOP)
  29093. pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID;
  29094. #endif
  29095. pDevice->coreaudio.audioUnitPlayback = (ma_ptr)data.audioUnit;
  29096. pDevice->coreaudio.originalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
  29097. pDevice->coreaudio.originalPeriodSizeInMilliseconds = pDescriptorPlayback->periodSizeInMilliseconds;
  29098. pDevice->coreaudio.originalPeriods = pDescriptorPlayback->periodCount;
  29099. pDevice->coreaudio.originalPerformanceProfile = pConfig->performanceProfile;
  29100. pDescriptorPlayback->format = data.formatOut;
  29101. pDescriptorPlayback->channels = data.channelsOut;
  29102. pDescriptorPlayback->sampleRate = data.sampleRateOut;
  29103. MA_COPY_MEMORY(pDescriptorPlayback->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  29104. pDescriptorPlayback->periodSizeInFrames = data.periodSizeInFramesOut;
  29105. pDescriptorPlayback->periodCount = data.periodsOut;
  29106. #if defined(MA_APPLE_DESKTOP)
  29107. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDPlayback, sizeof(pDevice->playback.id.coreaudio), pDevice->playback.id.coreaudio);
  29108. /*
  29109. If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly
  29110. switch the device in the background.
  29111. */
  29112. if (pDescriptorPlayback->pDeviceID == NULL && (pConfig->deviceType != ma_device_type_duplex || pDescriptorCapture->pDeviceID != NULL)) {
  29113. ma_device__track__coreaudio(pDevice);
  29114. }
  29115. #endif
  29116. }
  29117. /*
  29118. When stopping the device, a callback is called on another thread. We need to wait for this callback
  29119. before returning from ma_device_stop(). This event is used for this.
  29120. */
  29121. ma_event_init(&pDevice->coreaudio.stopEvent);
  29122. /*
  29123. We need to detect when a route has changed so we can update the data conversion pipeline accordingly. This is done
  29124. differently on non-Desktop Apple platforms.
  29125. */
  29126. #if defined(MA_APPLE_MOBILE)
  29127. pDevice->coreaudio.pNotificationHandler = (MA_BRIDGE_RETAINED void*)[[ma_ios_notification_handler alloc] init:pDevice];
  29128. #endif
  29129. return MA_SUCCESS;
  29130. }
  29131. static ma_result ma_device_start__coreaudio(ma_device* pDevice)
  29132. {
  29133. MA_ASSERT(pDevice != NULL);
  29134. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29135. OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  29136. if (status != noErr) {
  29137. return ma_result_from_OSStatus(status);
  29138. }
  29139. }
  29140. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29141. OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  29142. if (status != noErr) {
  29143. if (pDevice->type == ma_device_type_duplex) {
  29144. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  29145. }
  29146. return ma_result_from_OSStatus(status);
  29147. }
  29148. }
  29149. return MA_SUCCESS;
  29150. }
  29151. static ma_result ma_device_stop__coreaudio(ma_device* pDevice)
  29152. {
  29153. MA_ASSERT(pDevice != NULL);
  29154. /* It's not clear from the documentation whether or not AudioOutputUnitStop() actually drains the device or not. */
  29155. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29156. OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  29157. if (status != noErr) {
  29158. return ma_result_from_OSStatus(status);
  29159. }
  29160. }
  29161. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29162. OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  29163. if (status != noErr) {
  29164. return ma_result_from_OSStatus(status);
  29165. }
  29166. }
  29167. /* We need to wait for the callback to finish before returning. */
  29168. ma_event_wait(&pDevice->coreaudio.stopEvent);
  29169. return MA_SUCCESS;
  29170. }
  29171. static ma_result ma_context_uninit__coreaudio(ma_context* pContext)
  29172. {
  29173. MA_ASSERT(pContext != NULL);
  29174. MA_ASSERT(pContext->backend == ma_backend_coreaudio);
  29175. #if defined(MA_APPLE_MOBILE)
  29176. if (!pContext->coreaudio.noAudioSessionDeactivate) {
  29177. if (![[AVAudioSession sharedInstance] setActive:false error:nil]) {
  29178. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "Failed to deactivate audio session.");
  29179. return MA_FAILED_TO_INIT_BACKEND;
  29180. }
  29181. }
  29182. #endif
  29183. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  29184. ma_dlclose(pContext, pContext->coreaudio.hAudioUnit);
  29185. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  29186. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  29187. #endif
  29188. #if !defined(MA_APPLE_MOBILE)
  29189. ma_context__uninit_device_tracking__coreaudio(pContext);
  29190. #endif
  29191. (void)pContext;
  29192. return MA_SUCCESS;
  29193. }
  29194. #if defined(MA_APPLE_MOBILE) && defined(__IPHONE_12_0)
  29195. static AVAudioSessionCategory ma_to_AVAudioSessionCategory(ma_ios_session_category category)
  29196. {
  29197. /* The "default" and "none" categories are treated different and should not be used as an input into this function. */
  29198. MA_ASSERT(category != ma_ios_session_category_default);
  29199. MA_ASSERT(category != ma_ios_session_category_none);
  29200. switch (category) {
  29201. case ma_ios_session_category_ambient: return AVAudioSessionCategoryAmbient;
  29202. case ma_ios_session_category_solo_ambient: return AVAudioSessionCategorySoloAmbient;
  29203. case ma_ios_session_category_playback: return AVAudioSessionCategoryPlayback;
  29204. case ma_ios_session_category_record: return AVAudioSessionCategoryRecord;
  29205. case ma_ios_session_category_play_and_record: return AVAudioSessionCategoryPlayAndRecord;
  29206. case ma_ios_session_category_multi_route: return AVAudioSessionCategoryMultiRoute;
  29207. case ma_ios_session_category_none: return AVAudioSessionCategoryAmbient;
  29208. case ma_ios_session_category_default: return AVAudioSessionCategoryAmbient;
  29209. default: return AVAudioSessionCategoryAmbient;
  29210. }
  29211. }
  29212. #endif
  29213. static ma_result ma_context_init__coreaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  29214. {
  29215. #if !defined(MA_APPLE_MOBILE)
  29216. ma_result result;
  29217. #endif
  29218. MA_ASSERT(pConfig != NULL);
  29219. MA_ASSERT(pContext != NULL);
  29220. #if defined(MA_APPLE_MOBILE)
  29221. @autoreleasepool {
  29222. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  29223. AVAudioSessionCategoryOptions options = pConfig->coreaudio.sessionCategoryOptions;
  29224. MA_ASSERT(pAudioSession != NULL);
  29225. if (pConfig->coreaudio.sessionCategory == ma_ios_session_category_default) {
  29226. /*
  29227. I'm going to use trial and error to determine our default session category. First we'll try PlayAndRecord. If that fails
  29228. we'll try Playback and if that fails we'll try record. If all of these fail we'll just not set the category.
  29229. */
  29230. #if !defined(MA_APPLE_TV) && !defined(MA_APPLE_WATCH)
  29231. options |= AVAudioSessionCategoryOptionDefaultToSpeaker;
  29232. #endif
  29233. if ([pAudioSession setCategory: AVAudioSessionCategoryPlayAndRecord withOptions:options error:nil]) {
  29234. /* Using PlayAndRecord */
  29235. } else if ([pAudioSession setCategory: AVAudioSessionCategoryPlayback withOptions:options error:nil]) {
  29236. /* Using Playback */
  29237. } else if ([pAudioSession setCategory: AVAudioSessionCategoryRecord withOptions:options error:nil]) {
  29238. /* Using Record */
  29239. } else {
  29240. /* Leave as default? */
  29241. }
  29242. } else {
  29243. if (pConfig->coreaudio.sessionCategory != ma_ios_session_category_none) {
  29244. #if defined(__IPHONE_12_0)
  29245. if (![pAudioSession setCategory: ma_to_AVAudioSessionCategory(pConfig->coreaudio.sessionCategory) withOptions:options error:nil]) {
  29246. return MA_INVALID_OPERATION; /* Failed to set session category. */
  29247. }
  29248. #else
  29249. /* Ignore the session category on version 11 and older, but post a warning. */
  29250. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Session category only supported in iOS 12 and newer.");
  29251. #endif
  29252. }
  29253. }
  29254. if (!pConfig->coreaudio.noAudioSessionActivate) {
  29255. if (![pAudioSession setActive:true error:nil]) {
  29256. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "Failed to activate audio session.");
  29257. return MA_FAILED_TO_INIT_BACKEND;
  29258. }
  29259. }
  29260. }
  29261. #endif
  29262. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  29263. pContext->coreaudio.hCoreFoundation = ma_dlopen(pContext, "CoreFoundation.framework/CoreFoundation");
  29264. if (pContext->coreaudio.hCoreFoundation == NULL) {
  29265. return MA_API_NOT_FOUND;
  29266. }
  29267. pContext->coreaudio.CFStringGetCString = ma_dlsym(pContext, pContext->coreaudio.hCoreFoundation, "CFStringGetCString");
  29268. pContext->coreaudio.CFRelease = ma_dlsym(pContext, pContext->coreaudio.hCoreFoundation, "CFRelease");
  29269. pContext->coreaudio.hCoreAudio = ma_dlopen(pContext, "CoreAudio.framework/CoreAudio");
  29270. if (pContext->coreaudio.hCoreAudio == NULL) {
  29271. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  29272. return MA_API_NOT_FOUND;
  29273. }
  29274. pContext->coreaudio.AudioObjectGetPropertyData = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyData");
  29275. pContext->coreaudio.AudioObjectGetPropertyDataSize = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyDataSize");
  29276. pContext->coreaudio.AudioObjectSetPropertyData = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectSetPropertyData");
  29277. pContext->coreaudio.AudioObjectAddPropertyListener = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectAddPropertyListener");
  29278. pContext->coreaudio.AudioObjectRemovePropertyListener = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectRemovePropertyListener");
  29279. /*
  29280. It looks like Apple has moved some APIs from AudioUnit into AudioToolbox on more recent versions of macOS. They are still
  29281. defined in AudioUnit, but just in case they decide to remove them from there entirely I'm going to implement a fallback.
  29282. The way it'll work is that it'll first try AudioUnit, and if the required symbols are not present there we'll fall back to
  29283. AudioToolbox.
  29284. */
  29285. pContext->coreaudio.hAudioUnit = ma_dlopen(pContext, "AudioUnit.framework/AudioUnit");
  29286. if (pContext->coreaudio.hAudioUnit == NULL) {
  29287. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  29288. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  29289. return MA_API_NOT_FOUND;
  29290. }
  29291. if (ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentFindNext") == NULL) {
  29292. /* Couldn't find the required symbols in AudioUnit, so fall back to AudioToolbox. */
  29293. ma_dlclose(pContext, pContext->coreaudio.hAudioUnit);
  29294. pContext->coreaudio.hAudioUnit = ma_dlopen(pContext, "AudioToolbox.framework/AudioToolbox");
  29295. if (pContext->coreaudio.hAudioUnit == NULL) {
  29296. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  29297. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  29298. return MA_API_NOT_FOUND;
  29299. }
  29300. }
  29301. pContext->coreaudio.AudioComponentFindNext = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentFindNext");
  29302. pContext->coreaudio.AudioComponentInstanceDispose = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentInstanceDispose");
  29303. pContext->coreaudio.AudioComponentInstanceNew = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentInstanceNew");
  29304. pContext->coreaudio.AudioOutputUnitStart = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioOutputUnitStart");
  29305. pContext->coreaudio.AudioOutputUnitStop = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioOutputUnitStop");
  29306. pContext->coreaudio.AudioUnitAddPropertyListener = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitAddPropertyListener");
  29307. pContext->coreaudio.AudioUnitGetPropertyInfo = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitGetPropertyInfo");
  29308. pContext->coreaudio.AudioUnitGetProperty = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitGetProperty");
  29309. pContext->coreaudio.AudioUnitSetProperty = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitSetProperty");
  29310. pContext->coreaudio.AudioUnitInitialize = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitInitialize");
  29311. pContext->coreaudio.AudioUnitRender = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitRender");
  29312. #else
  29313. pContext->coreaudio.CFStringGetCString = (ma_proc)CFStringGetCString;
  29314. pContext->coreaudio.CFRelease = (ma_proc)CFRelease;
  29315. #if defined(MA_APPLE_DESKTOP)
  29316. pContext->coreaudio.AudioObjectGetPropertyData = (ma_proc)AudioObjectGetPropertyData;
  29317. pContext->coreaudio.AudioObjectGetPropertyDataSize = (ma_proc)AudioObjectGetPropertyDataSize;
  29318. pContext->coreaudio.AudioObjectSetPropertyData = (ma_proc)AudioObjectSetPropertyData;
  29319. pContext->coreaudio.AudioObjectAddPropertyListener = (ma_proc)AudioObjectAddPropertyListener;
  29320. pContext->coreaudio.AudioObjectRemovePropertyListener = (ma_proc)AudioObjectRemovePropertyListener;
  29321. #endif
  29322. pContext->coreaudio.AudioComponentFindNext = (ma_proc)AudioComponentFindNext;
  29323. pContext->coreaudio.AudioComponentInstanceDispose = (ma_proc)AudioComponentInstanceDispose;
  29324. pContext->coreaudio.AudioComponentInstanceNew = (ma_proc)AudioComponentInstanceNew;
  29325. pContext->coreaudio.AudioOutputUnitStart = (ma_proc)AudioOutputUnitStart;
  29326. pContext->coreaudio.AudioOutputUnitStop = (ma_proc)AudioOutputUnitStop;
  29327. pContext->coreaudio.AudioUnitAddPropertyListener = (ma_proc)AudioUnitAddPropertyListener;
  29328. pContext->coreaudio.AudioUnitGetPropertyInfo = (ma_proc)AudioUnitGetPropertyInfo;
  29329. pContext->coreaudio.AudioUnitGetProperty = (ma_proc)AudioUnitGetProperty;
  29330. pContext->coreaudio.AudioUnitSetProperty = (ma_proc)AudioUnitSetProperty;
  29331. pContext->coreaudio.AudioUnitInitialize = (ma_proc)AudioUnitInitialize;
  29332. pContext->coreaudio.AudioUnitRender = (ma_proc)AudioUnitRender;
  29333. #endif
  29334. /* Audio component. */
  29335. {
  29336. AudioComponentDescription desc;
  29337. desc.componentType = kAudioUnitType_Output;
  29338. #if defined(MA_APPLE_DESKTOP)
  29339. desc.componentSubType = kAudioUnitSubType_HALOutput;
  29340. #else
  29341. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  29342. #endif
  29343. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  29344. desc.componentFlags = 0;
  29345. desc.componentFlagsMask = 0;
  29346. pContext->coreaudio.component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc);
  29347. if (pContext->coreaudio.component == NULL) {
  29348. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  29349. ma_dlclose(pContext, pContext->coreaudio.hAudioUnit);
  29350. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  29351. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  29352. #endif
  29353. return MA_FAILED_TO_INIT_BACKEND;
  29354. }
  29355. }
  29356. #if !defined(MA_APPLE_MOBILE)
  29357. result = ma_context__init_device_tracking__coreaudio(pContext);
  29358. if (result != MA_SUCCESS) {
  29359. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  29360. ma_dlclose(pContext, pContext->coreaudio.hAudioUnit);
  29361. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  29362. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  29363. #endif
  29364. return result;
  29365. }
  29366. #endif
  29367. pContext->coreaudio.noAudioSessionDeactivate = pConfig->coreaudio.noAudioSessionDeactivate;
  29368. pCallbacks->onContextInit = ma_context_init__coreaudio;
  29369. pCallbacks->onContextUninit = ma_context_uninit__coreaudio;
  29370. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__coreaudio;
  29371. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__coreaudio;
  29372. pCallbacks->onDeviceInit = ma_device_init__coreaudio;
  29373. pCallbacks->onDeviceUninit = ma_device_uninit__coreaudio;
  29374. pCallbacks->onDeviceStart = ma_device_start__coreaudio;
  29375. pCallbacks->onDeviceStop = ma_device_stop__coreaudio;
  29376. pCallbacks->onDeviceRead = NULL;
  29377. pCallbacks->onDeviceWrite = NULL;
  29378. pCallbacks->onDeviceDataLoop = NULL;
  29379. return MA_SUCCESS;
  29380. }
  29381. #endif /* Core Audio */
  29382. /******************************************************************************
  29383. sndio Backend
  29384. ******************************************************************************/
  29385. #ifdef MA_HAS_SNDIO
  29386. #include <fcntl.h>
  29387. /*
  29388. Only supporting OpenBSD. This did not work very well at all on FreeBSD when I tried it. Not sure if this is due
  29389. to miniaudio's implementation or if it's some kind of system configuration issue, but basically the default device
  29390. just doesn't emit any sound, or at times you'll hear tiny pieces. I will consider enabling this when there's
  29391. demand for it or if I can get it tested and debugged more thoroughly.
  29392. */
  29393. #if 0
  29394. #if defined(__NetBSD__) || defined(__OpenBSD__)
  29395. #include <sys/audioio.h>
  29396. #endif
  29397. #if defined(__FreeBSD__) || defined(__DragonFly__)
  29398. #include <sys/soundcard.h>
  29399. #endif
  29400. #endif
  29401. #define MA_SIO_DEVANY "default"
  29402. #define MA_SIO_PLAY 1
  29403. #define MA_SIO_REC 2
  29404. #define MA_SIO_NENC 8
  29405. #define MA_SIO_NCHAN 8
  29406. #define MA_SIO_NRATE 16
  29407. #define MA_SIO_NCONF 4
  29408. struct ma_sio_hdl; /* <-- Opaque */
  29409. struct ma_sio_par
  29410. {
  29411. unsigned int bits;
  29412. unsigned int bps;
  29413. unsigned int sig;
  29414. unsigned int le;
  29415. unsigned int msb;
  29416. unsigned int rchan;
  29417. unsigned int pchan;
  29418. unsigned int rate;
  29419. unsigned int bufsz;
  29420. unsigned int xrun;
  29421. unsigned int round;
  29422. unsigned int appbufsz;
  29423. int __pad[3];
  29424. unsigned int __magic;
  29425. };
  29426. struct ma_sio_enc
  29427. {
  29428. unsigned int bits;
  29429. unsigned int bps;
  29430. unsigned int sig;
  29431. unsigned int le;
  29432. unsigned int msb;
  29433. };
  29434. struct ma_sio_conf
  29435. {
  29436. unsigned int enc;
  29437. unsigned int rchan;
  29438. unsigned int pchan;
  29439. unsigned int rate;
  29440. };
  29441. struct ma_sio_cap
  29442. {
  29443. struct ma_sio_enc enc[MA_SIO_NENC];
  29444. unsigned int rchan[MA_SIO_NCHAN];
  29445. unsigned int pchan[MA_SIO_NCHAN];
  29446. unsigned int rate[MA_SIO_NRATE];
  29447. int __pad[7];
  29448. unsigned int nconf;
  29449. struct ma_sio_conf confs[MA_SIO_NCONF];
  29450. };
  29451. typedef struct ma_sio_hdl* (* ma_sio_open_proc) (const char*, unsigned int, int);
  29452. typedef void (* ma_sio_close_proc) (struct ma_sio_hdl*);
  29453. typedef int (* ma_sio_setpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*);
  29454. typedef int (* ma_sio_getpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*);
  29455. typedef int (* ma_sio_getcap_proc) (struct ma_sio_hdl*, struct ma_sio_cap*);
  29456. typedef size_t (* ma_sio_write_proc) (struct ma_sio_hdl*, const void*, size_t);
  29457. typedef size_t (* ma_sio_read_proc) (struct ma_sio_hdl*, void*, size_t);
  29458. typedef int (* ma_sio_start_proc) (struct ma_sio_hdl*);
  29459. typedef int (* ma_sio_stop_proc) (struct ma_sio_hdl*);
  29460. typedef int (* ma_sio_initpar_proc)(struct ma_sio_par*);
  29461. static ma_uint32 ma_get_standard_sample_rate_priority_index__sndio(ma_uint32 sampleRate) /* Lower = higher priority */
  29462. {
  29463. ma_uint32 i;
  29464. for (i = 0; i < ma_countof(g_maStandardSampleRatePriorities); ++i) {
  29465. if (g_maStandardSampleRatePriorities[i] == sampleRate) {
  29466. return i;
  29467. }
  29468. }
  29469. return (ma_uint32)-1;
  29470. }
  29471. static ma_format ma_format_from_sio_enc__sndio(unsigned int bits, unsigned int bps, unsigned int sig, unsigned int le, unsigned int msb)
  29472. {
  29473. /* We only support native-endian right now. */
  29474. if ((ma_is_little_endian() && le == 0) || (ma_is_big_endian() && le == 1)) {
  29475. return ma_format_unknown;
  29476. }
  29477. if (bits == 8 && bps == 1 && sig == 0) {
  29478. return ma_format_u8;
  29479. }
  29480. if (bits == 16 && bps == 2 && sig == 1) {
  29481. return ma_format_s16;
  29482. }
  29483. if (bits == 24 && bps == 3 && sig == 1) {
  29484. return ma_format_s24;
  29485. }
  29486. if (bits == 24 && bps == 4 && sig == 1 && msb == 0) {
  29487. /*return ma_format_s24_32;*/
  29488. }
  29489. if (bits == 32 && bps == 4 && sig == 1) {
  29490. return ma_format_s32;
  29491. }
  29492. return ma_format_unknown;
  29493. }
  29494. static ma_format ma_find_best_format_from_sio_cap__sndio(struct ma_sio_cap* caps)
  29495. {
  29496. ma_format bestFormat;
  29497. unsigned int iConfig;
  29498. MA_ASSERT(caps != NULL);
  29499. bestFormat = ma_format_unknown;
  29500. for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) {
  29501. unsigned int iEncoding;
  29502. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  29503. unsigned int bits;
  29504. unsigned int bps;
  29505. unsigned int sig;
  29506. unsigned int le;
  29507. unsigned int msb;
  29508. ma_format format;
  29509. if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  29510. continue;
  29511. }
  29512. bits = caps->enc[iEncoding].bits;
  29513. bps = caps->enc[iEncoding].bps;
  29514. sig = caps->enc[iEncoding].sig;
  29515. le = caps->enc[iEncoding].le;
  29516. msb = caps->enc[iEncoding].msb;
  29517. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  29518. if (format == ma_format_unknown) {
  29519. continue; /* Format not supported. */
  29520. }
  29521. if (bestFormat == ma_format_unknown) {
  29522. bestFormat = format;
  29523. } else {
  29524. if (ma_get_format_priority_index(bestFormat) > ma_get_format_priority_index(format)) { /* <-- Lower = better. */
  29525. bestFormat = format;
  29526. }
  29527. }
  29528. }
  29529. }
  29530. return bestFormat;
  29531. }
  29532. static ma_uint32 ma_find_best_channels_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_device_type deviceType, ma_format requiredFormat)
  29533. {
  29534. ma_uint32 maxChannels;
  29535. unsigned int iConfig;
  29536. MA_ASSERT(caps != NULL);
  29537. MA_ASSERT(requiredFormat != ma_format_unknown);
  29538. /* Just pick whatever configuration has the most channels. */
  29539. maxChannels = 0;
  29540. for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) {
  29541. /* The encoding should be of requiredFormat. */
  29542. unsigned int iEncoding;
  29543. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  29544. unsigned int iChannel;
  29545. unsigned int bits;
  29546. unsigned int bps;
  29547. unsigned int sig;
  29548. unsigned int le;
  29549. unsigned int msb;
  29550. ma_format format;
  29551. if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  29552. continue;
  29553. }
  29554. bits = caps->enc[iEncoding].bits;
  29555. bps = caps->enc[iEncoding].bps;
  29556. sig = caps->enc[iEncoding].sig;
  29557. le = caps->enc[iEncoding].le;
  29558. msb = caps->enc[iEncoding].msb;
  29559. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  29560. if (format != requiredFormat) {
  29561. continue;
  29562. }
  29563. /* Getting here means the format is supported. Iterate over each channel count and grab the biggest one. */
  29564. for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) {
  29565. unsigned int chan = 0;
  29566. unsigned int channels;
  29567. if (deviceType == ma_device_type_playback) {
  29568. chan = caps->confs[iConfig].pchan;
  29569. } else {
  29570. chan = caps->confs[iConfig].rchan;
  29571. }
  29572. if ((chan & (1UL << iChannel)) == 0) {
  29573. continue;
  29574. }
  29575. if (deviceType == ma_device_type_playback) {
  29576. channels = caps->pchan[iChannel];
  29577. } else {
  29578. channels = caps->rchan[iChannel];
  29579. }
  29580. if (maxChannels < channels) {
  29581. maxChannels = channels;
  29582. }
  29583. }
  29584. }
  29585. }
  29586. return maxChannels;
  29587. }
  29588. static ma_uint32 ma_find_best_sample_rate_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_device_type deviceType, ma_format requiredFormat, ma_uint32 requiredChannels)
  29589. {
  29590. ma_uint32 firstSampleRate;
  29591. ma_uint32 bestSampleRate;
  29592. unsigned int iConfig;
  29593. MA_ASSERT(caps != NULL);
  29594. MA_ASSERT(requiredFormat != ma_format_unknown);
  29595. MA_ASSERT(requiredChannels > 0);
  29596. MA_ASSERT(requiredChannels <= MA_MAX_CHANNELS);
  29597. firstSampleRate = 0; /* <-- If the device does not support a standard rate we'll fall back to the first one that's found. */
  29598. bestSampleRate = 0;
  29599. for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) {
  29600. /* The encoding should be of requiredFormat. */
  29601. unsigned int iEncoding;
  29602. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  29603. unsigned int iChannel;
  29604. unsigned int bits;
  29605. unsigned int bps;
  29606. unsigned int sig;
  29607. unsigned int le;
  29608. unsigned int msb;
  29609. ma_format format;
  29610. if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  29611. continue;
  29612. }
  29613. bits = caps->enc[iEncoding].bits;
  29614. bps = caps->enc[iEncoding].bps;
  29615. sig = caps->enc[iEncoding].sig;
  29616. le = caps->enc[iEncoding].le;
  29617. msb = caps->enc[iEncoding].msb;
  29618. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  29619. if (format != requiredFormat) {
  29620. continue;
  29621. }
  29622. /* Getting here means the format is supported. Iterate over each channel count and grab the biggest one. */
  29623. for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) {
  29624. unsigned int chan = 0;
  29625. unsigned int channels;
  29626. unsigned int iRate;
  29627. if (deviceType == ma_device_type_playback) {
  29628. chan = caps->confs[iConfig].pchan;
  29629. } else {
  29630. chan = caps->confs[iConfig].rchan;
  29631. }
  29632. if ((chan & (1UL << iChannel)) == 0) {
  29633. continue;
  29634. }
  29635. if (deviceType == ma_device_type_playback) {
  29636. channels = caps->pchan[iChannel];
  29637. } else {
  29638. channels = caps->rchan[iChannel];
  29639. }
  29640. if (channels != requiredChannels) {
  29641. continue;
  29642. }
  29643. /* Getting here means we have found a compatible encoding/channel pair. */
  29644. for (iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) {
  29645. ma_uint32 rate = (ma_uint32)caps->rate[iRate];
  29646. ma_uint32 ratePriority;
  29647. if (firstSampleRate == 0) {
  29648. firstSampleRate = rate;
  29649. }
  29650. /* Disregard this rate if it's not a standard one. */
  29651. ratePriority = ma_get_standard_sample_rate_priority_index__sndio(rate);
  29652. if (ratePriority == (ma_uint32)-1) {
  29653. continue;
  29654. }
  29655. if (ma_get_standard_sample_rate_priority_index__sndio(bestSampleRate) > ratePriority) { /* Lower = better. */
  29656. bestSampleRate = rate;
  29657. }
  29658. }
  29659. }
  29660. }
  29661. }
  29662. /* If a standard sample rate was not found just fall back to the first one that was iterated. */
  29663. if (bestSampleRate == 0) {
  29664. bestSampleRate = firstSampleRate;
  29665. }
  29666. return bestSampleRate;
  29667. }
  29668. static ma_result ma_context_enumerate_devices__sndio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  29669. {
  29670. ma_bool32 isTerminating = MA_FALSE;
  29671. struct ma_sio_hdl* handle;
  29672. MA_ASSERT(pContext != NULL);
  29673. MA_ASSERT(callback != NULL);
  29674. /* sndio doesn't seem to have a good device enumeration API, so I'm therefore only enumerating over default devices for now. */
  29675. /* Playback. */
  29676. if (!isTerminating) {
  29677. handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_PLAY, 0);
  29678. if (handle != NULL) {
  29679. /* Supports playback. */
  29680. ma_device_info deviceInfo;
  29681. MA_ZERO_OBJECT(&deviceInfo);
  29682. ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), MA_SIO_DEVANY);
  29683. ma_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME);
  29684. isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  29685. ((ma_sio_close_proc)pContext->sndio.sio_close)(handle);
  29686. }
  29687. }
  29688. /* Capture. */
  29689. if (!isTerminating) {
  29690. handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_REC, 0);
  29691. if (handle != NULL) {
  29692. /* Supports capture. */
  29693. ma_device_info deviceInfo;
  29694. MA_ZERO_OBJECT(&deviceInfo);
  29695. ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), "default");
  29696. ma_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME);
  29697. isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  29698. ((ma_sio_close_proc)pContext->sndio.sio_close)(handle);
  29699. }
  29700. }
  29701. return MA_SUCCESS;
  29702. }
  29703. static ma_result ma_context_get_device_info__sndio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  29704. {
  29705. char devid[256];
  29706. struct ma_sio_hdl* handle;
  29707. struct ma_sio_cap caps;
  29708. unsigned int iConfig;
  29709. MA_ASSERT(pContext != NULL);
  29710. /* We need to open the device before we can get information about it. */
  29711. if (pDeviceID == NULL) {
  29712. ma_strcpy_s(devid, sizeof(devid), MA_SIO_DEVANY);
  29713. ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (deviceType == ma_device_type_playback) ? MA_DEFAULT_PLAYBACK_DEVICE_NAME : MA_DEFAULT_CAPTURE_DEVICE_NAME);
  29714. } else {
  29715. ma_strcpy_s(devid, sizeof(devid), pDeviceID->sndio);
  29716. ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), devid);
  29717. }
  29718. handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(devid, (deviceType == ma_device_type_playback) ? MA_SIO_PLAY : MA_SIO_REC, 0);
  29719. if (handle == NULL) {
  29720. return MA_NO_DEVICE;
  29721. }
  29722. if (((ma_sio_getcap_proc)pContext->sndio.sio_getcap)(handle, &caps) == 0) {
  29723. return MA_ERROR;
  29724. }
  29725. pDeviceInfo->nativeDataFormatCount = 0;
  29726. for (iConfig = 0; iConfig < caps.nconf; iConfig += 1) {
  29727. /*
  29728. The main thing we care about is that the encoding is supported by miniaudio. If it is, we want to give
  29729. preference to some formats over others.
  29730. */
  29731. unsigned int iEncoding;
  29732. unsigned int iChannel;
  29733. unsigned int iRate;
  29734. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  29735. unsigned int bits;
  29736. unsigned int bps;
  29737. unsigned int sig;
  29738. unsigned int le;
  29739. unsigned int msb;
  29740. ma_format format;
  29741. if ((caps.confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  29742. continue;
  29743. }
  29744. bits = caps.enc[iEncoding].bits;
  29745. bps = caps.enc[iEncoding].bps;
  29746. sig = caps.enc[iEncoding].sig;
  29747. le = caps.enc[iEncoding].le;
  29748. msb = caps.enc[iEncoding].msb;
  29749. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  29750. if (format == ma_format_unknown) {
  29751. continue; /* Format not supported. */
  29752. }
  29753. /* Channels. */
  29754. for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) {
  29755. unsigned int chan = 0;
  29756. unsigned int channels;
  29757. if (deviceType == ma_device_type_playback) {
  29758. chan = caps.confs[iConfig].pchan;
  29759. } else {
  29760. chan = caps.confs[iConfig].rchan;
  29761. }
  29762. if ((chan & (1UL << iChannel)) == 0) {
  29763. continue;
  29764. }
  29765. if (deviceType == ma_device_type_playback) {
  29766. channels = caps.pchan[iChannel];
  29767. } else {
  29768. channels = caps.rchan[iChannel];
  29769. }
  29770. /* Sample Rates. */
  29771. for (iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) {
  29772. if ((caps.confs[iConfig].rate & (1UL << iRate)) != 0) {
  29773. ma_device_info_add_native_data_format(pDeviceInfo, format, channels, caps.rate[iRate], 0);
  29774. }
  29775. }
  29776. }
  29777. }
  29778. }
  29779. ((ma_sio_close_proc)pContext->sndio.sio_close)(handle);
  29780. return MA_SUCCESS;
  29781. }
  29782. static ma_result ma_device_uninit__sndio(ma_device* pDevice)
  29783. {
  29784. MA_ASSERT(pDevice != NULL);
  29785. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29786. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
  29787. }
  29788. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29789. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback);
  29790. }
  29791. return MA_SUCCESS;
  29792. }
  29793. static ma_result ma_device_init_handle__sndio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  29794. {
  29795. const char* pDeviceName;
  29796. ma_ptr handle;
  29797. int openFlags = 0;
  29798. struct ma_sio_cap caps;
  29799. struct ma_sio_par par;
  29800. const ma_device_id* pDeviceID;
  29801. ma_format format;
  29802. ma_uint32 channels;
  29803. ma_uint32 sampleRate;
  29804. ma_format internalFormat;
  29805. ma_uint32 internalChannels;
  29806. ma_uint32 internalSampleRate;
  29807. ma_uint32 internalPeriodSizeInFrames;
  29808. ma_uint32 internalPeriods;
  29809. MA_ASSERT(pConfig != NULL);
  29810. MA_ASSERT(deviceType != ma_device_type_duplex);
  29811. MA_ASSERT(pDevice != NULL);
  29812. if (deviceType == ma_device_type_capture) {
  29813. openFlags = MA_SIO_REC;
  29814. } else {
  29815. openFlags = MA_SIO_PLAY;
  29816. }
  29817. pDeviceID = pDescriptor->pDeviceID;
  29818. format = pDescriptor->format;
  29819. channels = pDescriptor->channels;
  29820. sampleRate = pDescriptor->sampleRate;
  29821. pDeviceName = MA_SIO_DEVANY;
  29822. if (pDeviceID != NULL) {
  29823. pDeviceName = pDeviceID->sndio;
  29824. }
  29825. handle = (ma_ptr)((ma_sio_open_proc)pDevice->pContext->sndio.sio_open)(pDeviceName, openFlags, 0);
  29826. if (handle == NULL) {
  29827. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to open device.");
  29828. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  29829. }
  29830. /* We need to retrieve the device caps to determine the most appropriate format to use. */
  29831. if (((ma_sio_getcap_proc)pDevice->pContext->sndio.sio_getcap)((struct ma_sio_hdl*)handle, &caps) == 0) {
  29832. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
  29833. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve device caps.");
  29834. return MA_ERROR;
  29835. }
  29836. /*
  29837. Note: sndio reports a huge range of available channels. This is inconvenient for us because there's no real
  29838. way, as far as I can tell, to get the _actual_ channel count of the device. I'm therefore restricting this
  29839. to the requested channels, regardless of whether or not the default channel count is requested.
  29840. For hardware devices, I'm suspecting only a single channel count will be reported and we can safely use the
  29841. value returned by ma_find_best_channels_from_sio_cap__sndio().
  29842. */
  29843. if (deviceType == ma_device_type_capture) {
  29844. if (format == ma_format_unknown) {
  29845. format = ma_find_best_format_from_sio_cap__sndio(&caps);
  29846. }
  29847. if (channels == 0) {
  29848. if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) {
  29849. channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format);
  29850. } else {
  29851. channels = MA_DEFAULT_CHANNELS;
  29852. }
  29853. }
  29854. } else {
  29855. if (format == ma_format_unknown) {
  29856. format = ma_find_best_format_from_sio_cap__sndio(&caps);
  29857. }
  29858. if (channels == 0) {
  29859. if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) {
  29860. channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format);
  29861. } else {
  29862. channels = MA_DEFAULT_CHANNELS;
  29863. }
  29864. }
  29865. }
  29866. if (sampleRate == 0) {
  29867. sampleRate = ma_find_best_sample_rate_from_sio_cap__sndio(&caps, pConfig->deviceType, format, channels);
  29868. }
  29869. ((ma_sio_initpar_proc)pDevice->pContext->sndio.sio_initpar)(&par);
  29870. par.msb = 0;
  29871. par.le = ma_is_little_endian();
  29872. switch (format) {
  29873. case ma_format_u8:
  29874. {
  29875. par.bits = 8;
  29876. par.bps = 1;
  29877. par.sig = 0;
  29878. } break;
  29879. case ma_format_s24:
  29880. {
  29881. par.bits = 24;
  29882. par.bps = 3;
  29883. par.sig = 1;
  29884. } break;
  29885. case ma_format_s32:
  29886. {
  29887. par.bits = 32;
  29888. par.bps = 4;
  29889. par.sig = 1;
  29890. } break;
  29891. case ma_format_s16:
  29892. case ma_format_f32:
  29893. case ma_format_unknown:
  29894. default:
  29895. {
  29896. par.bits = 16;
  29897. par.bps = 2;
  29898. par.sig = 1;
  29899. } break;
  29900. }
  29901. if (deviceType == ma_device_type_capture) {
  29902. par.rchan = channels;
  29903. } else {
  29904. par.pchan = channels;
  29905. }
  29906. par.rate = sampleRate;
  29907. internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, par.rate, pConfig->performanceProfile);
  29908. par.round = internalPeriodSizeInFrames;
  29909. par.appbufsz = par.round * pDescriptor->periodCount;
  29910. if (((ma_sio_setpar_proc)pDevice->pContext->sndio.sio_setpar)((struct ma_sio_hdl*)handle, &par) == 0) {
  29911. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
  29912. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to set buffer size.");
  29913. return MA_ERROR;
  29914. }
  29915. if (((ma_sio_getpar_proc)pDevice->pContext->sndio.sio_getpar)((struct ma_sio_hdl*)handle, &par) == 0) {
  29916. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
  29917. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve buffer size.");
  29918. return MA_ERROR;
  29919. }
  29920. internalFormat = ma_format_from_sio_enc__sndio(par.bits, par.bps, par.sig, par.le, par.msb);
  29921. internalChannels = (deviceType == ma_device_type_capture) ? par.rchan : par.pchan;
  29922. internalSampleRate = par.rate;
  29923. internalPeriods = par.appbufsz / par.round;
  29924. internalPeriodSizeInFrames = par.round;
  29925. if (deviceType == ma_device_type_capture) {
  29926. pDevice->sndio.handleCapture = handle;
  29927. } else {
  29928. pDevice->sndio.handlePlayback = handle;
  29929. }
  29930. pDescriptor->format = internalFormat;
  29931. pDescriptor->channels = internalChannels;
  29932. pDescriptor->sampleRate = internalSampleRate;
  29933. ma_channel_map_init_standard(ma_standard_channel_map_sndio, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), internalChannels);
  29934. pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames;
  29935. pDescriptor->periodCount = internalPeriods;
  29936. return MA_SUCCESS;
  29937. }
  29938. static ma_result ma_device_init__sndio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  29939. {
  29940. MA_ASSERT(pDevice != NULL);
  29941. MA_ZERO_OBJECT(&pDevice->sndio);
  29942. if (pConfig->deviceType == ma_device_type_loopback) {
  29943. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  29944. }
  29945. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  29946. ma_result result = ma_device_init_handle__sndio(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  29947. if (result != MA_SUCCESS) {
  29948. return result;
  29949. }
  29950. }
  29951. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  29952. ma_result result = ma_device_init_handle__sndio(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  29953. if (result != MA_SUCCESS) {
  29954. return result;
  29955. }
  29956. }
  29957. return MA_SUCCESS;
  29958. }
  29959. static ma_result ma_device_start__sndio(ma_device* pDevice)
  29960. {
  29961. MA_ASSERT(pDevice != NULL);
  29962. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29963. ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
  29964. }
  29965. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29966. ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback); /* <-- Doesn't actually playback until data is written. */
  29967. }
  29968. return MA_SUCCESS;
  29969. }
  29970. static ma_result ma_device_stop__sndio(ma_device* pDevice)
  29971. {
  29972. MA_ASSERT(pDevice != NULL);
  29973. /*
  29974. From the documentation:
  29975. The sio_stop() function puts the audio subsystem in the same state as before sio_start() is called. It stops recording, drains the play buffer and then
  29976. stops playback. If samples to play are queued but playback hasn't started yet then playback is forced immediately; playback will actually stop once the
  29977. buffer is drained. In no case are samples in the play buffer discarded.
  29978. Therefore, sio_stop() performs all of the necessary draining for us.
  29979. */
  29980. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29981. ((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
  29982. }
  29983. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29984. ((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback);
  29985. }
  29986. return MA_SUCCESS;
  29987. }
  29988. static ma_result ma_device_write__sndio(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  29989. {
  29990. int result;
  29991. if (pFramesWritten != NULL) {
  29992. *pFramesWritten = 0;
  29993. }
  29994. result = ((ma_sio_write_proc)pDevice->pContext->sndio.sio_write)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  29995. if (result == 0) {
  29996. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to send data from the client to the device.");
  29997. return MA_IO_ERROR;
  29998. }
  29999. if (pFramesWritten != NULL) {
  30000. *pFramesWritten = frameCount;
  30001. }
  30002. return MA_SUCCESS;
  30003. }
  30004. static ma_result ma_device_read__sndio(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  30005. {
  30006. int result;
  30007. if (pFramesRead != NULL) {
  30008. *pFramesRead = 0;
  30009. }
  30010. result = ((ma_sio_read_proc)pDevice->pContext->sndio.sio_read)((struct ma_sio_hdl*)pDevice->sndio.handleCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  30011. if (result == 0) {
  30012. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to read data from the device to be sent to the device.");
  30013. return MA_IO_ERROR;
  30014. }
  30015. if (pFramesRead != NULL) {
  30016. *pFramesRead = frameCount;
  30017. }
  30018. return MA_SUCCESS;
  30019. }
  30020. static ma_result ma_context_uninit__sndio(ma_context* pContext)
  30021. {
  30022. MA_ASSERT(pContext != NULL);
  30023. MA_ASSERT(pContext->backend == ma_backend_sndio);
  30024. (void)pContext;
  30025. return MA_SUCCESS;
  30026. }
  30027. static ma_result ma_context_init__sndio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  30028. {
  30029. #ifndef MA_NO_RUNTIME_LINKING
  30030. const char* libsndioNames[] = {
  30031. "libsndio.so"
  30032. };
  30033. size_t i;
  30034. for (i = 0; i < ma_countof(libsndioNames); ++i) {
  30035. pContext->sndio.sndioSO = ma_dlopen(pContext, libsndioNames[i]);
  30036. if (pContext->sndio.sndioSO != NULL) {
  30037. break;
  30038. }
  30039. }
  30040. if (pContext->sndio.sndioSO == NULL) {
  30041. return MA_NO_BACKEND;
  30042. }
  30043. pContext->sndio.sio_open = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_open");
  30044. pContext->sndio.sio_close = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_close");
  30045. pContext->sndio.sio_setpar = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_setpar");
  30046. pContext->sndio.sio_getpar = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_getpar");
  30047. pContext->sndio.sio_getcap = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_getcap");
  30048. pContext->sndio.sio_write = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_write");
  30049. pContext->sndio.sio_read = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_read");
  30050. pContext->sndio.sio_start = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_start");
  30051. pContext->sndio.sio_stop = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_stop");
  30052. pContext->sndio.sio_initpar = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_initpar");
  30053. #else
  30054. pContext->sndio.sio_open = sio_open;
  30055. pContext->sndio.sio_close = sio_close;
  30056. pContext->sndio.sio_setpar = sio_setpar;
  30057. pContext->sndio.sio_getpar = sio_getpar;
  30058. pContext->sndio.sio_getcap = sio_getcap;
  30059. pContext->sndio.sio_write = sio_write;
  30060. pContext->sndio.sio_read = sio_read;
  30061. pContext->sndio.sio_start = sio_start;
  30062. pContext->sndio.sio_stop = sio_stop;
  30063. pContext->sndio.sio_initpar = sio_initpar;
  30064. #endif
  30065. pCallbacks->onContextInit = ma_context_init__sndio;
  30066. pCallbacks->onContextUninit = ma_context_uninit__sndio;
  30067. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__sndio;
  30068. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__sndio;
  30069. pCallbacks->onDeviceInit = ma_device_init__sndio;
  30070. pCallbacks->onDeviceUninit = ma_device_uninit__sndio;
  30071. pCallbacks->onDeviceStart = ma_device_start__sndio;
  30072. pCallbacks->onDeviceStop = ma_device_stop__sndio;
  30073. pCallbacks->onDeviceRead = ma_device_read__sndio;
  30074. pCallbacks->onDeviceWrite = ma_device_write__sndio;
  30075. pCallbacks->onDeviceDataLoop = NULL;
  30076. (void)pConfig;
  30077. return MA_SUCCESS;
  30078. }
  30079. #endif /* sndio */
  30080. /******************************************************************************
  30081. audio(4) Backend
  30082. ******************************************************************************/
  30083. #ifdef MA_HAS_AUDIO4
  30084. #include <fcntl.h>
  30085. #include <poll.h>
  30086. #include <errno.h>
  30087. #include <sys/stat.h>
  30088. #include <sys/types.h>
  30089. #include <sys/ioctl.h>
  30090. #include <sys/audioio.h>
  30091. #if defined(__OpenBSD__)
  30092. #include <sys/param.h>
  30093. #if defined(OpenBSD) && OpenBSD >= 201709
  30094. #define MA_AUDIO4_USE_NEW_API
  30095. #endif
  30096. #endif
  30097. static void ma_construct_device_id__audio4(char* id, size_t idSize, const char* base, int deviceIndex)
  30098. {
  30099. size_t baseLen;
  30100. MA_ASSERT(id != NULL);
  30101. MA_ASSERT(idSize > 0);
  30102. MA_ASSERT(deviceIndex >= 0);
  30103. baseLen = strlen(base);
  30104. MA_ASSERT(idSize > baseLen);
  30105. ma_strcpy_s(id, idSize, base);
  30106. ma_itoa_s(deviceIndex, id+baseLen, idSize-baseLen, 10);
  30107. }
  30108. static ma_result ma_extract_device_index_from_id__audio4(const char* id, const char* base, int* pIndexOut)
  30109. {
  30110. size_t idLen;
  30111. size_t baseLen;
  30112. const char* deviceIndexStr;
  30113. MA_ASSERT(id != NULL);
  30114. MA_ASSERT(base != NULL);
  30115. MA_ASSERT(pIndexOut != NULL);
  30116. idLen = strlen(id);
  30117. baseLen = strlen(base);
  30118. if (idLen <= baseLen) {
  30119. return MA_ERROR; /* Doesn't look like the id starts with the base. */
  30120. }
  30121. if (strncmp(id, base, baseLen) != 0) {
  30122. return MA_ERROR; /* ID does not begin with base. */
  30123. }
  30124. deviceIndexStr = id + baseLen;
  30125. if (deviceIndexStr[0] == '\0') {
  30126. return MA_ERROR; /* No index specified in the ID. */
  30127. }
  30128. if (pIndexOut) {
  30129. *pIndexOut = atoi(deviceIndexStr);
  30130. }
  30131. return MA_SUCCESS;
  30132. }
  30133. #if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */
  30134. static ma_format ma_format_from_encoding__audio4(unsigned int encoding, unsigned int precision)
  30135. {
  30136. if (precision == 8 && (encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR_LE || encoding == AUDIO_ENCODING_ULINEAR_BE)) {
  30137. return ma_format_u8;
  30138. } else {
  30139. if (ma_is_little_endian() && encoding == AUDIO_ENCODING_SLINEAR_LE) {
  30140. if (precision == 16) {
  30141. return ma_format_s16;
  30142. } else if (precision == 24) {
  30143. return ma_format_s24;
  30144. } else if (precision == 32) {
  30145. return ma_format_s32;
  30146. }
  30147. } else if (ma_is_big_endian() && encoding == AUDIO_ENCODING_SLINEAR_BE) {
  30148. if (precision == 16) {
  30149. return ma_format_s16;
  30150. } else if (precision == 24) {
  30151. return ma_format_s24;
  30152. } else if (precision == 32) {
  30153. return ma_format_s32;
  30154. }
  30155. }
  30156. }
  30157. return ma_format_unknown; /* Encoding not supported. */
  30158. }
  30159. static void ma_encoding_from_format__audio4(ma_format format, unsigned int* pEncoding, unsigned int* pPrecision)
  30160. {
  30161. MA_ASSERT(pEncoding != NULL);
  30162. MA_ASSERT(pPrecision != NULL);
  30163. switch (format)
  30164. {
  30165. case ma_format_u8:
  30166. {
  30167. *pEncoding = AUDIO_ENCODING_ULINEAR;
  30168. *pPrecision = 8;
  30169. } break;
  30170. case ma_format_s24:
  30171. {
  30172. *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE;
  30173. *pPrecision = 24;
  30174. } break;
  30175. case ma_format_s32:
  30176. {
  30177. *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE;
  30178. *pPrecision = 32;
  30179. } break;
  30180. case ma_format_s16:
  30181. case ma_format_f32:
  30182. case ma_format_unknown:
  30183. default:
  30184. {
  30185. *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE;
  30186. *pPrecision = 16;
  30187. } break;
  30188. }
  30189. }
  30190. static ma_format ma_format_from_prinfo__audio4(struct audio_prinfo* prinfo)
  30191. {
  30192. return ma_format_from_encoding__audio4(prinfo->encoding, prinfo->precision);
  30193. }
  30194. static ma_format ma_best_format_from_fd__audio4(int fd, ma_format preferredFormat)
  30195. {
  30196. audio_encoding_t encoding;
  30197. ma_uint32 iFormat;
  30198. int counter = 0;
  30199. /* First check to see if the preferred format is supported. */
  30200. if (preferredFormat != ma_format_unknown) {
  30201. counter = 0;
  30202. for (;;) {
  30203. MA_ZERO_OBJECT(&encoding);
  30204. encoding.index = counter;
  30205. if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) {
  30206. break;
  30207. }
  30208. if (preferredFormat == ma_format_from_encoding__audio4(encoding.encoding, encoding.precision)) {
  30209. return preferredFormat; /* Found the preferred format. */
  30210. }
  30211. /* Getting here means this encoding does not match our preferred format so we need to more on to the next encoding. */
  30212. counter += 1;
  30213. }
  30214. }
  30215. /* Getting here means our preferred format is not supported, so fall back to our standard priorities. */
  30216. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); iFormat += 1) {
  30217. ma_format format = g_maFormatPriorities[iFormat];
  30218. counter = 0;
  30219. for (;;) {
  30220. MA_ZERO_OBJECT(&encoding);
  30221. encoding.index = counter;
  30222. if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) {
  30223. break;
  30224. }
  30225. if (format == ma_format_from_encoding__audio4(encoding.encoding, encoding.precision)) {
  30226. return format; /* Found a workable format. */
  30227. }
  30228. /* Getting here means this encoding does not match our preferred format so we need to more on to the next encoding. */
  30229. counter += 1;
  30230. }
  30231. }
  30232. /* Getting here means not appropriate format was found. */
  30233. return ma_format_unknown;
  30234. }
  30235. #else
  30236. static ma_format ma_format_from_swpar__audio4(struct audio_swpar* par)
  30237. {
  30238. if (par->bits == 8 && par->bps == 1 && par->sig == 0) {
  30239. return ma_format_u8;
  30240. }
  30241. if (par->bits == 16 && par->bps == 2 && par->sig == 1 && par->le == ma_is_little_endian()) {
  30242. return ma_format_s16;
  30243. }
  30244. if (par->bits == 24 && par->bps == 3 && par->sig == 1 && par->le == ma_is_little_endian()) {
  30245. return ma_format_s24;
  30246. }
  30247. if (par->bits == 32 && par->bps == 4 && par->sig == 1 && par->le == ma_is_little_endian()) {
  30248. return ma_format_f32;
  30249. }
  30250. /* Format not supported. */
  30251. return ma_format_unknown;
  30252. }
  30253. #endif
  30254. static ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_device_type deviceType, int fd, ma_device_info* pDeviceInfo)
  30255. {
  30256. audio_device_t fdDevice;
  30257. MA_ASSERT(pContext != NULL);
  30258. MA_ASSERT(fd >= 0);
  30259. MA_ASSERT(pDeviceInfo != NULL);
  30260. (void)pContext;
  30261. (void)deviceType;
  30262. if (ioctl(fd, AUDIO_GETDEV, &fdDevice) < 0) {
  30263. return MA_ERROR; /* Failed to retrieve device info. */
  30264. }
  30265. /* Name. */
  30266. ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), fdDevice.name);
  30267. #if !defined(MA_AUDIO4_USE_NEW_API)
  30268. {
  30269. audio_info_t fdInfo;
  30270. int counter = 0;
  30271. ma_uint32 channels;
  30272. ma_uint32 sampleRate;
  30273. if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) {
  30274. return MA_ERROR;
  30275. }
  30276. if (deviceType == ma_device_type_playback) {
  30277. channels = fdInfo.play.channels;
  30278. sampleRate = fdInfo.play.sample_rate;
  30279. } else {
  30280. channels = fdInfo.record.channels;
  30281. sampleRate = fdInfo.record.sample_rate;
  30282. }
  30283. /* Supported formats. We get this by looking at the encodings. */
  30284. pDeviceInfo->nativeDataFormatCount = 0;
  30285. for (;;) {
  30286. audio_encoding_t encoding;
  30287. ma_format format;
  30288. MA_ZERO_OBJECT(&encoding);
  30289. encoding.index = counter;
  30290. if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) {
  30291. break;
  30292. }
  30293. format = ma_format_from_encoding__audio4(encoding.encoding, encoding.precision);
  30294. if (format != ma_format_unknown) {
  30295. ma_device_info_add_native_data_format(pDeviceInfo, format, channels, sampleRate, 0);
  30296. }
  30297. counter += 1;
  30298. }
  30299. }
  30300. #else
  30301. {
  30302. struct audio_swpar fdPar;
  30303. ma_format format;
  30304. ma_uint32 channels;
  30305. ma_uint32 sampleRate;
  30306. if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
  30307. return MA_ERROR;
  30308. }
  30309. format = ma_format_from_swpar__audio4(&fdPar);
  30310. if (format == ma_format_unknown) {
  30311. return MA_FORMAT_NOT_SUPPORTED;
  30312. }
  30313. if (deviceType == ma_device_type_playback) {
  30314. channels = fdPar.pchan;
  30315. } else {
  30316. channels = fdPar.rchan;
  30317. }
  30318. sampleRate = fdPar.rate;
  30319. pDeviceInfo->nativeDataFormatCount = 0;
  30320. ma_device_info_add_native_data_format(pDeviceInfo, format, channels, sampleRate, 0);
  30321. }
  30322. #endif
  30323. return MA_SUCCESS;
  30324. }
  30325. static ma_result ma_context_enumerate_devices__audio4(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  30326. {
  30327. const int maxDevices = 64;
  30328. char devpath[256];
  30329. int iDevice;
  30330. MA_ASSERT(pContext != NULL);
  30331. MA_ASSERT(callback != NULL);
  30332. /*
  30333. Every device will be named "/dev/audioN", with a "/dev/audioctlN" equivalent. We use the "/dev/audioctlN"
  30334. version here since we can open it even when another process has control of the "/dev/audioN" device.
  30335. */
  30336. for (iDevice = 0; iDevice < maxDevices; ++iDevice) {
  30337. struct stat st;
  30338. int fd;
  30339. ma_bool32 isTerminating = MA_FALSE;
  30340. ma_strcpy_s(devpath, sizeof(devpath), "/dev/audioctl");
  30341. ma_itoa_s(iDevice, devpath+strlen(devpath), sizeof(devpath)-strlen(devpath), 10);
  30342. if (stat(devpath, &st) < 0) {
  30343. break;
  30344. }
  30345. /* The device exists, but we need to check if it's usable as playback and/or capture. */
  30346. /* Playback. */
  30347. if (!isTerminating) {
  30348. fd = open(devpath, O_RDONLY, 0);
  30349. if (fd >= 0) {
  30350. /* Supports playback. */
  30351. ma_device_info deviceInfo;
  30352. MA_ZERO_OBJECT(&deviceInfo);
  30353. ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice);
  30354. if (ma_context_get_device_info_from_fd__audio4(pContext, ma_device_type_playback, fd, &deviceInfo) == MA_SUCCESS) {
  30355. isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  30356. }
  30357. close(fd);
  30358. }
  30359. }
  30360. /* Capture. */
  30361. if (!isTerminating) {
  30362. fd = open(devpath, O_WRONLY, 0);
  30363. if (fd >= 0) {
  30364. /* Supports capture. */
  30365. ma_device_info deviceInfo;
  30366. MA_ZERO_OBJECT(&deviceInfo);
  30367. ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice);
  30368. if (ma_context_get_device_info_from_fd__audio4(pContext, ma_device_type_capture, fd, &deviceInfo) == MA_SUCCESS) {
  30369. isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  30370. }
  30371. close(fd);
  30372. }
  30373. }
  30374. if (isTerminating) {
  30375. break;
  30376. }
  30377. }
  30378. return MA_SUCCESS;
  30379. }
  30380. static ma_result ma_context_get_device_info__audio4(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  30381. {
  30382. int fd = -1;
  30383. int deviceIndex = -1;
  30384. char ctlid[256];
  30385. ma_result result;
  30386. MA_ASSERT(pContext != NULL);
  30387. /*
  30388. We need to open the "/dev/audioctlN" device to get the info. To do this we need to extract the number
  30389. from the device ID which will be in "/dev/audioN" format.
  30390. */
  30391. if (pDeviceID == NULL) {
  30392. /* Default device. */
  30393. ma_strcpy_s(ctlid, sizeof(ctlid), "/dev/audioctl");
  30394. } else {
  30395. /* Specific device. We need to convert from "/dev/audioN" to "/dev/audioctlN". */
  30396. result = ma_extract_device_index_from_id__audio4(pDeviceID->audio4, "/dev/audio", &deviceIndex);
  30397. if (result != MA_SUCCESS) {
  30398. return result;
  30399. }
  30400. ma_construct_device_id__audio4(ctlid, sizeof(ctlid), "/dev/audioctl", deviceIndex);
  30401. }
  30402. fd = open(ctlid, (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY, 0);
  30403. if (fd == -1) {
  30404. return MA_NO_DEVICE;
  30405. }
  30406. if (deviceIndex == -1) {
  30407. ma_strcpy_s(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio");
  30408. } else {
  30409. ma_construct_device_id__audio4(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio", deviceIndex);
  30410. }
  30411. result = ma_context_get_device_info_from_fd__audio4(pContext, deviceType, fd, pDeviceInfo);
  30412. close(fd);
  30413. return result;
  30414. }
  30415. static ma_result ma_device_uninit__audio4(ma_device* pDevice)
  30416. {
  30417. MA_ASSERT(pDevice != NULL);
  30418. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30419. close(pDevice->audio4.fdCapture);
  30420. }
  30421. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30422. close(pDevice->audio4.fdPlayback);
  30423. }
  30424. return MA_SUCCESS;
  30425. }
  30426. static ma_result ma_device_init_fd__audio4(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  30427. {
  30428. const char* pDefaultDeviceNames[] = {
  30429. "/dev/audio",
  30430. "/dev/audio0"
  30431. };
  30432. const char* pDefaultDeviceCtlNames[] = {
  30433. "/dev/audioctl",
  30434. "/dev/audioctl0"
  30435. };
  30436. int fd;
  30437. int fdFlags = 0;
  30438. size_t iDefaultDevice = (size_t)-1;
  30439. ma_format internalFormat;
  30440. ma_uint32 internalChannels;
  30441. ma_uint32 internalSampleRate;
  30442. ma_uint32 internalPeriodSizeInFrames;
  30443. ma_uint32 internalPeriods;
  30444. MA_ASSERT(pConfig != NULL);
  30445. MA_ASSERT(deviceType != ma_device_type_duplex);
  30446. MA_ASSERT(pDevice != NULL);
  30447. /* The first thing to do is open the file. */
  30448. if (deviceType == ma_device_type_capture) {
  30449. fdFlags = O_RDONLY;
  30450. } else {
  30451. fdFlags = O_WRONLY;
  30452. }
  30453. /*fdFlags |= O_NONBLOCK;*/
  30454. /* Find the index of the default device as a start. We'll use this index later. Set it to (size_t)-1 otherwise. */
  30455. if (pDescriptor->pDeviceID == NULL) {
  30456. /* Default device. */
  30457. for (iDefaultDevice = 0; iDefaultDevice < ma_countof(pDefaultDeviceNames); ++iDefaultDevice) {
  30458. fd = open(pDefaultDeviceNames[iDefaultDevice], fdFlags, 0);
  30459. if (fd != -1) {
  30460. break;
  30461. }
  30462. }
  30463. } else {
  30464. /* Specific device. */
  30465. fd = open(pDescriptor->pDeviceID->audio4, fdFlags, 0);
  30466. for (iDefaultDevice = 0; iDefaultDevice < ma_countof(pDefaultDeviceNames); iDefaultDevice += 1) {
  30467. if (ma_strcmp(pDefaultDeviceNames[iDefaultDevice], pDescriptor->pDeviceID->audio4) == 0) {
  30468. break;
  30469. }
  30470. }
  30471. if (iDefaultDevice == ma_countof(pDefaultDeviceNames)) {
  30472. iDefaultDevice = (size_t)-1;
  30473. }
  30474. }
  30475. if (fd == -1) {
  30476. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to open device.");
  30477. return ma_result_from_errno(errno);
  30478. }
  30479. #if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */
  30480. {
  30481. audio_info_t fdInfo;
  30482. int fdInfoResult = -1;
  30483. /*
  30484. The documentation is a little bit unclear to me as to how it handles formats. It says the
  30485. following:
  30486. Regardless of formats supported by underlying driver, the audio driver accepts the
  30487. following formats.
  30488. By then the next sentence says this:
  30489. `encoding` and `precision` are one of the values obtained by AUDIO_GETENC.
  30490. It sounds like a direct contradiction to me. I'm going to play this safe any only use the
  30491. best sample format returned by AUDIO_GETENC. If the requested format is supported we'll
  30492. use that, but otherwise we'll just use our standard format priorities to pick an
  30493. appropriate one.
  30494. */
  30495. AUDIO_INITINFO(&fdInfo);
  30496. /*
  30497. Get the default format from the audioctl file if we're asking for a default device. If we
  30498. retrieve it from /dev/audio it'll default to mono 8000Hz.
  30499. */
  30500. if (iDefaultDevice != (size_t)-1) {
  30501. /* We're using a default device. Get the info from the /dev/audioctl file instead of /dev/audio. */
  30502. int fdctl = open(pDefaultDeviceCtlNames[iDefaultDevice], fdFlags, 0);
  30503. if (fdctl != -1) {
  30504. fdInfoResult = ioctl(fdctl, AUDIO_GETINFO, &fdInfo);
  30505. close(fdctl);
  30506. }
  30507. }
  30508. if (fdInfoResult == -1) {
  30509. /* We still don't have the default device info so just retrieve it from the main audio device. */
  30510. if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) {
  30511. close(fd);
  30512. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed.");
  30513. return ma_result_from_errno(errno);
  30514. }
  30515. }
  30516. /* We get the driver to do as much of the data conversion as possible. */
  30517. if (deviceType == ma_device_type_capture) {
  30518. fdInfo.mode = AUMODE_RECORD;
  30519. ma_encoding_from_format__audio4(ma_best_format_from_fd__audio4(fd, pDescriptor->format), &fdInfo.record.encoding, &fdInfo.record.precision);
  30520. if (pDescriptor->channels != 0) {
  30521. fdInfo.record.channels = ma_clamp(pDescriptor->channels, 1, 12); /* From the documentation: `channels` ranges from 1 to 12. */
  30522. }
  30523. if (pDescriptor->sampleRate != 0) {
  30524. fdInfo.record.sample_rate = ma_clamp(pDescriptor->sampleRate, 1000, 192000); /* From the documentation: `frequency` ranges from 1000Hz to 192000Hz. (They mean `sample_rate` instead of `frequency`.) */
  30525. }
  30526. } else {
  30527. fdInfo.mode = AUMODE_PLAY;
  30528. ma_encoding_from_format__audio4(ma_best_format_from_fd__audio4(fd, pDescriptor->format), &fdInfo.play.encoding, &fdInfo.play.precision);
  30529. if (pDescriptor->channels != 0) {
  30530. fdInfo.play.channels = ma_clamp(pDescriptor->channels, 1, 12); /* From the documentation: `channels` ranges from 1 to 12. */
  30531. }
  30532. if (pDescriptor->sampleRate != 0) {
  30533. fdInfo.play.sample_rate = ma_clamp(pDescriptor->sampleRate, 1000, 192000); /* From the documentation: `frequency` ranges from 1000Hz to 192000Hz. (They mean `sample_rate` instead of `frequency`.) */
  30534. }
  30535. }
  30536. if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) {
  30537. close(fd);
  30538. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device format. AUDIO_SETINFO failed.");
  30539. return ma_result_from_errno(errno);
  30540. }
  30541. if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) {
  30542. close(fd);
  30543. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed.");
  30544. return ma_result_from_errno(errno);
  30545. }
  30546. if (deviceType == ma_device_type_capture) {
  30547. internalFormat = ma_format_from_prinfo__audio4(&fdInfo.record);
  30548. internalChannels = fdInfo.record.channels;
  30549. internalSampleRate = fdInfo.record.sample_rate;
  30550. } else {
  30551. internalFormat = ma_format_from_prinfo__audio4(&fdInfo.play);
  30552. internalChannels = fdInfo.play.channels;
  30553. internalSampleRate = fdInfo.play.sample_rate;
  30554. }
  30555. if (internalFormat == ma_format_unknown) {
  30556. close(fd);
  30557. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable.");
  30558. return MA_FORMAT_NOT_SUPPORTED;
  30559. }
  30560. /* Buffer. */
  30561. {
  30562. ma_uint32 internalPeriodSizeInBytes;
  30563. internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile);
  30564. internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels);
  30565. if (internalPeriodSizeInBytes < 16) {
  30566. internalPeriodSizeInBytes = 16;
  30567. }
  30568. internalPeriods = pDescriptor->periodCount;
  30569. if (internalPeriods < 2) {
  30570. internalPeriods = 2;
  30571. }
  30572. /* What miniaudio calls a period, audio4 calls a block. */
  30573. AUDIO_INITINFO(&fdInfo);
  30574. fdInfo.hiwat = internalPeriods;
  30575. fdInfo.lowat = internalPeriods-1;
  30576. fdInfo.blocksize = internalPeriodSizeInBytes;
  30577. if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) {
  30578. close(fd);
  30579. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set internal buffer size. AUDIO_SETINFO failed.");
  30580. return ma_result_from_errno(errno);
  30581. }
  30582. internalPeriods = fdInfo.hiwat;
  30583. internalPeriodSizeInFrames = fdInfo.blocksize / ma_get_bytes_per_frame(internalFormat, internalChannels);
  30584. }
  30585. }
  30586. #else
  30587. {
  30588. struct audio_swpar fdPar;
  30589. /* We need to retrieve the format of the device so we can know the channel count and sample rate. Then we can calculate the buffer size. */
  30590. if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
  30591. close(fd);
  30592. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve initial device parameters.");
  30593. return ma_result_from_errno(errno);
  30594. }
  30595. internalFormat = ma_format_from_swpar__audio4(&fdPar);
  30596. internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan;
  30597. internalSampleRate = fdPar.rate;
  30598. if (internalFormat == ma_format_unknown) {
  30599. close(fd);
  30600. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable.");
  30601. return MA_FORMAT_NOT_SUPPORTED;
  30602. }
  30603. /* Buffer. */
  30604. {
  30605. ma_uint32 internalPeriodSizeInBytes;
  30606. internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile);
  30607. /* What miniaudio calls a period, audio4 calls a block. */
  30608. internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels);
  30609. if (internalPeriodSizeInBytes < 16) {
  30610. internalPeriodSizeInBytes = 16;
  30611. }
  30612. fdPar.nblks = pDescriptor->periodCount;
  30613. fdPar.round = internalPeriodSizeInBytes;
  30614. if (ioctl(fd, AUDIO_SETPAR, &fdPar) < 0) {
  30615. close(fd);
  30616. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device parameters.");
  30617. return ma_result_from_errno(errno);
  30618. }
  30619. if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
  30620. close(fd);
  30621. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve actual device parameters.");
  30622. return ma_result_from_errno(errno);
  30623. }
  30624. }
  30625. internalFormat = ma_format_from_swpar__audio4(&fdPar);
  30626. internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan;
  30627. internalSampleRate = fdPar.rate;
  30628. internalPeriods = fdPar.nblks;
  30629. internalPeriodSizeInFrames = fdPar.round / ma_get_bytes_per_frame(internalFormat, internalChannels);
  30630. }
  30631. #endif
  30632. if (internalFormat == ma_format_unknown) {
  30633. close(fd);
  30634. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable.");
  30635. return MA_FORMAT_NOT_SUPPORTED;
  30636. }
  30637. if (deviceType == ma_device_type_capture) {
  30638. pDevice->audio4.fdCapture = fd;
  30639. } else {
  30640. pDevice->audio4.fdPlayback = fd;
  30641. }
  30642. pDescriptor->format = internalFormat;
  30643. pDescriptor->channels = internalChannels;
  30644. pDescriptor->sampleRate = internalSampleRate;
  30645. ma_channel_map_init_standard(ma_standard_channel_map_sound4, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), internalChannels);
  30646. pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames;
  30647. pDescriptor->periodCount = internalPeriods;
  30648. return MA_SUCCESS;
  30649. }
  30650. static ma_result ma_device_init__audio4(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  30651. {
  30652. MA_ASSERT(pDevice != NULL);
  30653. MA_ZERO_OBJECT(&pDevice->audio4);
  30654. if (pConfig->deviceType == ma_device_type_loopback) {
  30655. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  30656. }
  30657. pDevice->audio4.fdCapture = -1;
  30658. pDevice->audio4.fdPlayback = -1;
  30659. /*
  30660. The version of the operating system dictates whether or not the device is exclusive or shared. NetBSD
  30661. introduced in-kernel mixing which means it's shared. All other BSD flavours are exclusive as far as
  30662. I'm aware.
  30663. */
  30664. #if defined(__NetBSD_Version__) && __NetBSD_Version__ >= 800000000
  30665. /* NetBSD 8.0+ */
  30666. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  30667. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  30668. return MA_SHARE_MODE_NOT_SUPPORTED;
  30669. }
  30670. #else
  30671. /* All other flavors. */
  30672. #endif
  30673. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  30674. ma_result result = ma_device_init_fd__audio4(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  30675. if (result != MA_SUCCESS) {
  30676. return result;
  30677. }
  30678. }
  30679. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  30680. ma_result result = ma_device_init_fd__audio4(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  30681. if (result != MA_SUCCESS) {
  30682. if (pConfig->deviceType == ma_device_type_duplex) {
  30683. close(pDevice->audio4.fdCapture);
  30684. }
  30685. return result;
  30686. }
  30687. }
  30688. return MA_SUCCESS;
  30689. }
  30690. static ma_result ma_device_start__audio4(ma_device* pDevice)
  30691. {
  30692. MA_ASSERT(pDevice != NULL);
  30693. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30694. if (pDevice->audio4.fdCapture == -1) {
  30695. return MA_INVALID_ARGS;
  30696. }
  30697. }
  30698. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30699. if (pDevice->audio4.fdPlayback == -1) {
  30700. return MA_INVALID_ARGS;
  30701. }
  30702. }
  30703. return MA_SUCCESS;
  30704. }
  30705. static ma_result ma_device_stop_fd__audio4(ma_device* pDevice, int fd)
  30706. {
  30707. if (fd == -1) {
  30708. return MA_INVALID_ARGS;
  30709. }
  30710. #if !defined(MA_AUDIO4_USE_NEW_API)
  30711. if (ioctl(fd, AUDIO_FLUSH, 0) < 0) {
  30712. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_FLUSH failed.");
  30713. return ma_result_from_errno(errno);
  30714. }
  30715. #else
  30716. if (ioctl(fd, AUDIO_STOP, 0) < 0) {
  30717. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_STOP failed.");
  30718. return ma_result_from_errno(errno);
  30719. }
  30720. #endif
  30721. return MA_SUCCESS;
  30722. }
  30723. static ma_result ma_device_stop__audio4(ma_device* pDevice)
  30724. {
  30725. MA_ASSERT(pDevice != NULL);
  30726. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30727. ma_result result;
  30728. result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdCapture);
  30729. if (result != MA_SUCCESS) {
  30730. return result;
  30731. }
  30732. }
  30733. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30734. ma_result result;
  30735. /* Drain the device first. If this fails we'll just need to flush without draining. Unfortunately draining isn't available on newer version of OpenBSD. */
  30736. #if !defined(MA_AUDIO4_USE_NEW_API)
  30737. ioctl(pDevice->audio4.fdPlayback, AUDIO_DRAIN, 0);
  30738. #endif
  30739. /* Here is where the device is stopped immediately. */
  30740. result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdPlayback);
  30741. if (result != MA_SUCCESS) {
  30742. return result;
  30743. }
  30744. }
  30745. return MA_SUCCESS;
  30746. }
  30747. static ma_result ma_device_write__audio4(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  30748. {
  30749. int result;
  30750. if (pFramesWritten != NULL) {
  30751. *pFramesWritten = 0;
  30752. }
  30753. result = write(pDevice->audio4.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  30754. if (result < 0) {
  30755. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to write data to the device.");
  30756. return ma_result_from_errno(errno);
  30757. }
  30758. if (pFramesWritten != NULL) {
  30759. *pFramesWritten = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  30760. }
  30761. return MA_SUCCESS;
  30762. }
  30763. static ma_result ma_device_read__audio4(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  30764. {
  30765. int result;
  30766. if (pFramesRead != NULL) {
  30767. *pFramesRead = 0;
  30768. }
  30769. result = read(pDevice->audio4.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  30770. if (result < 0) {
  30771. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to read data from the device.");
  30772. return ma_result_from_errno(errno);
  30773. }
  30774. if (pFramesRead != NULL) {
  30775. *pFramesRead = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  30776. }
  30777. return MA_SUCCESS;
  30778. }
  30779. static ma_result ma_context_uninit__audio4(ma_context* pContext)
  30780. {
  30781. MA_ASSERT(pContext != NULL);
  30782. MA_ASSERT(pContext->backend == ma_backend_audio4);
  30783. (void)pContext;
  30784. return MA_SUCCESS;
  30785. }
  30786. static ma_result ma_context_init__audio4(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  30787. {
  30788. MA_ASSERT(pContext != NULL);
  30789. (void)pConfig;
  30790. pCallbacks->onContextInit = ma_context_init__audio4;
  30791. pCallbacks->onContextUninit = ma_context_uninit__audio4;
  30792. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__audio4;
  30793. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__audio4;
  30794. pCallbacks->onDeviceInit = ma_device_init__audio4;
  30795. pCallbacks->onDeviceUninit = ma_device_uninit__audio4;
  30796. pCallbacks->onDeviceStart = ma_device_start__audio4;
  30797. pCallbacks->onDeviceStop = ma_device_stop__audio4;
  30798. pCallbacks->onDeviceRead = ma_device_read__audio4;
  30799. pCallbacks->onDeviceWrite = ma_device_write__audio4;
  30800. pCallbacks->onDeviceDataLoop = NULL;
  30801. return MA_SUCCESS;
  30802. }
  30803. #endif /* audio4 */
  30804. /******************************************************************************
  30805. OSS Backend
  30806. ******************************************************************************/
  30807. #ifdef MA_HAS_OSS
  30808. #include <sys/ioctl.h>
  30809. #include <unistd.h>
  30810. #include <fcntl.h>
  30811. #include <sys/soundcard.h>
  30812. #ifndef SNDCTL_DSP_HALT
  30813. #define SNDCTL_DSP_HALT SNDCTL_DSP_RESET
  30814. #endif
  30815. #define MA_OSS_DEFAULT_DEVICE_NAME "/dev/dsp"
  30816. static int ma_open_temp_device__oss()
  30817. {
  30818. /* The OSS sample code uses "/dev/mixer" as the device for getting system properties so I'm going to do the same. */
  30819. int fd = open("/dev/mixer", O_RDONLY, 0);
  30820. if (fd >= 0) {
  30821. return fd;
  30822. }
  30823. return -1;
  30824. }
  30825. static ma_result ma_context_open_device__oss(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, int* pfd)
  30826. {
  30827. const char* deviceName;
  30828. int flags;
  30829. MA_ASSERT(pContext != NULL);
  30830. MA_ASSERT(pfd != NULL);
  30831. (void)pContext;
  30832. *pfd = -1;
  30833. /* This function should only be called for playback or capture, not duplex. */
  30834. if (deviceType == ma_device_type_duplex) {
  30835. return MA_INVALID_ARGS;
  30836. }
  30837. deviceName = MA_OSS_DEFAULT_DEVICE_NAME;
  30838. if (pDeviceID != NULL) {
  30839. deviceName = pDeviceID->oss;
  30840. }
  30841. flags = (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY;
  30842. if (shareMode == ma_share_mode_exclusive) {
  30843. flags |= O_EXCL;
  30844. }
  30845. *pfd = open(deviceName, flags, 0);
  30846. if (*pfd == -1) {
  30847. return ma_result_from_errno(errno);
  30848. }
  30849. return MA_SUCCESS;
  30850. }
  30851. static ma_result ma_context_enumerate_devices__oss(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  30852. {
  30853. int fd;
  30854. oss_sysinfo si;
  30855. int result;
  30856. MA_ASSERT(pContext != NULL);
  30857. MA_ASSERT(callback != NULL);
  30858. fd = ma_open_temp_device__oss();
  30859. if (fd == -1) {
  30860. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration.");
  30861. return MA_NO_BACKEND;
  30862. }
  30863. result = ioctl(fd, SNDCTL_SYSINFO, &si);
  30864. if (result != -1) {
  30865. int iAudioDevice;
  30866. for (iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) {
  30867. oss_audioinfo ai;
  30868. ai.dev = iAudioDevice;
  30869. result = ioctl(fd, SNDCTL_AUDIOINFO, &ai);
  30870. if (result != -1) {
  30871. if (ai.devnode[0] != '\0') { /* <-- Can be blank, according to documentation. */
  30872. ma_device_info deviceInfo;
  30873. ma_bool32 isTerminating = MA_FALSE;
  30874. MA_ZERO_OBJECT(&deviceInfo);
  30875. /* ID */
  30876. ma_strncpy_s(deviceInfo.id.oss, sizeof(deviceInfo.id.oss), ai.devnode, (size_t)-1);
  30877. /*
  30878. The human readable device name should be in the "ai.handle" variable, but it can
  30879. sometimes be empty in which case we just fall back to "ai.name" which is less user
  30880. friendly, but usually has a value.
  30881. */
  30882. if (ai.handle[0] != '\0') {
  30883. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.handle, (size_t)-1);
  30884. } else {
  30885. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.name, (size_t)-1);
  30886. }
  30887. /* The device can be both playback and capture. */
  30888. if (!isTerminating && (ai.caps & PCM_CAP_OUTPUT) != 0) {
  30889. isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  30890. }
  30891. if (!isTerminating && (ai.caps & PCM_CAP_INPUT) != 0) {
  30892. isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  30893. }
  30894. if (isTerminating) {
  30895. break;
  30896. }
  30897. }
  30898. }
  30899. }
  30900. } else {
  30901. close(fd);
  30902. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.");
  30903. return MA_NO_BACKEND;
  30904. }
  30905. close(fd);
  30906. return MA_SUCCESS;
  30907. }
  30908. static void ma_context_add_native_data_format__oss(ma_context* pContext, oss_audioinfo* pAudioInfo, ma_format format, ma_device_info* pDeviceInfo)
  30909. {
  30910. unsigned int minChannels;
  30911. unsigned int maxChannels;
  30912. unsigned int iRate;
  30913. MA_ASSERT(pContext != NULL);
  30914. MA_ASSERT(pAudioInfo != NULL);
  30915. MA_ASSERT(pDeviceInfo != NULL);
  30916. /* If we support all channels we just report 0. */
  30917. minChannels = ma_clamp(pAudioInfo->min_channels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  30918. maxChannels = ma_clamp(pAudioInfo->max_channels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  30919. /*
  30920. OSS has this annoying thing where sample rates can be reported in two ways. We prefer explicitness,
  30921. which OSS has in the form of nrates/rates, however there are times where nrates can be 0, in which
  30922. case we'll need to use min_rate and max_rate and report only standard rates.
  30923. */
  30924. if (pAudioInfo->nrates > 0) {
  30925. for (iRate = 0; iRate < pAudioInfo->nrates; iRate += 1) {
  30926. unsigned int rate = pAudioInfo->rates[iRate];
  30927. if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) {
  30928. ma_device_info_add_native_data_format(pDeviceInfo, format, 0, rate, 0); /* Set the channel count to 0 to indicate that all channel counts are supported. */
  30929. } else {
  30930. unsigned int iChannel;
  30931. for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) {
  30932. ma_device_info_add_native_data_format(pDeviceInfo, format, iChannel, rate, 0);
  30933. }
  30934. }
  30935. }
  30936. } else {
  30937. for (iRate = 0; iRate < ma_countof(g_maStandardSampleRatePriorities); iRate += 1) {
  30938. ma_uint32 standardRate = g_maStandardSampleRatePriorities[iRate];
  30939. if (standardRate >= (ma_uint32)pAudioInfo->min_rate && standardRate <= (ma_uint32)pAudioInfo->max_rate) {
  30940. if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) {
  30941. ma_device_info_add_native_data_format(pDeviceInfo, format, 0, standardRate, 0); /* Set the channel count to 0 to indicate that all channel counts are supported. */
  30942. } else {
  30943. unsigned int iChannel;
  30944. for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) {
  30945. ma_device_info_add_native_data_format(pDeviceInfo, format, iChannel, standardRate, 0);
  30946. }
  30947. }
  30948. }
  30949. }
  30950. }
  30951. }
  30952. static ma_result ma_context_get_device_info__oss(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  30953. {
  30954. ma_bool32 foundDevice;
  30955. int fdTemp;
  30956. oss_sysinfo si;
  30957. int result;
  30958. MA_ASSERT(pContext != NULL);
  30959. /* Handle the default device a little differently. */
  30960. if (pDeviceID == NULL) {
  30961. if (deviceType == ma_device_type_playback) {
  30962. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  30963. } else {
  30964. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  30965. }
  30966. return MA_SUCCESS;
  30967. }
  30968. /* If we get here it means we are _not_ using the default device. */
  30969. foundDevice = MA_FALSE;
  30970. fdTemp = ma_open_temp_device__oss();
  30971. if (fdTemp == -1) {
  30972. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration.");
  30973. return MA_NO_BACKEND;
  30974. }
  30975. result = ioctl(fdTemp, SNDCTL_SYSINFO, &si);
  30976. if (result != -1) {
  30977. int iAudioDevice;
  30978. for (iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) {
  30979. oss_audioinfo ai;
  30980. ai.dev = iAudioDevice;
  30981. result = ioctl(fdTemp, SNDCTL_AUDIOINFO, &ai);
  30982. if (result != -1) {
  30983. if (ma_strcmp(ai.devnode, pDeviceID->oss) == 0) {
  30984. /* It has the same name, so now just confirm the type. */
  30985. if ((deviceType == ma_device_type_playback && ((ai.caps & PCM_CAP_OUTPUT) != 0)) ||
  30986. (deviceType == ma_device_type_capture && ((ai.caps & PCM_CAP_INPUT) != 0))) {
  30987. unsigned int formatMask;
  30988. /* ID */
  30989. ma_strncpy_s(pDeviceInfo->id.oss, sizeof(pDeviceInfo->id.oss), ai.devnode, (size_t)-1);
  30990. /*
  30991. The human readable device name should be in the "ai.handle" variable, but it can
  30992. sometimes be empty in which case we just fall back to "ai.name" which is less user
  30993. friendly, but usually has a value.
  30994. */
  30995. if (ai.handle[0] != '\0') {
  30996. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.handle, (size_t)-1);
  30997. } else {
  30998. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.name, (size_t)-1);
  30999. }
  31000. pDeviceInfo->nativeDataFormatCount = 0;
  31001. if (deviceType == ma_device_type_playback) {
  31002. formatMask = ai.oformats;
  31003. } else {
  31004. formatMask = ai.iformats;
  31005. }
  31006. if (((formatMask & AFMT_S16_LE) != 0 && ma_is_little_endian()) || (AFMT_S16_BE && ma_is_big_endian())) {
  31007. ma_context_add_native_data_format__oss(pContext, &ai, ma_format_s16, pDeviceInfo);
  31008. }
  31009. if (((formatMask & AFMT_S32_LE) != 0 && ma_is_little_endian()) || (AFMT_S32_BE && ma_is_big_endian())) {
  31010. ma_context_add_native_data_format__oss(pContext, &ai, ma_format_s32, pDeviceInfo);
  31011. }
  31012. if ((formatMask & AFMT_U8) != 0) {
  31013. ma_context_add_native_data_format__oss(pContext, &ai, ma_format_u8, pDeviceInfo);
  31014. }
  31015. foundDevice = MA_TRUE;
  31016. break;
  31017. }
  31018. }
  31019. }
  31020. }
  31021. } else {
  31022. close(fdTemp);
  31023. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.");
  31024. return MA_NO_BACKEND;
  31025. }
  31026. close(fdTemp);
  31027. if (!foundDevice) {
  31028. return MA_NO_DEVICE;
  31029. }
  31030. return MA_SUCCESS;
  31031. }
  31032. static ma_result ma_device_uninit__oss(ma_device* pDevice)
  31033. {
  31034. MA_ASSERT(pDevice != NULL);
  31035. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31036. close(pDevice->oss.fdCapture);
  31037. }
  31038. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  31039. close(pDevice->oss.fdPlayback);
  31040. }
  31041. return MA_SUCCESS;
  31042. }
  31043. static int ma_format_to_oss(ma_format format)
  31044. {
  31045. int ossFormat = AFMT_U8;
  31046. switch (format) {
  31047. case ma_format_s16: ossFormat = (ma_is_little_endian()) ? AFMT_S16_LE : AFMT_S16_BE; break;
  31048. case ma_format_s24: ossFormat = (ma_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break;
  31049. case ma_format_s32: ossFormat = (ma_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break;
  31050. case ma_format_f32: ossFormat = (ma_is_little_endian()) ? AFMT_S16_LE : AFMT_S16_BE; break;
  31051. case ma_format_u8:
  31052. default: ossFormat = AFMT_U8; break;
  31053. }
  31054. return ossFormat;
  31055. }
  31056. static ma_format ma_format_from_oss(int ossFormat)
  31057. {
  31058. if (ossFormat == AFMT_U8) {
  31059. return ma_format_u8;
  31060. } else {
  31061. if (ma_is_little_endian()) {
  31062. switch (ossFormat) {
  31063. case AFMT_S16_LE: return ma_format_s16;
  31064. case AFMT_S32_LE: return ma_format_s32;
  31065. default: return ma_format_unknown;
  31066. }
  31067. } else {
  31068. switch (ossFormat) {
  31069. case AFMT_S16_BE: return ma_format_s16;
  31070. case AFMT_S32_BE: return ma_format_s32;
  31071. default: return ma_format_unknown;
  31072. }
  31073. }
  31074. }
  31075. return ma_format_unknown;
  31076. }
  31077. static ma_result ma_device_init_fd__oss(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  31078. {
  31079. ma_result result;
  31080. int ossResult;
  31081. int fd;
  31082. const ma_device_id* pDeviceID = NULL;
  31083. ma_share_mode shareMode;
  31084. int ossFormat;
  31085. int ossChannels;
  31086. int ossSampleRate;
  31087. int ossFragment;
  31088. MA_ASSERT(pDevice != NULL);
  31089. MA_ASSERT(pConfig != NULL);
  31090. MA_ASSERT(deviceType != ma_device_type_duplex);
  31091. pDeviceID = pDescriptor->pDeviceID;
  31092. shareMode = pDescriptor->shareMode;
  31093. ossFormat = ma_format_to_oss((pDescriptor->format != ma_format_unknown) ? pDescriptor->format : ma_format_s16); /* Use s16 by default because OSS doesn't like floating point. */
  31094. ossChannels = (int)(pDescriptor->channels > 0) ? pDescriptor->channels : MA_DEFAULT_CHANNELS;
  31095. ossSampleRate = (int)(pDescriptor->sampleRate > 0) ? pDescriptor->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  31096. result = ma_context_open_device__oss(pDevice->pContext, deviceType, pDeviceID, shareMode, &fd);
  31097. if (result != MA_SUCCESS) {
  31098. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.");
  31099. return result;
  31100. }
  31101. /*
  31102. The OSS documantation is very clear about the order we should be initializing the device's properties:
  31103. 1) Format
  31104. 2) Channels
  31105. 3) Sample rate.
  31106. */
  31107. /* Format. */
  31108. ossResult = ioctl(fd, SNDCTL_DSP_SETFMT, &ossFormat);
  31109. if (ossResult == -1) {
  31110. close(fd);
  31111. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set format.");
  31112. return ma_result_from_errno(errno);
  31113. }
  31114. /* Channels. */
  31115. ossResult = ioctl(fd, SNDCTL_DSP_CHANNELS, &ossChannels);
  31116. if (ossResult == -1) {
  31117. close(fd);
  31118. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set channel count.");
  31119. return ma_result_from_errno(errno);
  31120. }
  31121. /* Sample Rate. */
  31122. ossResult = ioctl(fd, SNDCTL_DSP_SPEED, &ossSampleRate);
  31123. if (ossResult == -1) {
  31124. close(fd);
  31125. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set sample rate.");
  31126. return ma_result_from_errno(errno);
  31127. }
  31128. /*
  31129. Buffer.
  31130. The documentation says that the fragment settings should be set as soon as possible, but I'm not sure if
  31131. it should be done before or after format/channels/rate.
  31132. OSS wants the fragment size in bytes and a power of 2. When setting, we specify the power, not the actual
  31133. value.
  31134. */
  31135. {
  31136. ma_uint32 periodSizeInFrames;
  31137. ma_uint32 periodSizeInBytes;
  31138. ma_uint32 ossFragmentSizePower;
  31139. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, (ma_uint32)ossSampleRate, pConfig->performanceProfile);
  31140. periodSizeInBytes = ma_round_to_power_of_2(periodSizeInFrames * ma_get_bytes_per_frame(ma_format_from_oss(ossFormat), ossChannels));
  31141. if (periodSizeInBytes < 16) {
  31142. periodSizeInBytes = 16;
  31143. }
  31144. ossFragmentSizePower = 4;
  31145. periodSizeInBytes >>= 4;
  31146. while (periodSizeInBytes >>= 1) {
  31147. ossFragmentSizePower += 1;
  31148. }
  31149. ossFragment = (int)((pConfig->periods << 16) | ossFragmentSizePower);
  31150. ossResult = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossFragment);
  31151. if (ossResult == -1) {
  31152. close(fd);
  31153. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set fragment size and period count.");
  31154. return ma_result_from_errno(errno);
  31155. }
  31156. }
  31157. /* Internal settings. */
  31158. if (deviceType == ma_device_type_capture) {
  31159. pDevice->oss.fdCapture = fd;
  31160. } else {
  31161. pDevice->oss.fdPlayback = fd;
  31162. }
  31163. pDescriptor->format = ma_format_from_oss(ossFormat);
  31164. pDescriptor->channels = ossChannels;
  31165. pDescriptor->sampleRate = ossSampleRate;
  31166. ma_channel_map_init_standard(ma_standard_channel_map_sound4, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), pDescriptor->channels);
  31167. pDescriptor->periodCount = (ma_uint32)(ossFragment >> 16);
  31168. pDescriptor->periodSizeInFrames = (ma_uint32)(1 << (ossFragment & 0xFFFF)) / ma_get_bytes_per_frame(pDescriptor->format, pDescriptor->channels);
  31169. if (pDescriptor->format == ma_format_unknown) {
  31170. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by miniaudio.");
  31171. return MA_FORMAT_NOT_SUPPORTED;
  31172. }
  31173. return MA_SUCCESS;
  31174. }
  31175. static ma_result ma_device_init__oss(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  31176. {
  31177. MA_ASSERT(pDevice != NULL);
  31178. MA_ASSERT(pConfig != NULL);
  31179. MA_ZERO_OBJECT(&pDevice->oss);
  31180. if (pConfig->deviceType == ma_device_type_loopback) {
  31181. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  31182. }
  31183. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  31184. ma_result result = ma_device_init_fd__oss(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  31185. if (result != MA_SUCCESS) {
  31186. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.");
  31187. return result;
  31188. }
  31189. }
  31190. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  31191. ma_result result = ma_device_init_fd__oss(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  31192. if (result != MA_SUCCESS) {
  31193. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.");
  31194. return result;
  31195. }
  31196. }
  31197. return MA_SUCCESS;
  31198. }
  31199. /*
  31200. Note on Starting and Stopping
  31201. =============================
  31202. In the past I was using SNDCTL_DSP_HALT to stop the device, however this results in issues when
  31203. trying to resume the device again. If we use SNDCTL_DSP_HALT, the next write() or read() will
  31204. fail. Instead what we need to do is just not write or read to and from the device when the
  31205. device is not running.
  31206. As a result, both the start and stop functions for OSS are just empty stubs. The starting and
  31207. stopping logic is handled by ma_device_write__oss() and ma_device_read__oss(). These will check
  31208. the device state, and if the device is stopped they will simply not do any kind of processing.
  31209. The downside to this technique is that I've noticed a fairly lengthy delay in stopping the
  31210. device, up to a second. This is on a virtual machine, and as such might just be due to the
  31211. virtual drivers, but I'm not fully sure. I am not sure how to work around this problem so for
  31212. the moment that's just how it's going to have to be.
  31213. When starting the device, OSS will automatically start it when write() or read() is called.
  31214. */
  31215. static ma_result ma_device_start__oss(ma_device* pDevice)
  31216. {
  31217. MA_ASSERT(pDevice != NULL);
  31218. /* The device is automatically started with reading and writing. */
  31219. (void)pDevice;
  31220. return MA_SUCCESS;
  31221. }
  31222. static ma_result ma_device_stop__oss(ma_device* pDevice)
  31223. {
  31224. MA_ASSERT(pDevice != NULL);
  31225. /* See note above on why this is empty. */
  31226. (void)pDevice;
  31227. return MA_SUCCESS;
  31228. }
  31229. static ma_result ma_device_write__oss(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  31230. {
  31231. int resultOSS;
  31232. ma_uint32 deviceState;
  31233. if (pFramesWritten != NULL) {
  31234. *pFramesWritten = 0;
  31235. }
  31236. /* Don't do any processing if the device is stopped. */
  31237. deviceState = ma_device_get_state(pDevice);
  31238. if (deviceState != ma_device_state_started && deviceState != ma_device_state_starting) {
  31239. return MA_SUCCESS;
  31240. }
  31241. resultOSS = write(pDevice->oss.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  31242. if (resultOSS < 0) {
  31243. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to send data from the client to the device.");
  31244. return ma_result_from_errno(errno);
  31245. }
  31246. if (pFramesWritten != NULL) {
  31247. *pFramesWritten = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  31248. }
  31249. return MA_SUCCESS;
  31250. }
  31251. static ma_result ma_device_read__oss(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  31252. {
  31253. int resultOSS;
  31254. ma_uint32 deviceState;
  31255. if (pFramesRead != NULL) {
  31256. *pFramesRead = 0;
  31257. }
  31258. /* Don't do any processing if the device is stopped. */
  31259. deviceState = ma_device_get_state(pDevice);
  31260. if (deviceState != ma_device_state_started && deviceState != ma_device_state_starting) {
  31261. return MA_SUCCESS;
  31262. }
  31263. resultOSS = read(pDevice->oss.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  31264. if (resultOSS < 0) {
  31265. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to read data from the device to be sent to the client.");
  31266. return ma_result_from_errno(errno);
  31267. }
  31268. if (pFramesRead != NULL) {
  31269. *pFramesRead = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  31270. }
  31271. return MA_SUCCESS;
  31272. }
  31273. static ma_result ma_context_uninit__oss(ma_context* pContext)
  31274. {
  31275. MA_ASSERT(pContext != NULL);
  31276. MA_ASSERT(pContext->backend == ma_backend_oss);
  31277. (void)pContext;
  31278. return MA_SUCCESS;
  31279. }
  31280. static ma_result ma_context_init__oss(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  31281. {
  31282. int fd;
  31283. int ossVersion;
  31284. int result;
  31285. MA_ASSERT(pContext != NULL);
  31286. (void)pConfig;
  31287. /* Try opening a temporary device first so we can get version information. This is closed at the end. */
  31288. fd = ma_open_temp_device__oss();
  31289. if (fd == -1) {
  31290. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open temporary device for retrieving system properties."); /* Looks liks OSS isn't installed, or there are no available devices. */
  31291. return MA_NO_BACKEND;
  31292. }
  31293. /* Grab the OSS version. */
  31294. ossVersion = 0;
  31295. result = ioctl(fd, OSS_GETVERSION, &ossVersion);
  31296. if (result == -1) {
  31297. close(fd);
  31298. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve OSS version.");
  31299. return MA_NO_BACKEND;
  31300. }
  31301. /* The file handle to temp device is no longer needed. Close ASAP. */
  31302. close(fd);
  31303. pContext->oss.versionMajor = ((ossVersion & 0xFF0000) >> 16);
  31304. pContext->oss.versionMinor = ((ossVersion & 0x00FF00) >> 8);
  31305. pCallbacks->onContextInit = ma_context_init__oss;
  31306. pCallbacks->onContextUninit = ma_context_uninit__oss;
  31307. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__oss;
  31308. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__oss;
  31309. pCallbacks->onDeviceInit = ma_device_init__oss;
  31310. pCallbacks->onDeviceUninit = ma_device_uninit__oss;
  31311. pCallbacks->onDeviceStart = ma_device_start__oss;
  31312. pCallbacks->onDeviceStop = ma_device_stop__oss;
  31313. pCallbacks->onDeviceRead = ma_device_read__oss;
  31314. pCallbacks->onDeviceWrite = ma_device_write__oss;
  31315. pCallbacks->onDeviceDataLoop = NULL;
  31316. return MA_SUCCESS;
  31317. }
  31318. #endif /* OSS */
  31319. /******************************************************************************
  31320. AAudio Backend
  31321. ******************************************************************************/
  31322. #ifdef MA_HAS_AAUDIO
  31323. /*#include <AAudio/AAudio.h>*/
  31324. typedef int32_t ma_aaudio_result_t;
  31325. typedef int32_t ma_aaudio_direction_t;
  31326. typedef int32_t ma_aaudio_sharing_mode_t;
  31327. typedef int32_t ma_aaudio_format_t;
  31328. typedef int32_t ma_aaudio_stream_state_t;
  31329. typedef int32_t ma_aaudio_performance_mode_t;
  31330. typedef int32_t ma_aaudio_usage_t;
  31331. typedef int32_t ma_aaudio_content_type_t;
  31332. typedef int32_t ma_aaudio_input_preset_t;
  31333. typedef int32_t ma_aaudio_allowed_capture_policy_t;
  31334. typedef int32_t ma_aaudio_data_callback_result_t;
  31335. typedef struct ma_AAudioStreamBuilder_t* ma_AAudioStreamBuilder;
  31336. typedef struct ma_AAudioStream_t* ma_AAudioStream;
  31337. #define MA_AAUDIO_UNSPECIFIED 0
  31338. /* Result codes. miniaudio only cares about the success code. */
  31339. #define MA_AAUDIO_OK 0
  31340. /* Directions. */
  31341. #define MA_AAUDIO_DIRECTION_OUTPUT 0
  31342. #define MA_AAUDIO_DIRECTION_INPUT 1
  31343. /* Sharing modes. */
  31344. #define MA_AAUDIO_SHARING_MODE_EXCLUSIVE 0
  31345. #define MA_AAUDIO_SHARING_MODE_SHARED 1
  31346. /* Formats. */
  31347. #define MA_AAUDIO_FORMAT_PCM_I16 1
  31348. #define MA_AAUDIO_FORMAT_PCM_FLOAT 2
  31349. /* Stream states. */
  31350. #define MA_AAUDIO_STREAM_STATE_UNINITIALIZED 0
  31351. #define MA_AAUDIO_STREAM_STATE_UNKNOWN 1
  31352. #define MA_AAUDIO_STREAM_STATE_OPEN 2
  31353. #define MA_AAUDIO_STREAM_STATE_STARTING 3
  31354. #define MA_AAUDIO_STREAM_STATE_STARTED 4
  31355. #define MA_AAUDIO_STREAM_STATE_PAUSING 5
  31356. #define MA_AAUDIO_STREAM_STATE_PAUSED 6
  31357. #define MA_AAUDIO_STREAM_STATE_FLUSHING 7
  31358. #define MA_AAUDIO_STREAM_STATE_FLUSHED 8
  31359. #define MA_AAUDIO_STREAM_STATE_STOPPING 9
  31360. #define MA_AAUDIO_STREAM_STATE_STOPPED 10
  31361. #define MA_AAUDIO_STREAM_STATE_CLOSING 11
  31362. #define MA_AAUDIO_STREAM_STATE_CLOSED 12
  31363. #define MA_AAUDIO_STREAM_STATE_DISCONNECTED 13
  31364. /* Performance modes. */
  31365. #define MA_AAUDIO_PERFORMANCE_MODE_NONE 10
  31366. #define MA_AAUDIO_PERFORMANCE_MODE_POWER_SAVING 11
  31367. #define MA_AAUDIO_PERFORMANCE_MODE_LOW_LATENCY 12
  31368. /* Usage types. */
  31369. #define MA_AAUDIO_USAGE_MEDIA 1
  31370. #define MA_AAUDIO_USAGE_VOICE_COMMUNICATION 2
  31371. #define MA_AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING 3
  31372. #define MA_AAUDIO_USAGE_ALARM 4
  31373. #define MA_AAUDIO_USAGE_NOTIFICATION 5
  31374. #define MA_AAUDIO_USAGE_NOTIFICATION_RINGTONE 6
  31375. #define MA_AAUDIO_USAGE_NOTIFICATION_EVENT 10
  31376. #define MA_AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY 11
  31377. #define MA_AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE 12
  31378. #define MA_AAUDIO_USAGE_ASSISTANCE_SONIFICATION 13
  31379. #define MA_AAUDIO_USAGE_GAME 14
  31380. #define MA_AAUDIO_USAGE_ASSISTANT 16
  31381. #define MA_AAUDIO_SYSTEM_USAGE_EMERGENCY 1000
  31382. #define MA_AAUDIO_SYSTEM_USAGE_SAFETY 1001
  31383. #define MA_AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS 1002
  31384. #define MA_AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT 1003
  31385. /* Content types. */
  31386. #define MA_AAUDIO_CONTENT_TYPE_SPEECH 1
  31387. #define MA_AAUDIO_CONTENT_TYPE_MUSIC 2
  31388. #define MA_AAUDIO_CONTENT_TYPE_MOVIE 3
  31389. #define MA_AAUDIO_CONTENT_TYPE_SONIFICATION 4
  31390. /* Input presets. */
  31391. #define MA_AAUDIO_INPUT_PRESET_GENERIC 1
  31392. #define MA_AAUDIO_INPUT_PRESET_CAMCORDER 5
  31393. #define MA_AAUDIO_INPUT_PRESET_VOICE_RECOGNITION 6
  31394. #define MA_AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION 7
  31395. #define MA_AAUDIO_INPUT_PRESET_UNPROCESSED 9
  31396. #define MA_AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE 10
  31397. /* Allowed Capture Policies */
  31398. #define MA_AAUDIO_ALLOW_CAPTURE_BY_ALL 1
  31399. #define MA_AAUDIO_ALLOW_CAPTURE_BY_SYSTEM 2
  31400. #define MA_AAUDIO_ALLOW_CAPTURE_BY_NONE 3
  31401. /* Callback results. */
  31402. #define MA_AAUDIO_CALLBACK_RESULT_CONTINUE 0
  31403. #define MA_AAUDIO_CALLBACK_RESULT_STOP 1
  31404. typedef ma_aaudio_data_callback_result_t (* ma_AAudioStream_dataCallback) (ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t numFrames);
  31405. typedef void (* ma_AAudioStream_errorCallback)(ma_AAudioStream *pStream, void *pUserData, ma_aaudio_result_t error);
  31406. typedef ma_aaudio_result_t (* MA_PFN_AAudio_createStreamBuilder) (ma_AAudioStreamBuilder** ppBuilder);
  31407. typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_delete) (ma_AAudioStreamBuilder* pBuilder);
  31408. typedef void (* MA_PFN_AAudioStreamBuilder_setDeviceId) (ma_AAudioStreamBuilder* pBuilder, int32_t deviceId);
  31409. typedef void (* MA_PFN_AAudioStreamBuilder_setDirection) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_direction_t direction);
  31410. typedef void (* MA_PFN_AAudioStreamBuilder_setSharingMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_sharing_mode_t sharingMode);
  31411. typedef void (* MA_PFN_AAudioStreamBuilder_setFormat) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_format_t format);
  31412. typedef void (* MA_PFN_AAudioStreamBuilder_setChannelCount) (ma_AAudioStreamBuilder* pBuilder, int32_t channelCount);
  31413. typedef void (* MA_PFN_AAudioStreamBuilder_setSampleRate) (ma_AAudioStreamBuilder* pBuilder, int32_t sampleRate);
  31414. typedef void (* MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)(ma_AAudioStreamBuilder* pBuilder, int32_t numFrames);
  31415. typedef void (* MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback) (ma_AAudioStreamBuilder* pBuilder, int32_t numFrames);
  31416. typedef void (* MA_PFN_AAudioStreamBuilder_setDataCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_dataCallback callback, void* pUserData);
  31417. typedef void (* MA_PFN_AAudioStreamBuilder_setErrorCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_errorCallback callback, void* pUserData);
  31418. typedef void (* MA_PFN_AAudioStreamBuilder_setPerformanceMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_performance_mode_t mode);
  31419. typedef void (* MA_PFN_AAudioStreamBuilder_setUsage) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_usage_t contentType);
  31420. typedef void (* MA_PFN_AAudioStreamBuilder_setContentType) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_content_type_t contentType);
  31421. typedef void (* MA_PFN_AAudioStreamBuilder_setInputPreset) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_input_preset_t inputPreset);
  31422. typedef void (* MA_PFN_AAudioStreamBuilder_setAllowedCapturePolicy) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_allowed_capture_policy_t policy);
  31423. typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_openStream) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream);
  31424. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_close) (ma_AAudioStream* pStream);
  31425. typedef ma_aaudio_stream_state_t (* MA_PFN_AAudioStream_getState) (ma_AAudioStream* pStream);
  31426. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_waitForStateChange) (ma_AAudioStream* pStream, ma_aaudio_stream_state_t inputState, ma_aaudio_stream_state_t* pNextState, int64_t timeoutInNanoseconds);
  31427. typedef ma_aaudio_format_t (* MA_PFN_AAudioStream_getFormat) (ma_AAudioStream* pStream);
  31428. typedef int32_t (* MA_PFN_AAudioStream_getChannelCount) (ma_AAudioStream* pStream);
  31429. typedef int32_t (* MA_PFN_AAudioStream_getSampleRate) (ma_AAudioStream* pStream);
  31430. typedef int32_t (* MA_PFN_AAudioStream_getBufferCapacityInFrames) (ma_AAudioStream* pStream);
  31431. typedef int32_t (* MA_PFN_AAudioStream_getFramesPerDataCallback) (ma_AAudioStream* pStream);
  31432. typedef int32_t (* MA_PFN_AAudioStream_getFramesPerBurst) (ma_AAudioStream* pStream);
  31433. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStart) (ma_AAudioStream* pStream);
  31434. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStop) (ma_AAudioStream* pStream);
  31435. static ma_result ma_result_from_aaudio(ma_aaudio_result_t resultAA)
  31436. {
  31437. switch (resultAA)
  31438. {
  31439. case MA_AAUDIO_OK: return MA_SUCCESS;
  31440. default: break;
  31441. }
  31442. return MA_ERROR;
  31443. }
  31444. static ma_aaudio_usage_t ma_to_usage__aaudio(ma_aaudio_usage usage)
  31445. {
  31446. switch (usage) {
  31447. case ma_aaudio_usage_media: return MA_AAUDIO_USAGE_MEDIA;
  31448. case ma_aaudio_usage_voice_communication: return MA_AAUDIO_USAGE_VOICE_COMMUNICATION;
  31449. case ma_aaudio_usage_voice_communication_signalling: return MA_AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
  31450. case ma_aaudio_usage_alarm: return MA_AAUDIO_USAGE_ALARM;
  31451. case ma_aaudio_usage_notification: return MA_AAUDIO_USAGE_NOTIFICATION;
  31452. case ma_aaudio_usage_notification_ringtone: return MA_AAUDIO_USAGE_NOTIFICATION_RINGTONE;
  31453. case ma_aaudio_usage_notification_event: return MA_AAUDIO_USAGE_NOTIFICATION_EVENT;
  31454. case ma_aaudio_usage_assistance_accessibility: return MA_AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
  31455. case ma_aaudio_usage_assistance_navigation_guidance: return MA_AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE;
  31456. case ma_aaudio_usage_assistance_sonification: return MA_AAUDIO_USAGE_ASSISTANCE_SONIFICATION;
  31457. case ma_aaudio_usage_game: return MA_AAUDIO_USAGE_GAME;
  31458. case ma_aaudio_usage_assitant: return MA_AAUDIO_USAGE_ASSISTANT;
  31459. case ma_aaudio_usage_emergency: return MA_AAUDIO_SYSTEM_USAGE_EMERGENCY;
  31460. case ma_aaudio_usage_safety: return MA_AAUDIO_SYSTEM_USAGE_SAFETY;
  31461. case ma_aaudio_usage_vehicle_status: return MA_AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS;
  31462. case ma_aaudio_usage_announcement: return MA_AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT;
  31463. default: break;
  31464. }
  31465. return MA_AAUDIO_USAGE_MEDIA;
  31466. }
  31467. static ma_aaudio_content_type_t ma_to_content_type__aaudio(ma_aaudio_content_type contentType)
  31468. {
  31469. switch (contentType) {
  31470. case ma_aaudio_content_type_speech: return MA_AAUDIO_CONTENT_TYPE_SPEECH;
  31471. case ma_aaudio_content_type_music: return MA_AAUDIO_CONTENT_TYPE_MUSIC;
  31472. case ma_aaudio_content_type_movie: return MA_AAUDIO_CONTENT_TYPE_MOVIE;
  31473. case ma_aaudio_content_type_sonification: return MA_AAUDIO_CONTENT_TYPE_SONIFICATION;
  31474. default: break;
  31475. }
  31476. return MA_AAUDIO_CONTENT_TYPE_SPEECH;
  31477. }
  31478. static ma_aaudio_input_preset_t ma_to_input_preset__aaudio(ma_aaudio_input_preset inputPreset)
  31479. {
  31480. switch (inputPreset) {
  31481. case ma_aaudio_input_preset_generic: return MA_AAUDIO_INPUT_PRESET_GENERIC;
  31482. case ma_aaudio_input_preset_camcorder: return MA_AAUDIO_INPUT_PRESET_CAMCORDER;
  31483. case ma_aaudio_input_preset_voice_recognition: return MA_AAUDIO_INPUT_PRESET_VOICE_RECOGNITION;
  31484. case ma_aaudio_input_preset_voice_communication: return MA_AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION;
  31485. case ma_aaudio_input_preset_unprocessed: return MA_AAUDIO_INPUT_PRESET_UNPROCESSED;
  31486. case ma_aaudio_input_preset_voice_performance: return MA_AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE;
  31487. default: break;
  31488. }
  31489. return MA_AAUDIO_INPUT_PRESET_GENERIC;
  31490. }
  31491. static ma_aaudio_allowed_capture_policy_t ma_to_allowed_capture_policy__aaudio(ma_aaudio_allowed_capture_policy allowedCapturePolicy)
  31492. {
  31493. switch (allowedCapturePolicy) {
  31494. case ma_aaudio_allow_capture_by_all: return MA_AAUDIO_ALLOW_CAPTURE_BY_ALL;
  31495. case ma_aaudio_allow_capture_by_system: return MA_AAUDIO_ALLOW_CAPTURE_BY_SYSTEM;
  31496. case ma_aaudio_allow_capture_by_none: return MA_AAUDIO_ALLOW_CAPTURE_BY_NONE;
  31497. default: break;
  31498. }
  31499. return MA_AAUDIO_ALLOW_CAPTURE_BY_ALL;
  31500. }
  31501. static void ma_stream_error_callback__aaudio(ma_AAudioStream* pStream, void* pUserData, ma_aaudio_result_t error)
  31502. {
  31503. ma_result result;
  31504. ma_job job;
  31505. ma_device* pDevice = (ma_device*)pUserData;
  31506. MA_ASSERT(pDevice != NULL);
  31507. (void)error;
  31508. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[AAudio] ERROR CALLBACK: error=%d, AAudioStream_getState()=%d\n", error, ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream));
  31509. /*
  31510. When we get an error, we'll assume that the stream is in an erroneous state and needs to be restarted. From the documentation,
  31511. we cannot do this from the error callback. Therefore we are going to use an event thread for the AAudio backend to do this
  31512. cleanly and safely.
  31513. */
  31514. job = ma_job_init(MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE);
  31515. job.data.device.aaudio.reroute.pDevice = pDevice;
  31516. if (pStream == pDevice->aaudio.pStreamCapture) {
  31517. job.data.device.aaudio.reroute.deviceType = ma_device_type_capture;
  31518. }
  31519. else {
  31520. job.data.device.aaudio.reroute.deviceType = ma_device_type_playback;
  31521. }
  31522. result = ma_device_job_thread_post(&pDevice->pContext->aaudio.jobThread, &job);
  31523. if (result != MA_SUCCESS) {
  31524. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[AAudio] Device Disconnected. Failed to post job for rerouting.\n");
  31525. return;
  31526. }
  31527. }
  31528. static ma_aaudio_data_callback_result_t ma_stream_data_callback_capture__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount)
  31529. {
  31530. ma_device* pDevice = (ma_device*)pUserData;
  31531. MA_ASSERT(pDevice != NULL);
  31532. ma_device_handle_backend_data_callback(pDevice, NULL, pAudioData, frameCount);
  31533. (void)pStream;
  31534. return MA_AAUDIO_CALLBACK_RESULT_CONTINUE;
  31535. }
  31536. static ma_aaudio_data_callback_result_t ma_stream_data_callback_playback__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount)
  31537. {
  31538. ma_device* pDevice = (ma_device*)pUserData;
  31539. MA_ASSERT(pDevice != NULL);
  31540. ma_device_handle_backend_data_callback(pDevice, pAudioData, NULL, frameCount);
  31541. (void)pStream;
  31542. return MA_AAUDIO_CALLBACK_RESULT_CONTINUE;
  31543. }
  31544. static ma_result ma_create_and_configure_AAudioStreamBuilder__aaudio(ma_context* pContext, const ma_device_id* pDeviceID, ma_device_type deviceType, ma_share_mode shareMode, const ma_device_descriptor* pDescriptor, const ma_device_config* pConfig, ma_device* pDevice, ma_AAudioStreamBuilder** ppBuilder)
  31545. {
  31546. ma_AAudioStreamBuilder* pBuilder;
  31547. ma_aaudio_result_t resultAA;
  31548. /* Safety. */
  31549. *ppBuilder = NULL;
  31550. resultAA = ((MA_PFN_AAudio_createStreamBuilder)pContext->aaudio.AAudio_createStreamBuilder)(&pBuilder);
  31551. if (resultAA != MA_AAUDIO_OK) {
  31552. return ma_result_from_aaudio(resultAA);
  31553. }
  31554. if (pDeviceID != NULL) {
  31555. ((MA_PFN_AAudioStreamBuilder_setDeviceId)pContext->aaudio.AAudioStreamBuilder_setDeviceId)(pBuilder, pDeviceID->aaudio);
  31556. }
  31557. ((MA_PFN_AAudioStreamBuilder_setDirection)pContext->aaudio.AAudioStreamBuilder_setDirection)(pBuilder, (deviceType == ma_device_type_playback) ? MA_AAUDIO_DIRECTION_OUTPUT : MA_AAUDIO_DIRECTION_INPUT);
  31558. ((MA_PFN_AAudioStreamBuilder_setSharingMode)pContext->aaudio.AAudioStreamBuilder_setSharingMode)(pBuilder, (shareMode == ma_share_mode_shared) ? MA_AAUDIO_SHARING_MODE_SHARED : MA_AAUDIO_SHARING_MODE_EXCLUSIVE);
  31559. /* If we have a device descriptor make sure we configure the stream builder to take our requested parameters. */
  31560. if (pDescriptor != NULL) {
  31561. MA_ASSERT(pConfig != NULL); /* We must have a device config if we also have a descriptor. The config is required for AAudio specific configuration options. */
  31562. if (pDescriptor->sampleRate != 0) {
  31563. ((MA_PFN_AAudioStreamBuilder_setSampleRate)pContext->aaudio.AAudioStreamBuilder_setSampleRate)(pBuilder, pDescriptor->sampleRate);
  31564. }
  31565. if (deviceType == ma_device_type_capture) {
  31566. if (pDescriptor->channels != 0) {
  31567. ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pDescriptor->channels);
  31568. }
  31569. if (pDescriptor->format != ma_format_unknown) {
  31570. ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pDescriptor->format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT);
  31571. }
  31572. } else {
  31573. if (pDescriptor->channels != 0) {
  31574. ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pDescriptor->channels);
  31575. }
  31576. if (pDescriptor->format != ma_format_unknown) {
  31577. ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pDescriptor->format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT);
  31578. }
  31579. }
  31580. /*
  31581. There have been reports where setting the frames per data callback results in an error
  31582. later on from Android. To address this, I'm experimenting with simply not setting it on
  31583. anything from Android 11 and earlier. Suggestions welcome on how we might be able to make
  31584. this more targetted.
  31585. */
  31586. if (pConfig->aaudio.enableCompatibilityWorkarounds && ma_android_sdk_version() > 30) {
  31587. /*
  31588. AAudio is annoying when it comes to it's buffer calculation stuff because it doesn't let you
  31589. retrieve the actual sample rate until after you've opened the stream. But you need to configure
  31590. the buffer capacity before you open the stream... :/
  31591. To solve, we're just going to assume MA_DEFAULT_SAMPLE_RATE (48000) and move on.
  31592. */
  31593. ma_uint32 bufferCapacityInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, pDescriptor->sampleRate, pConfig->performanceProfile) * pDescriptor->periodCount;
  31594. ((MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames)(pBuilder, bufferCapacityInFrames);
  31595. ((MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback)pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback)(pBuilder, bufferCapacityInFrames / pDescriptor->periodCount);
  31596. }
  31597. if (deviceType == ma_device_type_capture) {
  31598. if (pConfig->aaudio.inputPreset != ma_aaudio_input_preset_default && pContext->aaudio.AAudioStreamBuilder_setInputPreset != NULL) {
  31599. ((MA_PFN_AAudioStreamBuilder_setInputPreset)pContext->aaudio.AAudioStreamBuilder_setInputPreset)(pBuilder, ma_to_input_preset__aaudio(pConfig->aaudio.inputPreset));
  31600. }
  31601. ((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_capture__aaudio, (void*)pDevice);
  31602. } else {
  31603. if (pConfig->aaudio.usage != ma_aaudio_usage_default && pContext->aaudio.AAudioStreamBuilder_setUsage != NULL) {
  31604. ((MA_PFN_AAudioStreamBuilder_setUsage)pContext->aaudio.AAudioStreamBuilder_setUsage)(pBuilder, ma_to_usage__aaudio(pConfig->aaudio.usage));
  31605. }
  31606. if (pConfig->aaudio.contentType != ma_aaudio_content_type_default && pContext->aaudio.AAudioStreamBuilder_setContentType != NULL) {
  31607. ((MA_PFN_AAudioStreamBuilder_setContentType)pContext->aaudio.AAudioStreamBuilder_setContentType)(pBuilder, ma_to_content_type__aaudio(pConfig->aaudio.contentType));
  31608. }
  31609. if (pConfig->aaudio.allowedCapturePolicy != ma_aaudio_allow_capture_default && pContext->aaudio.AAudioStreamBuilder_setAllowedCapturePolicy != NULL) {
  31610. ((MA_PFN_AAudioStreamBuilder_setAllowedCapturePolicy)pContext->aaudio.AAudioStreamBuilder_setAllowedCapturePolicy)(pBuilder, ma_to_allowed_capture_policy__aaudio(pConfig->aaudio.allowedCapturePolicy));
  31611. }
  31612. ((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_playback__aaudio, (void*)pDevice);
  31613. }
  31614. /* Not sure how this affects things, but since there's a mapping between miniaudio's performance profiles and AAudio's performance modes, let go ahead and set it. */
  31615. ((MA_PFN_AAudioStreamBuilder_setPerformanceMode)pContext->aaudio.AAudioStreamBuilder_setPerformanceMode)(pBuilder, (pConfig->performanceProfile == ma_performance_profile_low_latency) ? MA_AAUDIO_PERFORMANCE_MODE_LOW_LATENCY : MA_AAUDIO_PERFORMANCE_MODE_NONE);
  31616. /* We need to set an error callback to detect device changes. */
  31617. if (pDevice != NULL) { /* <-- pDevice should never be null if pDescriptor is not null, which is always the case if we hit this branch. Check anyway for safety. */
  31618. ((MA_PFN_AAudioStreamBuilder_setErrorCallback)pContext->aaudio.AAudioStreamBuilder_setErrorCallback)(pBuilder, ma_stream_error_callback__aaudio, (void*)pDevice);
  31619. }
  31620. }
  31621. *ppBuilder = pBuilder;
  31622. return MA_SUCCESS;
  31623. }
  31624. static ma_result ma_open_stream_and_close_builder__aaudio(ma_context* pContext, ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream)
  31625. {
  31626. ma_result result;
  31627. result = ma_result_from_aaudio(((MA_PFN_AAudioStreamBuilder_openStream)pContext->aaudio.AAudioStreamBuilder_openStream)(pBuilder, ppStream));
  31628. ((MA_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder);
  31629. return result;
  31630. }
  31631. static ma_result ma_open_stream_basic__aaudio(ma_context* pContext, const ma_device_id* pDeviceID, ma_device_type deviceType, ma_share_mode shareMode, ma_AAudioStream** ppStream)
  31632. {
  31633. ma_result result;
  31634. ma_AAudioStreamBuilder* pBuilder;
  31635. *ppStream = NULL;
  31636. result = ma_create_and_configure_AAudioStreamBuilder__aaudio(pContext, pDeviceID, deviceType, shareMode, NULL, NULL, NULL, &pBuilder);
  31637. if (result != MA_SUCCESS) {
  31638. return result;
  31639. }
  31640. return ma_open_stream_and_close_builder__aaudio(pContext, pBuilder, ppStream);
  31641. }
  31642. static ma_result ma_open_stream__aaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_type deviceType, const ma_device_descriptor* pDescriptor, ma_AAudioStream** ppStream)
  31643. {
  31644. ma_result result;
  31645. ma_AAudioStreamBuilder* pBuilder;
  31646. MA_ASSERT(pDevice != NULL);
  31647. MA_ASSERT(pDescriptor != NULL);
  31648. MA_ASSERT(deviceType != ma_device_type_duplex); /* This function should not be called for a full-duplex device type. */
  31649. *ppStream = NULL;
  31650. result = ma_create_and_configure_AAudioStreamBuilder__aaudio(pDevice->pContext, pDescriptor->pDeviceID, deviceType, pDescriptor->shareMode, pDescriptor, pConfig, pDevice, &pBuilder);
  31651. if (result != MA_SUCCESS) {
  31652. return result;
  31653. }
  31654. return ma_open_stream_and_close_builder__aaudio(pDevice->pContext, pBuilder, ppStream);
  31655. }
  31656. static ma_result ma_close_stream__aaudio(ma_context* pContext, ma_AAudioStream* pStream)
  31657. {
  31658. return ma_result_from_aaudio(((MA_PFN_AAudioStream_close)pContext->aaudio.AAudioStream_close)(pStream));
  31659. }
  31660. static ma_bool32 ma_has_default_device__aaudio(ma_context* pContext, ma_device_type deviceType)
  31661. {
  31662. /* The only way to know this is to try creating a stream. */
  31663. ma_AAudioStream* pStream;
  31664. ma_result result = ma_open_stream_basic__aaudio(pContext, NULL, deviceType, ma_share_mode_shared, &pStream);
  31665. if (result != MA_SUCCESS) {
  31666. return MA_FALSE;
  31667. }
  31668. ma_close_stream__aaudio(pContext, pStream);
  31669. return MA_TRUE;
  31670. }
  31671. static ma_result ma_wait_for_simple_state_transition__aaudio(ma_context* pContext, ma_AAudioStream* pStream, ma_aaudio_stream_state_t oldState, ma_aaudio_stream_state_t newState)
  31672. {
  31673. ma_aaudio_stream_state_t actualNewState;
  31674. ma_aaudio_result_t resultAA = ((MA_PFN_AAudioStream_waitForStateChange)pContext->aaudio.AAudioStream_waitForStateChange)(pStream, oldState, &actualNewState, 5000000000); /* 5 second timeout. */
  31675. if (resultAA != MA_AAUDIO_OK) {
  31676. return ma_result_from_aaudio(resultAA);
  31677. }
  31678. if (newState != actualNewState) {
  31679. return MA_ERROR; /* Failed to transition into the expected state. */
  31680. }
  31681. return MA_SUCCESS;
  31682. }
  31683. static ma_result ma_context_enumerate_devices__aaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  31684. {
  31685. ma_bool32 cbResult = MA_TRUE;
  31686. MA_ASSERT(pContext != NULL);
  31687. MA_ASSERT(callback != NULL);
  31688. /* Unfortunately AAudio does not have an enumeration API. Therefore I'm only going to report default devices, but only if it can instantiate a stream. */
  31689. /* Playback. */
  31690. if (cbResult) {
  31691. ma_device_info deviceInfo;
  31692. MA_ZERO_OBJECT(&deviceInfo);
  31693. deviceInfo.id.aaudio = MA_AAUDIO_UNSPECIFIED;
  31694. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  31695. if (ma_has_default_device__aaudio(pContext, ma_device_type_playback)) {
  31696. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  31697. }
  31698. }
  31699. /* Capture. */
  31700. if (cbResult) {
  31701. ma_device_info deviceInfo;
  31702. MA_ZERO_OBJECT(&deviceInfo);
  31703. deviceInfo.id.aaudio = MA_AAUDIO_UNSPECIFIED;
  31704. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  31705. if (ma_has_default_device__aaudio(pContext, ma_device_type_capture)) {
  31706. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  31707. }
  31708. }
  31709. return MA_SUCCESS;
  31710. }
  31711. static void ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(ma_context* pContext, ma_AAudioStream* pStream, ma_format format, ma_uint32 flags, ma_device_info* pDeviceInfo)
  31712. {
  31713. MA_ASSERT(pContext != NULL);
  31714. MA_ASSERT(pStream != NULL);
  31715. MA_ASSERT(pDeviceInfo != NULL);
  31716. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  31717. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)(pStream);
  31718. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)(pStream);
  31719. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags;
  31720. pDeviceInfo->nativeDataFormatCount += 1;
  31721. }
  31722. static void ma_context_add_native_data_format_from_AAudioStream__aaudio(ma_context* pContext, ma_AAudioStream* pStream, ma_uint32 flags, ma_device_info* pDeviceInfo)
  31723. {
  31724. /* AAudio supports s16 and f32. */
  31725. ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(pContext, pStream, ma_format_f32, flags, pDeviceInfo);
  31726. ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(pContext, pStream, ma_format_s16, flags, pDeviceInfo);
  31727. }
  31728. static ma_result ma_context_get_device_info__aaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  31729. {
  31730. ma_AAudioStream* pStream;
  31731. ma_result result;
  31732. MA_ASSERT(pContext != NULL);
  31733. /* ID */
  31734. if (pDeviceID != NULL) {
  31735. pDeviceInfo->id.aaudio = pDeviceID->aaudio;
  31736. } else {
  31737. pDeviceInfo->id.aaudio = MA_AAUDIO_UNSPECIFIED;
  31738. }
  31739. /* Name */
  31740. if (deviceType == ma_device_type_playback) {
  31741. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  31742. } else {
  31743. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  31744. }
  31745. pDeviceInfo->nativeDataFormatCount = 0;
  31746. /* We'll need to open the device to get accurate sample rate and channel count information. */
  31747. result = ma_open_stream_basic__aaudio(pContext, pDeviceID, deviceType, ma_share_mode_shared, &pStream);
  31748. if (result != MA_SUCCESS) {
  31749. return result;
  31750. }
  31751. ma_context_add_native_data_format_from_AAudioStream__aaudio(pContext, pStream, 0, pDeviceInfo);
  31752. ma_close_stream__aaudio(pContext, pStream);
  31753. pStream = NULL;
  31754. return MA_SUCCESS;
  31755. }
  31756. static ma_result ma_device_uninit__aaudio(ma_device* pDevice)
  31757. {
  31758. MA_ASSERT(pDevice != NULL);
  31759. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31760. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31761. pDevice->aaudio.pStreamCapture = NULL;
  31762. }
  31763. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  31764. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  31765. pDevice->aaudio.pStreamPlayback = NULL;
  31766. }
  31767. return MA_SUCCESS;
  31768. }
  31769. static ma_result ma_device_init_by_type__aaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_type deviceType, ma_device_descriptor* pDescriptor, ma_AAudioStream** ppStream)
  31770. {
  31771. ma_result result;
  31772. int32_t bufferCapacityInFrames;
  31773. int32_t framesPerDataCallback;
  31774. ma_AAudioStream* pStream;
  31775. MA_ASSERT(pDevice != NULL);
  31776. MA_ASSERT(pConfig != NULL);
  31777. MA_ASSERT(pDescriptor != NULL);
  31778. *ppStream = NULL; /* Safety. */
  31779. /* First step is to open the stream. From there we'll be able to extract the internal configuration. */
  31780. result = ma_open_stream__aaudio(pDevice, pConfig, deviceType, pDescriptor, &pStream);
  31781. if (result != MA_SUCCESS) {
  31782. return result; /* Failed to open the AAudio stream. */
  31783. }
  31784. /* Now extract the internal configuration. */
  31785. pDescriptor->format = (((MA_PFN_AAudioStream_getFormat)pDevice->pContext->aaudio.AAudioStream_getFormat)(pStream) == MA_AAUDIO_FORMAT_PCM_I16) ? ma_format_s16 : ma_format_f32;
  31786. pDescriptor->channels = ((MA_PFN_AAudioStream_getChannelCount)pDevice->pContext->aaudio.AAudioStream_getChannelCount)(pStream);
  31787. pDescriptor->sampleRate = ((MA_PFN_AAudioStream_getSampleRate)pDevice->pContext->aaudio.AAudioStream_getSampleRate)(pStream);
  31788. /* For the channel map we need to be sure we don't overflow any buffers. */
  31789. if (pDescriptor->channels <= MA_MAX_CHANNELS) {
  31790. ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), pDescriptor->channels); /* <-- Cannot find info on channel order, so assuming a default. */
  31791. } else {
  31792. ma_channel_map_init_blank(pDescriptor->channelMap, MA_MAX_CHANNELS); /* Too many channels. Use a blank channel map. */
  31793. }
  31794. bufferCapacityInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pDevice->pContext->aaudio.AAudioStream_getBufferCapacityInFrames)(pStream);
  31795. framesPerDataCallback = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pDevice->pContext->aaudio.AAudioStream_getFramesPerDataCallback)(pStream);
  31796. if (framesPerDataCallback > 0) {
  31797. pDescriptor->periodSizeInFrames = framesPerDataCallback;
  31798. pDescriptor->periodCount = bufferCapacityInFrames / framesPerDataCallback;
  31799. } else {
  31800. pDescriptor->periodSizeInFrames = bufferCapacityInFrames;
  31801. pDescriptor->periodCount = 1;
  31802. }
  31803. *ppStream = pStream;
  31804. return MA_SUCCESS;
  31805. }
  31806. static ma_result ma_device_init__aaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  31807. {
  31808. ma_result result;
  31809. MA_ASSERT(pDevice != NULL);
  31810. if (pConfig->deviceType == ma_device_type_loopback) {
  31811. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  31812. }
  31813. pDevice->aaudio.usage = pConfig->aaudio.usage;
  31814. pDevice->aaudio.contentType = pConfig->aaudio.contentType;
  31815. pDevice->aaudio.inputPreset = pConfig->aaudio.inputPreset;
  31816. pDevice->aaudio.allowedCapturePolicy = pConfig->aaudio.allowedCapturePolicy;
  31817. pDevice->aaudio.noAutoStartAfterReroute = pConfig->aaudio.noAutoStartAfterReroute;
  31818. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  31819. result = ma_device_init_by_type__aaudio(pDevice, pConfig, ma_device_type_capture, pDescriptorCapture, (ma_AAudioStream**)&pDevice->aaudio.pStreamCapture);
  31820. if (result != MA_SUCCESS) {
  31821. return result;
  31822. }
  31823. }
  31824. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  31825. result = ma_device_init_by_type__aaudio(pDevice, pConfig, ma_device_type_playback, pDescriptorPlayback, (ma_AAudioStream**)&pDevice->aaudio.pStreamPlayback);
  31826. if (result != MA_SUCCESS) {
  31827. return result;
  31828. }
  31829. }
  31830. return MA_SUCCESS;
  31831. }
  31832. static ma_result ma_device_start_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream)
  31833. {
  31834. ma_aaudio_result_t resultAA;
  31835. ma_aaudio_stream_state_t currentState;
  31836. MA_ASSERT(pDevice != NULL);
  31837. resultAA = ((MA_PFN_AAudioStream_requestStart)pDevice->pContext->aaudio.AAudioStream_requestStart)(pStream);
  31838. if (resultAA != MA_AAUDIO_OK) {
  31839. return ma_result_from_aaudio(resultAA);
  31840. }
  31841. /* Do we actually need to wait for the device to transition into it's started state? */
  31842. /* The device should be in either a starting or started state. If it's not set to started we need to wait for it to transition. It should go from starting to started. */
  31843. currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
  31844. if (currentState != MA_AAUDIO_STREAM_STATE_STARTED) {
  31845. ma_result result;
  31846. if (currentState != MA_AAUDIO_STREAM_STATE_STARTING) {
  31847. return MA_ERROR; /* Expecting the stream to be a starting or started state. */
  31848. }
  31849. result = ma_wait_for_simple_state_transition__aaudio(pDevice->pContext, pStream, currentState, MA_AAUDIO_STREAM_STATE_STARTED);
  31850. if (result != MA_SUCCESS) {
  31851. return result;
  31852. }
  31853. }
  31854. return MA_SUCCESS;
  31855. }
  31856. static ma_result ma_device_stop_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream)
  31857. {
  31858. ma_aaudio_result_t resultAA;
  31859. ma_aaudio_stream_state_t currentState;
  31860. MA_ASSERT(pDevice != NULL);
  31861. /*
  31862. From the AAudio documentation:
  31863. The stream will stop after all of the data currently buffered has been played.
  31864. This maps with miniaudio's requirement that device's be drained which means we don't need to implement any draining logic.
  31865. */
  31866. currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
  31867. if (currentState == MA_AAUDIO_STREAM_STATE_DISCONNECTED) {
  31868. return MA_SUCCESS; /* The device is disconnected. Don't try stopping it. */
  31869. }
  31870. resultAA = ((MA_PFN_AAudioStream_requestStop)pDevice->pContext->aaudio.AAudioStream_requestStop)(pStream);
  31871. if (resultAA != MA_AAUDIO_OK) {
  31872. return ma_result_from_aaudio(resultAA);
  31873. }
  31874. /* The device should be in either a stopping or stopped state. If it's not set to started we need to wait for it to transition. It should go from stopping to stopped. */
  31875. currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
  31876. if (currentState != MA_AAUDIO_STREAM_STATE_STOPPED) {
  31877. ma_result result;
  31878. if (currentState != MA_AAUDIO_STREAM_STATE_STOPPING) {
  31879. return MA_ERROR; /* Expecting the stream to be a stopping or stopped state. */
  31880. }
  31881. result = ma_wait_for_simple_state_transition__aaudio(pDevice->pContext, pStream, currentState, MA_AAUDIO_STREAM_STATE_STOPPED);
  31882. if (result != MA_SUCCESS) {
  31883. return result;
  31884. }
  31885. }
  31886. return MA_SUCCESS;
  31887. }
  31888. static ma_result ma_device_start__aaudio(ma_device* pDevice)
  31889. {
  31890. MA_ASSERT(pDevice != NULL);
  31891. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31892. ma_result result = ma_device_start_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31893. if (result != MA_SUCCESS) {
  31894. return result;
  31895. }
  31896. }
  31897. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  31898. ma_result result = ma_device_start_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  31899. if (result != MA_SUCCESS) {
  31900. if (pDevice->type == ma_device_type_duplex) {
  31901. ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31902. }
  31903. return result;
  31904. }
  31905. }
  31906. return MA_SUCCESS;
  31907. }
  31908. static ma_result ma_device_stop__aaudio(ma_device* pDevice)
  31909. {
  31910. MA_ASSERT(pDevice != NULL);
  31911. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31912. ma_result result = ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31913. if (result != MA_SUCCESS) {
  31914. return result;
  31915. }
  31916. }
  31917. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  31918. ma_result result = ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  31919. if (result != MA_SUCCESS) {
  31920. return result;
  31921. }
  31922. }
  31923. ma_device__on_notification_stopped(pDevice);
  31924. return MA_SUCCESS;
  31925. }
  31926. static ma_result ma_device_reinit__aaudio(ma_device* pDevice, ma_device_type deviceType)
  31927. {
  31928. ma_result result;
  31929. MA_ASSERT(pDevice != NULL);
  31930. /* The first thing to do is close the streams. */
  31931. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex) {
  31932. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31933. pDevice->aaudio.pStreamCapture = NULL;
  31934. }
  31935. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  31936. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  31937. pDevice->aaudio.pStreamPlayback = NULL;
  31938. }
  31939. /* Now we need to reinitialize each streams. The hardest part with this is just filling output the config and descriptors. */
  31940. {
  31941. ma_device_config deviceConfig;
  31942. ma_device_descriptor descriptorPlayback;
  31943. ma_device_descriptor descriptorCapture;
  31944. deviceConfig = ma_device_config_init(deviceType);
  31945. deviceConfig.playback.pDeviceID = NULL; /* Only doing rerouting with default devices. */
  31946. deviceConfig.playback.shareMode = pDevice->playback.shareMode;
  31947. deviceConfig.playback.format = pDevice->playback.format;
  31948. deviceConfig.playback.channels = pDevice->playback.channels;
  31949. deviceConfig.capture.pDeviceID = NULL; /* Only doing rerouting with default devices. */
  31950. deviceConfig.capture.shareMode = pDevice->capture.shareMode;
  31951. deviceConfig.capture.format = pDevice->capture.format;
  31952. deviceConfig.capture.channels = pDevice->capture.channels;
  31953. deviceConfig.sampleRate = pDevice->sampleRate;
  31954. deviceConfig.aaudio.usage = pDevice->aaudio.usage;
  31955. deviceConfig.aaudio.contentType = pDevice->aaudio.contentType;
  31956. deviceConfig.aaudio.inputPreset = pDevice->aaudio.inputPreset;
  31957. deviceConfig.aaudio.allowedCapturePolicy = pDevice->aaudio.allowedCapturePolicy;
  31958. deviceConfig.aaudio.noAutoStartAfterReroute = pDevice->aaudio.noAutoStartAfterReroute;
  31959. deviceConfig.periods = 1;
  31960. /* Try to get an accurate period size. */
  31961. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  31962. deviceConfig.periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames;
  31963. } else {
  31964. deviceConfig.periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames;
  31965. }
  31966. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  31967. descriptorCapture.pDeviceID = deviceConfig.capture.pDeviceID;
  31968. descriptorCapture.shareMode = deviceConfig.capture.shareMode;
  31969. descriptorCapture.format = deviceConfig.capture.format;
  31970. descriptorCapture.channels = deviceConfig.capture.channels;
  31971. descriptorCapture.sampleRate = deviceConfig.sampleRate;
  31972. descriptorCapture.periodSizeInFrames = deviceConfig.periodSizeInFrames;
  31973. descriptorCapture.periodCount = deviceConfig.periods;
  31974. }
  31975. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  31976. descriptorPlayback.pDeviceID = deviceConfig.playback.pDeviceID;
  31977. descriptorPlayback.shareMode = deviceConfig.playback.shareMode;
  31978. descriptorPlayback.format = deviceConfig.playback.format;
  31979. descriptorPlayback.channels = deviceConfig.playback.channels;
  31980. descriptorPlayback.sampleRate = deviceConfig.sampleRate;
  31981. descriptorPlayback.periodSizeInFrames = deviceConfig.periodSizeInFrames;
  31982. descriptorPlayback.periodCount = deviceConfig.periods;
  31983. }
  31984. result = ma_device_init__aaudio(pDevice, &deviceConfig, &descriptorPlayback, &descriptorCapture);
  31985. if (result != MA_SUCCESS) {
  31986. return result;
  31987. }
  31988. result = ma_device_post_init(pDevice, deviceType, &descriptorPlayback, &descriptorCapture);
  31989. if (result != MA_SUCCESS) {
  31990. ma_device_uninit__aaudio(pDevice);
  31991. return result;
  31992. }
  31993. /* We'll only ever do this in response to a reroute. */
  31994. ma_device__on_notification_rerouted(pDevice);
  31995. /* If the device is started, start the streams. Maybe make this configurable? */
  31996. if (ma_device_get_state(pDevice) == ma_device_state_started) {
  31997. if (pDevice->aaudio.noAutoStartAfterReroute == MA_FALSE) {
  31998. ma_device_start__aaudio(pDevice);
  31999. } else {
  32000. ma_device_stop(pDevice); /* Do a full device stop so we set internal state correctly. */
  32001. }
  32002. }
  32003. return MA_SUCCESS;
  32004. }
  32005. }
  32006. static ma_result ma_device_get_info__aaudio(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo)
  32007. {
  32008. ma_AAudioStream* pStream = NULL;
  32009. MA_ASSERT(pDevice != NULL);
  32010. MA_ASSERT(type != ma_device_type_duplex);
  32011. MA_ASSERT(pDeviceInfo != NULL);
  32012. if (type == ma_device_type_playback) {
  32013. pStream = (ma_AAudioStream*)pDevice->aaudio.pStreamCapture;
  32014. pDeviceInfo->id.aaudio = pDevice->capture.id.aaudio;
  32015. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); /* Only supporting default devices. */
  32016. }
  32017. if (type == ma_device_type_capture) {
  32018. pStream = (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback;
  32019. pDeviceInfo->id.aaudio = pDevice->playback.id.aaudio;
  32020. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); /* Only supporting default devices. */
  32021. }
  32022. /* Safety. Should never happen. */
  32023. if (pStream == NULL) {
  32024. return MA_INVALID_OPERATION;
  32025. }
  32026. pDeviceInfo->nativeDataFormatCount = 0;
  32027. ma_context_add_native_data_format_from_AAudioStream__aaudio(pDevice->pContext, pStream, 0, pDeviceInfo);
  32028. return MA_SUCCESS;
  32029. }
  32030. static ma_result ma_context_uninit__aaudio(ma_context* pContext)
  32031. {
  32032. MA_ASSERT(pContext != NULL);
  32033. MA_ASSERT(pContext->backend == ma_backend_aaudio);
  32034. ma_device_job_thread_uninit(&pContext->aaudio.jobThread, &pContext->allocationCallbacks);
  32035. ma_dlclose(pContext, pContext->aaudio.hAAudio);
  32036. pContext->aaudio.hAAudio = NULL;
  32037. return MA_SUCCESS;
  32038. }
  32039. static ma_result ma_context_init__aaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  32040. {
  32041. size_t i;
  32042. const char* libNames[] = {
  32043. "libaaudio.so"
  32044. };
  32045. for (i = 0; i < ma_countof(libNames); ++i) {
  32046. pContext->aaudio.hAAudio = ma_dlopen(pContext, libNames[i]);
  32047. if (pContext->aaudio.hAAudio != NULL) {
  32048. break;
  32049. }
  32050. }
  32051. if (pContext->aaudio.hAAudio == NULL) {
  32052. return MA_FAILED_TO_INIT_BACKEND;
  32053. }
  32054. pContext->aaudio.AAudio_createStreamBuilder = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudio_createStreamBuilder");
  32055. pContext->aaudio.AAudioStreamBuilder_delete = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_delete");
  32056. pContext->aaudio.AAudioStreamBuilder_setDeviceId = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDeviceId");
  32057. pContext->aaudio.AAudioStreamBuilder_setDirection = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDirection");
  32058. pContext->aaudio.AAudioStreamBuilder_setSharingMode = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSharingMode");
  32059. pContext->aaudio.AAudioStreamBuilder_setFormat = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFormat");
  32060. pContext->aaudio.AAudioStreamBuilder_setChannelCount = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setChannelCount");
  32061. pContext->aaudio.AAudioStreamBuilder_setSampleRate = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSampleRate");
  32062. pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setBufferCapacityInFrames");
  32063. pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFramesPerDataCallback");
  32064. pContext->aaudio.AAudioStreamBuilder_setDataCallback = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDataCallback");
  32065. pContext->aaudio.AAudioStreamBuilder_setErrorCallback = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setErrorCallback");
  32066. pContext->aaudio.AAudioStreamBuilder_setPerformanceMode = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setPerformanceMode");
  32067. pContext->aaudio.AAudioStreamBuilder_setUsage = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setUsage");
  32068. pContext->aaudio.AAudioStreamBuilder_setContentType = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setContentType");
  32069. pContext->aaudio.AAudioStreamBuilder_setInputPreset = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setInputPreset");
  32070. pContext->aaudio.AAudioStreamBuilder_setAllowedCapturePolicy = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setAllowedCapturePolicy");
  32071. pContext->aaudio.AAudioStreamBuilder_openStream = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_openStream");
  32072. pContext->aaudio.AAudioStream_close = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_close");
  32073. pContext->aaudio.AAudioStream_getState = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getState");
  32074. pContext->aaudio.AAudioStream_waitForStateChange = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_waitForStateChange");
  32075. pContext->aaudio.AAudioStream_getFormat = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getFormat");
  32076. pContext->aaudio.AAudioStream_getChannelCount = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getChannelCount");
  32077. pContext->aaudio.AAudioStream_getSampleRate = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getSampleRate");
  32078. pContext->aaudio.AAudioStream_getBufferCapacityInFrames = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getBufferCapacityInFrames");
  32079. pContext->aaudio.AAudioStream_getFramesPerDataCallback = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getFramesPerDataCallback");
  32080. pContext->aaudio.AAudioStream_getFramesPerBurst = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getFramesPerBurst");
  32081. pContext->aaudio.AAudioStream_requestStart = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_requestStart");
  32082. pContext->aaudio.AAudioStream_requestStop = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_requestStop");
  32083. pCallbacks->onContextInit = ma_context_init__aaudio;
  32084. pCallbacks->onContextUninit = ma_context_uninit__aaudio;
  32085. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__aaudio;
  32086. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__aaudio;
  32087. pCallbacks->onDeviceInit = ma_device_init__aaudio;
  32088. pCallbacks->onDeviceUninit = ma_device_uninit__aaudio;
  32089. pCallbacks->onDeviceStart = ma_device_start__aaudio;
  32090. pCallbacks->onDeviceStop = ma_device_stop__aaudio;
  32091. pCallbacks->onDeviceRead = NULL; /* Not used because AAudio is asynchronous. */
  32092. pCallbacks->onDeviceWrite = NULL; /* Not used because AAudio is asynchronous. */
  32093. pCallbacks->onDeviceDataLoop = NULL; /* Not used because AAudio is asynchronous. */
  32094. pCallbacks->onDeviceGetInfo = ma_device_get_info__aaudio;
  32095. /* We need a job thread so we can deal with rerouting. */
  32096. {
  32097. ma_result result;
  32098. ma_device_job_thread_config jobThreadConfig;
  32099. jobThreadConfig = ma_device_job_thread_config_init();
  32100. result = ma_device_job_thread_init(&jobThreadConfig, &pContext->allocationCallbacks, &pContext->aaudio.jobThread);
  32101. if (result != MA_SUCCESS) {
  32102. ma_dlclose(pContext, pContext->aaudio.hAAudio);
  32103. pContext->aaudio.hAAudio = NULL;
  32104. return result;
  32105. }
  32106. }
  32107. (void)pConfig;
  32108. return MA_SUCCESS;
  32109. }
  32110. static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob)
  32111. {
  32112. ma_device* pDevice;
  32113. MA_ASSERT(pJob != NULL);
  32114. pDevice = (ma_device*)pJob->data.device.aaudio.reroute.pDevice;
  32115. MA_ASSERT(pDevice != NULL);
  32116. /* Here is where we need to reroute the device. To do this we need to uninitialize the stream and reinitialize it. */
  32117. return ma_device_reinit__aaudio(pDevice, (ma_device_type)pJob->data.device.aaudio.reroute.deviceType);
  32118. }
  32119. #else
  32120. /* Getting here means there is no AAudio backend so we need a no-op job implementation. */
  32121. static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob)
  32122. {
  32123. return ma_job_process__noop(pJob);
  32124. }
  32125. #endif /* AAudio */
  32126. /******************************************************************************
  32127. OpenSL|ES Backend
  32128. ******************************************************************************/
  32129. #ifdef MA_HAS_OPENSL
  32130. #include <SLES/OpenSLES.h>
  32131. #ifdef MA_ANDROID
  32132. #include <SLES/OpenSLES_Android.h>
  32133. #endif
  32134. typedef SLresult (SLAPIENTRY * ma_slCreateEngine_proc)(SLObjectItf* pEngine, SLuint32 numOptions, SLEngineOption* pEngineOptions, SLuint32 numInterfaces, SLInterfaceID* pInterfaceIds, SLboolean* pInterfaceRequired);
  32135. /* OpenSL|ES has one-per-application objects :( */
  32136. static SLObjectItf g_maEngineObjectSL = NULL;
  32137. static SLEngineItf g_maEngineSL = NULL;
  32138. static ma_uint32 g_maOpenSLInitCounter = 0;
  32139. static ma_spinlock g_maOpenSLSpinlock = 0; /* For init/uninit. */
  32140. #define MA_OPENSL_OBJ(p) (*((SLObjectItf)(p)))
  32141. #define MA_OPENSL_OUTPUTMIX(p) (*((SLOutputMixItf)(p)))
  32142. #define MA_OPENSL_PLAY(p) (*((SLPlayItf)(p)))
  32143. #define MA_OPENSL_RECORD(p) (*((SLRecordItf)(p)))
  32144. #ifdef MA_ANDROID
  32145. #define MA_OPENSL_BUFFERQUEUE(p) (*((SLAndroidSimpleBufferQueueItf)(p)))
  32146. #else
  32147. #define MA_OPENSL_BUFFERQUEUE(p) (*((SLBufferQueueItf)(p)))
  32148. #endif
  32149. static ma_result ma_result_from_OpenSL(SLuint32 result)
  32150. {
  32151. switch (result)
  32152. {
  32153. case SL_RESULT_SUCCESS: return MA_SUCCESS;
  32154. case SL_RESULT_PRECONDITIONS_VIOLATED: return MA_ERROR;
  32155. case SL_RESULT_PARAMETER_INVALID: return MA_INVALID_ARGS;
  32156. case SL_RESULT_MEMORY_FAILURE: return MA_OUT_OF_MEMORY;
  32157. case SL_RESULT_RESOURCE_ERROR: return MA_INVALID_DATA;
  32158. case SL_RESULT_RESOURCE_LOST: return MA_ERROR;
  32159. case SL_RESULT_IO_ERROR: return MA_IO_ERROR;
  32160. case SL_RESULT_BUFFER_INSUFFICIENT: return MA_NO_SPACE;
  32161. case SL_RESULT_CONTENT_CORRUPTED: return MA_INVALID_DATA;
  32162. case SL_RESULT_CONTENT_UNSUPPORTED: return MA_FORMAT_NOT_SUPPORTED;
  32163. case SL_RESULT_CONTENT_NOT_FOUND: return MA_ERROR;
  32164. case SL_RESULT_PERMISSION_DENIED: return MA_ACCESS_DENIED;
  32165. case SL_RESULT_FEATURE_UNSUPPORTED: return MA_NOT_IMPLEMENTED;
  32166. case SL_RESULT_INTERNAL_ERROR: return MA_ERROR;
  32167. case SL_RESULT_UNKNOWN_ERROR: return MA_ERROR;
  32168. case SL_RESULT_OPERATION_ABORTED: return MA_ERROR;
  32169. case SL_RESULT_CONTROL_LOST: return MA_ERROR;
  32170. default: return MA_ERROR;
  32171. }
  32172. }
  32173. /* Converts an individual OpenSL-style channel identifier (SL_SPEAKER_FRONT_LEFT, etc.) to miniaudio. */
  32174. static ma_uint8 ma_channel_id_to_ma__opensl(SLuint32 id)
  32175. {
  32176. switch (id)
  32177. {
  32178. case SL_SPEAKER_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
  32179. case SL_SPEAKER_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
  32180. case SL_SPEAKER_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
  32181. case SL_SPEAKER_LOW_FREQUENCY: return MA_CHANNEL_LFE;
  32182. case SL_SPEAKER_BACK_LEFT: return MA_CHANNEL_BACK_LEFT;
  32183. case SL_SPEAKER_BACK_RIGHT: return MA_CHANNEL_BACK_RIGHT;
  32184. case SL_SPEAKER_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
  32185. case SL_SPEAKER_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  32186. case SL_SPEAKER_BACK_CENTER: return MA_CHANNEL_BACK_CENTER;
  32187. case SL_SPEAKER_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
  32188. case SL_SPEAKER_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
  32189. case SL_SPEAKER_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
  32190. case SL_SPEAKER_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
  32191. case SL_SPEAKER_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
  32192. case SL_SPEAKER_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
  32193. case SL_SPEAKER_TOP_BACK_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
  32194. case SL_SPEAKER_TOP_BACK_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
  32195. case SL_SPEAKER_TOP_BACK_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
  32196. default: return 0;
  32197. }
  32198. }
  32199. /* Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to OpenSL-style. */
  32200. static SLuint32 ma_channel_id_to_opensl(ma_uint8 id)
  32201. {
  32202. switch (id)
  32203. {
  32204. case MA_CHANNEL_MONO: return SL_SPEAKER_FRONT_CENTER;
  32205. case MA_CHANNEL_FRONT_LEFT: return SL_SPEAKER_FRONT_LEFT;
  32206. case MA_CHANNEL_FRONT_RIGHT: return SL_SPEAKER_FRONT_RIGHT;
  32207. case MA_CHANNEL_FRONT_CENTER: return SL_SPEAKER_FRONT_CENTER;
  32208. case MA_CHANNEL_LFE: return SL_SPEAKER_LOW_FREQUENCY;
  32209. case MA_CHANNEL_BACK_LEFT: return SL_SPEAKER_BACK_LEFT;
  32210. case MA_CHANNEL_BACK_RIGHT: return SL_SPEAKER_BACK_RIGHT;
  32211. case MA_CHANNEL_FRONT_LEFT_CENTER: return SL_SPEAKER_FRONT_LEFT_OF_CENTER;
  32212. case MA_CHANNEL_FRONT_RIGHT_CENTER: return SL_SPEAKER_FRONT_RIGHT_OF_CENTER;
  32213. case MA_CHANNEL_BACK_CENTER: return SL_SPEAKER_BACK_CENTER;
  32214. case MA_CHANNEL_SIDE_LEFT: return SL_SPEAKER_SIDE_LEFT;
  32215. case MA_CHANNEL_SIDE_RIGHT: return SL_SPEAKER_SIDE_RIGHT;
  32216. case MA_CHANNEL_TOP_CENTER: return SL_SPEAKER_TOP_CENTER;
  32217. case MA_CHANNEL_TOP_FRONT_LEFT: return SL_SPEAKER_TOP_FRONT_LEFT;
  32218. case MA_CHANNEL_TOP_FRONT_CENTER: return SL_SPEAKER_TOP_FRONT_CENTER;
  32219. case MA_CHANNEL_TOP_FRONT_RIGHT: return SL_SPEAKER_TOP_FRONT_RIGHT;
  32220. case MA_CHANNEL_TOP_BACK_LEFT: return SL_SPEAKER_TOP_BACK_LEFT;
  32221. case MA_CHANNEL_TOP_BACK_CENTER: return SL_SPEAKER_TOP_BACK_CENTER;
  32222. case MA_CHANNEL_TOP_BACK_RIGHT: return SL_SPEAKER_TOP_BACK_RIGHT;
  32223. default: return 0;
  32224. }
  32225. }
  32226. /* Converts a channel mapping to an OpenSL-style channel mask. */
  32227. static SLuint32 ma_channel_map_to_channel_mask__opensl(const ma_channel* pChannelMap, ma_uint32 channels)
  32228. {
  32229. SLuint32 channelMask = 0;
  32230. ma_uint32 iChannel;
  32231. for (iChannel = 0; iChannel < channels; ++iChannel) {
  32232. channelMask |= ma_channel_id_to_opensl(pChannelMap[iChannel]);
  32233. }
  32234. return channelMask;
  32235. }
  32236. /* Converts an OpenSL-style channel mask to a miniaudio channel map. */
  32237. static void ma_channel_mask_to_channel_map__opensl(SLuint32 channelMask, ma_uint32 channels, ma_channel* pChannelMap)
  32238. {
  32239. if (channels == 1 && channelMask == 0) {
  32240. pChannelMap[0] = MA_CHANNEL_MONO;
  32241. } else if (channels == 2 && channelMask == 0) {
  32242. pChannelMap[0] = MA_CHANNEL_FRONT_LEFT;
  32243. pChannelMap[1] = MA_CHANNEL_FRONT_RIGHT;
  32244. } else {
  32245. if (channels == 1 && (channelMask & SL_SPEAKER_FRONT_CENTER) != 0) {
  32246. pChannelMap[0] = MA_CHANNEL_MONO;
  32247. } else {
  32248. /* Just iterate over each bit. */
  32249. ma_uint32 iChannel = 0;
  32250. ma_uint32 iBit;
  32251. for (iBit = 0; iBit < 32 && iChannel < channels; ++iBit) {
  32252. SLuint32 bitValue = (channelMask & (1UL << iBit));
  32253. if (bitValue != 0) {
  32254. /* The bit is set. */
  32255. pChannelMap[iChannel] = ma_channel_id_to_ma__opensl(bitValue);
  32256. iChannel += 1;
  32257. }
  32258. }
  32259. }
  32260. }
  32261. }
  32262. static SLuint32 ma_round_to_standard_sample_rate__opensl(SLuint32 samplesPerSec)
  32263. {
  32264. if (samplesPerSec <= SL_SAMPLINGRATE_8) {
  32265. return SL_SAMPLINGRATE_8;
  32266. }
  32267. if (samplesPerSec <= SL_SAMPLINGRATE_11_025) {
  32268. return SL_SAMPLINGRATE_11_025;
  32269. }
  32270. if (samplesPerSec <= SL_SAMPLINGRATE_12) {
  32271. return SL_SAMPLINGRATE_12;
  32272. }
  32273. if (samplesPerSec <= SL_SAMPLINGRATE_16) {
  32274. return SL_SAMPLINGRATE_16;
  32275. }
  32276. if (samplesPerSec <= SL_SAMPLINGRATE_22_05) {
  32277. return SL_SAMPLINGRATE_22_05;
  32278. }
  32279. if (samplesPerSec <= SL_SAMPLINGRATE_24) {
  32280. return SL_SAMPLINGRATE_24;
  32281. }
  32282. if (samplesPerSec <= SL_SAMPLINGRATE_32) {
  32283. return SL_SAMPLINGRATE_32;
  32284. }
  32285. if (samplesPerSec <= SL_SAMPLINGRATE_44_1) {
  32286. return SL_SAMPLINGRATE_44_1;
  32287. }
  32288. if (samplesPerSec <= SL_SAMPLINGRATE_48) {
  32289. return SL_SAMPLINGRATE_48;
  32290. }
  32291. /* Android doesn't support more than 48000. */
  32292. #ifndef MA_ANDROID
  32293. if (samplesPerSec <= SL_SAMPLINGRATE_64) {
  32294. return SL_SAMPLINGRATE_64;
  32295. }
  32296. if (samplesPerSec <= SL_SAMPLINGRATE_88_2) {
  32297. return SL_SAMPLINGRATE_88_2;
  32298. }
  32299. if (samplesPerSec <= SL_SAMPLINGRATE_96) {
  32300. return SL_SAMPLINGRATE_96;
  32301. }
  32302. if (samplesPerSec <= SL_SAMPLINGRATE_192) {
  32303. return SL_SAMPLINGRATE_192;
  32304. }
  32305. #endif
  32306. return SL_SAMPLINGRATE_16;
  32307. }
  32308. static SLint32 ma_to_stream_type__opensl(ma_opensl_stream_type streamType)
  32309. {
  32310. switch (streamType) {
  32311. case ma_opensl_stream_type_voice: return SL_ANDROID_STREAM_VOICE;
  32312. case ma_opensl_stream_type_system: return SL_ANDROID_STREAM_SYSTEM;
  32313. case ma_opensl_stream_type_ring: return SL_ANDROID_STREAM_RING;
  32314. case ma_opensl_stream_type_media: return SL_ANDROID_STREAM_MEDIA;
  32315. case ma_opensl_stream_type_alarm: return SL_ANDROID_STREAM_ALARM;
  32316. case ma_opensl_stream_type_notification: return SL_ANDROID_STREAM_NOTIFICATION;
  32317. default: break;
  32318. }
  32319. return SL_ANDROID_STREAM_VOICE;
  32320. }
  32321. static SLint32 ma_to_recording_preset__opensl(ma_opensl_recording_preset recordingPreset)
  32322. {
  32323. switch (recordingPreset) {
  32324. case ma_opensl_recording_preset_generic: return SL_ANDROID_RECORDING_PRESET_GENERIC;
  32325. case ma_opensl_recording_preset_camcorder: return SL_ANDROID_RECORDING_PRESET_CAMCORDER;
  32326. case ma_opensl_recording_preset_voice_recognition: return SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION;
  32327. case ma_opensl_recording_preset_voice_communication: return SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION;
  32328. case ma_opensl_recording_preset_voice_unprocessed: return SL_ANDROID_RECORDING_PRESET_UNPROCESSED;
  32329. default: break;
  32330. }
  32331. return SL_ANDROID_RECORDING_PRESET_NONE;
  32332. }
  32333. static ma_result ma_context_enumerate_devices__opensl(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  32334. {
  32335. ma_bool32 cbResult;
  32336. MA_ASSERT(pContext != NULL);
  32337. MA_ASSERT(callback != NULL);
  32338. MA_ASSERT(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to enumerate devices. */
  32339. if (g_maOpenSLInitCounter == 0) {
  32340. return MA_INVALID_OPERATION;
  32341. }
  32342. /*
  32343. TODO: Test Me.
  32344. This is currently untested, so for now we are just returning default devices.
  32345. */
  32346. #if 0 && !defined(MA_ANDROID)
  32347. ma_bool32 isTerminated = MA_FALSE;
  32348. SLuint32 pDeviceIDs[128];
  32349. SLint32 deviceCount = sizeof(pDeviceIDs) / sizeof(pDeviceIDs[0]);
  32350. SLAudioIODeviceCapabilitiesItf deviceCaps;
  32351. SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps);
  32352. if (resultSL != SL_RESULT_SUCCESS) {
  32353. /* The interface may not be supported so just report a default device. */
  32354. goto return_default_device;
  32355. }
  32356. /* Playback */
  32357. if (!isTerminated) {
  32358. resultSL = (*deviceCaps)->GetAvailableAudioOutputs(deviceCaps, &deviceCount, pDeviceIDs);
  32359. if (resultSL != SL_RESULT_SUCCESS) {
  32360. return ma_result_from_OpenSL(resultSL);
  32361. }
  32362. for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) {
  32363. ma_device_info deviceInfo;
  32364. MA_ZERO_OBJECT(&deviceInfo);
  32365. deviceInfo.id.opensl = pDeviceIDs[iDevice];
  32366. SLAudioOutputDescriptor desc;
  32367. resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc);
  32368. if (resultSL == SL_RESULT_SUCCESS) {
  32369. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.pDeviceName, (size_t)-1);
  32370. ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  32371. if (cbResult == MA_FALSE) {
  32372. isTerminated = MA_TRUE;
  32373. break;
  32374. }
  32375. }
  32376. }
  32377. }
  32378. /* Capture */
  32379. if (!isTerminated) {
  32380. resultSL = (*deviceCaps)->GetAvailableAudioInputs(deviceCaps, &deviceCount, pDeviceIDs);
  32381. if (resultSL != SL_RESULT_SUCCESS) {
  32382. return ma_result_from_OpenSL(resultSL);
  32383. }
  32384. for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) {
  32385. ma_device_info deviceInfo;
  32386. MA_ZERO_OBJECT(&deviceInfo);
  32387. deviceInfo.id.opensl = pDeviceIDs[iDevice];
  32388. SLAudioInputDescriptor desc;
  32389. resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc);
  32390. if (resultSL == SL_RESULT_SUCCESS) {
  32391. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.deviceName, (size_t)-1);
  32392. ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  32393. if (cbResult == MA_FALSE) {
  32394. isTerminated = MA_TRUE;
  32395. break;
  32396. }
  32397. }
  32398. }
  32399. }
  32400. return MA_SUCCESS;
  32401. #else
  32402. goto return_default_device;
  32403. #endif
  32404. return_default_device:;
  32405. cbResult = MA_TRUE;
  32406. /* Playback. */
  32407. if (cbResult) {
  32408. ma_device_info deviceInfo;
  32409. MA_ZERO_OBJECT(&deviceInfo);
  32410. deviceInfo.id.opensl = SL_DEFAULTDEVICEID_AUDIOOUTPUT;
  32411. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  32412. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  32413. }
  32414. /* Capture. */
  32415. if (cbResult) {
  32416. ma_device_info deviceInfo;
  32417. MA_ZERO_OBJECT(&deviceInfo);
  32418. deviceInfo.id.opensl = SL_DEFAULTDEVICEID_AUDIOINPUT;
  32419. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  32420. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  32421. }
  32422. return MA_SUCCESS;
  32423. }
  32424. static void ma_context_add_data_format_ex__opensl(ma_context* pContext, ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_device_info* pDeviceInfo)
  32425. {
  32426. MA_ASSERT(pContext != NULL);
  32427. MA_ASSERT(pDeviceInfo != NULL);
  32428. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  32429. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  32430. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  32431. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  32432. pDeviceInfo->nativeDataFormatCount += 1;
  32433. }
  32434. static void ma_context_add_data_format__opensl(ma_context* pContext, ma_format format, ma_device_info* pDeviceInfo)
  32435. {
  32436. ma_uint32 minChannels = 1;
  32437. ma_uint32 maxChannels = 2;
  32438. ma_uint32 minSampleRate = (ma_uint32)ma_standard_sample_rate_8000;
  32439. ma_uint32 maxSampleRate = (ma_uint32)ma_standard_sample_rate_48000;
  32440. ma_uint32 iChannel;
  32441. ma_uint32 iSampleRate;
  32442. MA_ASSERT(pContext != NULL);
  32443. MA_ASSERT(pDeviceInfo != NULL);
  32444. /*
  32445. Each sample format can support mono and stereo, and we'll support a small subset of standard
  32446. rates (up to 48000). A better solution would be to somehow find a native sample rate.
  32447. */
  32448. for (iChannel = minChannels; iChannel < maxChannels; iChannel += 1) {
  32449. for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); iSampleRate += 1) {
  32450. ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iSampleRate];
  32451. if (standardSampleRate >= minSampleRate && standardSampleRate <= maxSampleRate) {
  32452. ma_context_add_data_format_ex__opensl(pContext, format, iChannel, standardSampleRate, pDeviceInfo);
  32453. }
  32454. }
  32455. }
  32456. }
  32457. static ma_result ma_context_get_device_info__opensl(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  32458. {
  32459. MA_ASSERT(pContext != NULL);
  32460. MA_ASSERT(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to get device info. */
  32461. if (g_maOpenSLInitCounter == 0) {
  32462. return MA_INVALID_OPERATION;
  32463. }
  32464. /*
  32465. TODO: Test Me.
  32466. This is currently untested, so for now we are just returning default devices.
  32467. */
  32468. #if 0 && !defined(MA_ANDROID)
  32469. SLAudioIODeviceCapabilitiesItf deviceCaps;
  32470. SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps);
  32471. if (resultSL != SL_RESULT_SUCCESS) {
  32472. /* The interface may not be supported so just report a default device. */
  32473. goto return_default_device;
  32474. }
  32475. if (deviceType == ma_device_type_playback) {
  32476. SLAudioOutputDescriptor desc;
  32477. resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, pDeviceID->opensl, &desc);
  32478. if (resultSL != SL_RESULT_SUCCESS) {
  32479. return ma_result_from_OpenSL(resultSL);
  32480. }
  32481. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.pDeviceName, (size_t)-1);
  32482. } else {
  32483. SLAudioInputDescriptor desc;
  32484. resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, pDeviceID->opensl, &desc);
  32485. if (resultSL != SL_RESULT_SUCCESS) {
  32486. return ma_result_from_OpenSL(resultSL);
  32487. }
  32488. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.deviceName, (size_t)-1);
  32489. }
  32490. goto return_detailed_info;
  32491. #else
  32492. goto return_default_device;
  32493. #endif
  32494. return_default_device:
  32495. if (pDeviceID != NULL) {
  32496. if ((deviceType == ma_device_type_playback && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOOUTPUT) ||
  32497. (deviceType == ma_device_type_capture && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOINPUT)) {
  32498. return MA_NO_DEVICE; /* Don't know the device. */
  32499. }
  32500. }
  32501. /* ID and Name / Description */
  32502. if (deviceType == ma_device_type_playback) {
  32503. pDeviceInfo->id.opensl = SL_DEFAULTDEVICEID_AUDIOOUTPUT;
  32504. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  32505. } else {
  32506. pDeviceInfo->id.opensl = SL_DEFAULTDEVICEID_AUDIOINPUT;
  32507. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  32508. }
  32509. pDeviceInfo->isDefault = MA_TRUE;
  32510. goto return_detailed_info;
  32511. return_detailed_info:
  32512. /*
  32513. For now we're just outputting a set of values that are supported by the API but not necessarily supported
  32514. by the device natively. Later on we should work on this so that it more closely reflects the device's
  32515. actual native format.
  32516. */
  32517. pDeviceInfo->nativeDataFormatCount = 0;
  32518. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  32519. ma_context_add_data_format__opensl(pContext, ma_format_f32, pDeviceInfo);
  32520. #endif
  32521. ma_context_add_data_format__opensl(pContext, ma_format_s16, pDeviceInfo);
  32522. ma_context_add_data_format__opensl(pContext, ma_format_u8, pDeviceInfo);
  32523. return MA_SUCCESS;
  32524. }
  32525. #ifdef MA_ANDROID
  32526. /*void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, SLuint32 eventFlags, const void* pBuffer, SLuint32 bufferSize, SLuint32 dataUsed, void* pContext)*/
  32527. static void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData)
  32528. {
  32529. ma_device* pDevice = (ma_device*)pUserData;
  32530. size_t periodSizeInBytes;
  32531. ma_uint8* pBuffer;
  32532. SLresult resultSL;
  32533. MA_ASSERT(pDevice != NULL);
  32534. (void)pBufferQueue;
  32535. /*
  32536. For now, don't do anything unless the buffer was fully processed. From what I can tell, it looks like
  32537. OpenSL|ES 1.1 improves on buffer queues to the point that we could much more intelligently handle this,
  32538. but unfortunately it looks like Android is only supporting OpenSL|ES 1.0.1 for now :(
  32539. */
  32540. /* Don't do anything if the device is not started. */
  32541. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  32542. return;
  32543. }
  32544. /* Don't do anything if the device is being drained. */
  32545. if (pDevice->opensl.isDrainingCapture) {
  32546. return;
  32547. }
  32548. periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  32549. pBuffer = pDevice->opensl.pBufferCapture + (pDevice->opensl.currentBufferIndexCapture * periodSizeInBytes);
  32550. ma_device_handle_backend_data_callback(pDevice, NULL, pBuffer, pDevice->capture.internalPeriodSizeInFrames);
  32551. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pBuffer, periodSizeInBytes);
  32552. if (resultSL != SL_RESULT_SUCCESS) {
  32553. return;
  32554. }
  32555. pDevice->opensl.currentBufferIndexCapture = (pDevice->opensl.currentBufferIndexCapture + 1) % pDevice->capture.internalPeriods;
  32556. }
  32557. static void ma_buffer_queue_callback_playback__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData)
  32558. {
  32559. ma_device* pDevice = (ma_device*)pUserData;
  32560. size_t periodSizeInBytes;
  32561. ma_uint8* pBuffer;
  32562. SLresult resultSL;
  32563. MA_ASSERT(pDevice != NULL);
  32564. (void)pBufferQueue;
  32565. /* Don't do anything if the device is not started. */
  32566. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  32567. return;
  32568. }
  32569. /* Don't do anything if the device is being drained. */
  32570. if (pDevice->opensl.isDrainingPlayback) {
  32571. return;
  32572. }
  32573. periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  32574. pBuffer = pDevice->opensl.pBufferPlayback + (pDevice->opensl.currentBufferIndexPlayback * periodSizeInBytes);
  32575. ma_device_handle_backend_data_callback(pDevice, pBuffer, NULL, pDevice->playback.internalPeriodSizeInFrames);
  32576. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pBuffer, periodSizeInBytes);
  32577. if (resultSL != SL_RESULT_SUCCESS) {
  32578. return;
  32579. }
  32580. pDevice->opensl.currentBufferIndexPlayback = (pDevice->opensl.currentBufferIndexPlayback + 1) % pDevice->playback.internalPeriods;
  32581. }
  32582. #endif
  32583. static ma_result ma_device_uninit__opensl(ma_device* pDevice)
  32584. {
  32585. MA_ASSERT(pDevice != NULL);
  32586. MA_ASSERT(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it before uninitializing the device. */
  32587. if (g_maOpenSLInitCounter == 0) {
  32588. return MA_INVALID_OPERATION;
  32589. }
  32590. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  32591. if (pDevice->opensl.pAudioRecorderObj) {
  32592. MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioRecorderObj);
  32593. }
  32594. ma_free(pDevice->opensl.pBufferCapture, &pDevice->pContext->allocationCallbacks);
  32595. }
  32596. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  32597. if (pDevice->opensl.pAudioPlayerObj) {
  32598. MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioPlayerObj);
  32599. }
  32600. if (pDevice->opensl.pOutputMixObj) {
  32601. MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Destroy((SLObjectItf)pDevice->opensl.pOutputMixObj);
  32602. }
  32603. ma_free(pDevice->opensl.pBufferPlayback, &pDevice->pContext->allocationCallbacks);
  32604. }
  32605. return MA_SUCCESS;
  32606. }
  32607. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  32608. typedef SLAndroidDataFormat_PCM_EX ma_SLDataFormat_PCM;
  32609. #else
  32610. typedef SLDataFormat_PCM ma_SLDataFormat_PCM;
  32611. #endif
  32612. static ma_result ma_SLDataFormat_PCM_init__opensl(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* channelMap, ma_SLDataFormat_PCM* pDataFormat)
  32613. {
  32614. /* We need to convert our format/channels/rate so that they aren't set to default. */
  32615. if (format == ma_format_unknown) {
  32616. format = MA_DEFAULT_FORMAT;
  32617. }
  32618. if (channels == 0) {
  32619. channels = MA_DEFAULT_CHANNELS;
  32620. }
  32621. if (sampleRate == 0) {
  32622. sampleRate = MA_DEFAULT_SAMPLE_RATE;
  32623. }
  32624. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  32625. if (format == ma_format_f32) {
  32626. pDataFormat->formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
  32627. pDataFormat->representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT;
  32628. } else {
  32629. pDataFormat->formatType = SL_DATAFORMAT_PCM;
  32630. }
  32631. #else
  32632. pDataFormat->formatType = SL_DATAFORMAT_PCM;
  32633. #endif
  32634. pDataFormat->numChannels = channels;
  32635. ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec = ma_round_to_standard_sample_rate__opensl(sampleRate * 1000); /* In millihertz. Annoyingly, the sample rate variable is named differently between SLAndroidDataFormat_PCM_EX and SLDataFormat_PCM */
  32636. pDataFormat->bitsPerSample = ma_get_bytes_per_sample(format) * 8;
  32637. pDataFormat->channelMask = ma_channel_map_to_channel_mask__opensl(channelMap, channels);
  32638. pDataFormat->endianness = (ma_is_little_endian()) ? SL_BYTEORDER_LITTLEENDIAN : SL_BYTEORDER_BIGENDIAN;
  32639. /*
  32640. Android has a few restrictions on the format as documented here: https://developer.android.com/ndk/guides/audio/opensl-for-android.html
  32641. - Only mono and stereo is supported.
  32642. - Only u8 and s16 formats are supported.
  32643. - Maximum sample rate of 48000.
  32644. */
  32645. #ifdef MA_ANDROID
  32646. if (pDataFormat->numChannels > 2) {
  32647. pDataFormat->numChannels = 2;
  32648. }
  32649. #if __ANDROID_API__ >= 21
  32650. if (pDataFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) {
  32651. /* It's floating point. */
  32652. MA_ASSERT(pDataFormat->representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT);
  32653. if (pDataFormat->bitsPerSample > 32) {
  32654. pDataFormat->bitsPerSample = 32;
  32655. }
  32656. } else {
  32657. if (pDataFormat->bitsPerSample > 16) {
  32658. pDataFormat->bitsPerSample = 16;
  32659. }
  32660. }
  32661. #else
  32662. if (pDataFormat->bitsPerSample > 16) {
  32663. pDataFormat->bitsPerSample = 16;
  32664. }
  32665. #endif
  32666. if (((SLDataFormat_PCM*)pDataFormat)->samplesPerSec > SL_SAMPLINGRATE_48) {
  32667. ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec = SL_SAMPLINGRATE_48;
  32668. }
  32669. #endif
  32670. pDataFormat->containerSize = pDataFormat->bitsPerSample; /* Always tightly packed for now. */
  32671. return MA_SUCCESS;
  32672. }
  32673. static ma_result ma_deconstruct_SLDataFormat_PCM__opensl(ma_SLDataFormat_PCM* pDataFormat, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  32674. {
  32675. ma_bool32 isFloatingPoint = MA_FALSE;
  32676. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  32677. if (pDataFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) {
  32678. MA_ASSERT(pDataFormat->representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT);
  32679. isFloatingPoint = MA_TRUE;
  32680. }
  32681. #endif
  32682. if (isFloatingPoint) {
  32683. if (pDataFormat->bitsPerSample == 32) {
  32684. *pFormat = ma_format_f32;
  32685. }
  32686. } else {
  32687. if (pDataFormat->bitsPerSample == 8) {
  32688. *pFormat = ma_format_u8;
  32689. } else if (pDataFormat->bitsPerSample == 16) {
  32690. *pFormat = ma_format_s16;
  32691. } else if (pDataFormat->bitsPerSample == 24) {
  32692. *pFormat = ma_format_s24;
  32693. } else if (pDataFormat->bitsPerSample == 32) {
  32694. *pFormat = ma_format_s32;
  32695. }
  32696. }
  32697. *pChannels = pDataFormat->numChannels;
  32698. *pSampleRate = ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec / 1000;
  32699. ma_channel_mask_to_channel_map__opensl(pDataFormat->channelMask, ma_min(pDataFormat->numChannels, channelMapCap), pChannelMap);
  32700. return MA_SUCCESS;
  32701. }
  32702. static ma_result ma_device_init__opensl(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  32703. {
  32704. #ifdef MA_ANDROID
  32705. SLDataLocator_AndroidSimpleBufferQueue queue;
  32706. SLresult resultSL;
  32707. size_t bufferSizeInBytes;
  32708. SLInterfaceID itfIDs[2];
  32709. const SLboolean itfIDsRequired[] = {
  32710. SL_BOOLEAN_TRUE, /* SL_IID_ANDROIDSIMPLEBUFFERQUEUE */
  32711. SL_BOOLEAN_FALSE /* SL_IID_ANDROIDCONFIGURATION */
  32712. };
  32713. #endif
  32714. MA_ASSERT(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to initialize a new device. */
  32715. if (g_maOpenSLInitCounter == 0) {
  32716. return MA_INVALID_OPERATION;
  32717. }
  32718. if (pConfig->deviceType == ma_device_type_loopback) {
  32719. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  32720. }
  32721. /*
  32722. For now, only supporting Android implementations of OpenSL|ES since that's the only one I've
  32723. been able to test with and I currently depend on Android-specific extensions (simple buffer
  32724. queues).
  32725. */
  32726. #ifdef MA_ANDROID
  32727. itfIDs[0] = (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
  32728. itfIDs[1] = (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION;
  32729. /* No exclusive mode with OpenSL|ES. */
  32730. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  32731. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  32732. return MA_SHARE_MODE_NOT_SUPPORTED;
  32733. }
  32734. /* Now we can start initializing the device properly. */
  32735. MA_ASSERT(pDevice != NULL);
  32736. MA_ZERO_OBJECT(&pDevice->opensl);
  32737. queue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
  32738. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  32739. ma_SLDataFormat_PCM pcm;
  32740. SLDataLocator_IODevice locatorDevice;
  32741. SLDataSource source;
  32742. SLDataSink sink;
  32743. SLAndroidConfigurationItf pRecorderConfig;
  32744. ma_SLDataFormat_PCM_init__opensl(pDescriptorCapture->format, pDescriptorCapture->channels, pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, &pcm);
  32745. locatorDevice.locatorType = SL_DATALOCATOR_IODEVICE;
  32746. locatorDevice.deviceType = SL_IODEVICE_AUDIOINPUT;
  32747. locatorDevice.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT; /* Must always use the default device with Android. */
  32748. locatorDevice.device = NULL;
  32749. source.pLocator = &locatorDevice;
  32750. source.pFormat = NULL;
  32751. queue.numBuffers = pDescriptorCapture->periodCount;
  32752. sink.pLocator = &queue;
  32753. sink.pFormat = (SLDataFormat_PCM*)&pcm;
  32754. resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  32755. if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED || resultSL == SL_RESULT_PARAMETER_INVALID) {
  32756. /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */
  32757. pcm.formatType = SL_DATAFORMAT_PCM;
  32758. pcm.numChannels = 1;
  32759. ((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16; /* The name of the sample rate variable is different between SLAndroidDataFormat_PCM_EX and SLDataFormat_PCM. */
  32760. pcm.bitsPerSample = 16;
  32761. pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */
  32762. pcm.channelMask = 0;
  32763. resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  32764. }
  32765. if (resultSL != SL_RESULT_SUCCESS) {
  32766. ma_device_uninit__opensl(pDevice);
  32767. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio recorder.");
  32768. return ma_result_from_OpenSL(resultSL);
  32769. }
  32770. /* Set the recording preset before realizing the player. */
  32771. if (pConfig->opensl.recordingPreset != ma_opensl_recording_preset_default) {
  32772. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION, &pRecorderConfig);
  32773. if (resultSL == SL_RESULT_SUCCESS) {
  32774. SLint32 recordingPreset = ma_to_recording_preset__opensl(pConfig->opensl.recordingPreset);
  32775. resultSL = (*pRecorderConfig)->SetConfiguration(pRecorderConfig, SL_ANDROID_KEY_RECORDING_PRESET, &recordingPreset, sizeof(SLint32));
  32776. if (resultSL != SL_RESULT_SUCCESS) {
  32777. /* Failed to set the configuration. Just keep going. */
  32778. }
  32779. }
  32780. }
  32781. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Realize((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_BOOLEAN_FALSE);
  32782. if (resultSL != SL_RESULT_SUCCESS) {
  32783. ma_device_uninit__opensl(pDevice);
  32784. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio recorder.");
  32785. return ma_result_from_OpenSL(resultSL);
  32786. }
  32787. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_RECORD, &pDevice->opensl.pAudioRecorder);
  32788. if (resultSL != SL_RESULT_SUCCESS) {
  32789. ma_device_uninit__opensl(pDevice);
  32790. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_RECORD interface.");
  32791. return ma_result_from_OpenSL(resultSL);
  32792. }
  32793. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueueCapture);
  32794. if (resultSL != SL_RESULT_SUCCESS) {
  32795. ma_device_uninit__opensl(pDevice);
  32796. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.");
  32797. return ma_result_from_OpenSL(resultSL);
  32798. }
  32799. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, ma_buffer_queue_callback_capture__opensl_android, pDevice);
  32800. if (resultSL != SL_RESULT_SUCCESS) {
  32801. ma_device_uninit__opensl(pDevice);
  32802. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.");
  32803. return ma_result_from_OpenSL(resultSL);
  32804. }
  32805. /* The internal format is determined by the "pcm" object. */
  32806. ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDescriptorCapture->format, &pDescriptorCapture->channels, &pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap));
  32807. /* Buffer. */
  32808. pDescriptorCapture->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
  32809. pDevice->opensl.currentBufferIndexCapture = 0;
  32810. bufferSizeInBytes = pDescriptorCapture->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) * pDescriptorCapture->periodCount;
  32811. pDevice->opensl.pBufferCapture = (ma_uint8*)ma_calloc(bufferSizeInBytes, &pDevice->pContext->allocationCallbacks);
  32812. if (pDevice->opensl.pBufferCapture == NULL) {
  32813. ma_device_uninit__opensl(pDevice);
  32814. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.");
  32815. return MA_OUT_OF_MEMORY;
  32816. }
  32817. MA_ZERO_MEMORY(pDevice->opensl.pBufferCapture, bufferSizeInBytes);
  32818. }
  32819. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  32820. ma_SLDataFormat_PCM pcm;
  32821. SLDataSource source;
  32822. SLDataLocator_OutputMix outmixLocator;
  32823. SLDataSink sink;
  32824. SLAndroidConfigurationItf pPlayerConfig;
  32825. ma_SLDataFormat_PCM_init__opensl(pDescriptorPlayback->format, pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, &pcm);
  32826. resultSL = (*g_maEngineSL)->CreateOutputMix(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pOutputMixObj, 0, NULL, NULL);
  32827. if (resultSL != SL_RESULT_SUCCESS) {
  32828. ma_device_uninit__opensl(pDevice);
  32829. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create output mix.");
  32830. return ma_result_from_OpenSL(resultSL);
  32831. }
  32832. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Realize((SLObjectItf)pDevice->opensl.pOutputMixObj, SL_BOOLEAN_FALSE);
  32833. if (resultSL != SL_RESULT_SUCCESS) {
  32834. ma_device_uninit__opensl(pDevice);
  32835. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize output mix object.");
  32836. return ma_result_from_OpenSL(resultSL);
  32837. }
  32838. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->GetInterface((SLObjectItf)pDevice->opensl.pOutputMixObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_OUTPUTMIX, &pDevice->opensl.pOutputMix);
  32839. if (resultSL != SL_RESULT_SUCCESS) {
  32840. ma_device_uninit__opensl(pDevice);
  32841. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_OUTPUTMIX interface.");
  32842. return ma_result_from_OpenSL(resultSL);
  32843. }
  32844. /* Set the output device. */
  32845. if (pDescriptorPlayback->pDeviceID != NULL) {
  32846. SLuint32 deviceID_OpenSL = pDescriptorPlayback->pDeviceID->opensl;
  32847. MA_OPENSL_OUTPUTMIX(pDevice->opensl.pOutputMix)->ReRoute((SLOutputMixItf)pDevice->opensl.pOutputMix, 1, &deviceID_OpenSL);
  32848. }
  32849. queue.numBuffers = pDescriptorPlayback->periodCount;
  32850. source.pLocator = &queue;
  32851. source.pFormat = (SLDataFormat_PCM*)&pcm;
  32852. outmixLocator.locatorType = SL_DATALOCATOR_OUTPUTMIX;
  32853. outmixLocator.outputMix = (SLObjectItf)pDevice->opensl.pOutputMixObj;
  32854. sink.pLocator = &outmixLocator;
  32855. sink.pFormat = NULL;
  32856. resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  32857. if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED || resultSL == SL_RESULT_PARAMETER_INVALID) {
  32858. /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */
  32859. pcm.formatType = SL_DATAFORMAT_PCM;
  32860. pcm.numChannels = 2;
  32861. ((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16;
  32862. pcm.bitsPerSample = 16;
  32863. pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */
  32864. pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
  32865. resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  32866. }
  32867. if (resultSL != SL_RESULT_SUCCESS) {
  32868. ma_device_uninit__opensl(pDevice);
  32869. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio player.");
  32870. return ma_result_from_OpenSL(resultSL);
  32871. }
  32872. /* Set the stream type before realizing the player. */
  32873. if (pConfig->opensl.streamType != ma_opensl_stream_type_default) {
  32874. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION, &pPlayerConfig);
  32875. if (resultSL == SL_RESULT_SUCCESS) {
  32876. SLint32 streamType = ma_to_stream_type__opensl(pConfig->opensl.streamType);
  32877. resultSL = (*pPlayerConfig)->SetConfiguration(pPlayerConfig, SL_ANDROID_KEY_STREAM_TYPE, &streamType, sizeof(SLint32));
  32878. if (resultSL != SL_RESULT_SUCCESS) {
  32879. /* Failed to set the configuration. Just keep going. */
  32880. }
  32881. }
  32882. }
  32883. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Realize((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_BOOLEAN_FALSE);
  32884. if (resultSL != SL_RESULT_SUCCESS) {
  32885. ma_device_uninit__opensl(pDevice);
  32886. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio player.");
  32887. return ma_result_from_OpenSL(resultSL);
  32888. }
  32889. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_PLAY, &pDevice->opensl.pAudioPlayer);
  32890. if (resultSL != SL_RESULT_SUCCESS) {
  32891. ma_device_uninit__opensl(pDevice);
  32892. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_PLAY interface.");
  32893. return ma_result_from_OpenSL(resultSL);
  32894. }
  32895. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueuePlayback);
  32896. if (resultSL != SL_RESULT_SUCCESS) {
  32897. ma_device_uninit__opensl(pDevice);
  32898. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.");
  32899. return ma_result_from_OpenSL(resultSL);
  32900. }
  32901. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, ma_buffer_queue_callback_playback__opensl_android, pDevice);
  32902. if (resultSL != SL_RESULT_SUCCESS) {
  32903. ma_device_uninit__opensl(pDevice);
  32904. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.");
  32905. return ma_result_from_OpenSL(resultSL);
  32906. }
  32907. /* The internal format is determined by the "pcm" object. */
  32908. ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDescriptorPlayback->format, &pDescriptorPlayback->channels, &pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap));
  32909. /* Buffer. */
  32910. pDescriptorPlayback->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  32911. pDevice->opensl.currentBufferIndexPlayback = 0;
  32912. bufferSizeInBytes = pDescriptorPlayback->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels) * pDescriptorPlayback->periodCount;
  32913. pDevice->opensl.pBufferPlayback = (ma_uint8*)ma_calloc(bufferSizeInBytes, &pDevice->pContext->allocationCallbacks);
  32914. if (pDevice->opensl.pBufferPlayback == NULL) {
  32915. ma_device_uninit__opensl(pDevice);
  32916. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.");
  32917. return MA_OUT_OF_MEMORY;
  32918. }
  32919. MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, bufferSizeInBytes);
  32920. }
  32921. return MA_SUCCESS;
  32922. #else
  32923. return MA_NO_BACKEND; /* Non-Android implementations are not supported. */
  32924. #endif
  32925. }
  32926. static ma_result ma_device_start__opensl(ma_device* pDevice)
  32927. {
  32928. SLresult resultSL;
  32929. size_t periodSizeInBytes;
  32930. ma_uint32 iPeriod;
  32931. MA_ASSERT(pDevice != NULL);
  32932. MA_ASSERT(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to start the device. */
  32933. if (g_maOpenSLInitCounter == 0) {
  32934. return MA_INVALID_OPERATION;
  32935. }
  32936. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  32937. resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_RECORDING);
  32938. if (resultSL != SL_RESULT_SUCCESS) {
  32939. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal capture device.");
  32940. return ma_result_from_OpenSL(resultSL);
  32941. }
  32942. periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  32943. for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) {
  32944. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pDevice->opensl.pBufferCapture + (periodSizeInBytes * iPeriod), periodSizeInBytes);
  32945. if (resultSL != SL_RESULT_SUCCESS) {
  32946. MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED);
  32947. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for capture device.");
  32948. return ma_result_from_OpenSL(resultSL);
  32949. }
  32950. }
  32951. }
  32952. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  32953. resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_PLAYING);
  32954. if (resultSL != SL_RESULT_SUCCESS) {
  32955. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal playback device.");
  32956. return ma_result_from_OpenSL(resultSL);
  32957. }
  32958. /* In playback mode (no duplex) we need to load some initial buffers. In duplex mode we need to enqueu silent buffers. */
  32959. if (pDevice->type == ma_device_type_duplex) {
  32960. MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  32961. } else {
  32962. ma_device__read_frames_from_client(pDevice, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods, pDevice->opensl.pBufferPlayback);
  32963. }
  32964. periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  32965. for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) {
  32966. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pDevice->opensl.pBufferPlayback + (periodSizeInBytes * iPeriod), periodSizeInBytes);
  32967. if (resultSL != SL_RESULT_SUCCESS) {
  32968. MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED);
  32969. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for playback device.");
  32970. return ma_result_from_OpenSL(resultSL);
  32971. }
  32972. }
  32973. }
  32974. return MA_SUCCESS;
  32975. }
  32976. static ma_result ma_device_drain__opensl(ma_device* pDevice, ma_device_type deviceType)
  32977. {
  32978. SLAndroidSimpleBufferQueueItf pBufferQueue;
  32979. MA_ASSERT(deviceType == ma_device_type_capture || deviceType == ma_device_type_playback);
  32980. if (pDevice->type == ma_device_type_capture) {
  32981. pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture;
  32982. pDevice->opensl.isDrainingCapture = MA_TRUE;
  32983. } else {
  32984. pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback;
  32985. pDevice->opensl.isDrainingPlayback = MA_TRUE;
  32986. }
  32987. for (;;) {
  32988. SLAndroidSimpleBufferQueueState state;
  32989. MA_OPENSL_BUFFERQUEUE(pBufferQueue)->GetState(pBufferQueue, &state);
  32990. if (state.count == 0) {
  32991. break;
  32992. }
  32993. ma_sleep(10);
  32994. }
  32995. if (pDevice->type == ma_device_type_capture) {
  32996. pDevice->opensl.isDrainingCapture = MA_FALSE;
  32997. } else {
  32998. pDevice->opensl.isDrainingPlayback = MA_FALSE;
  32999. }
  33000. return MA_SUCCESS;
  33001. }
  33002. static ma_result ma_device_stop__opensl(ma_device* pDevice)
  33003. {
  33004. SLresult resultSL;
  33005. MA_ASSERT(pDevice != NULL);
  33006. MA_ASSERT(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it before stopping/uninitializing the device. */
  33007. if (g_maOpenSLInitCounter == 0) {
  33008. return MA_INVALID_OPERATION;
  33009. }
  33010. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  33011. ma_device_drain__opensl(pDevice, ma_device_type_capture);
  33012. resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED);
  33013. if (resultSL != SL_RESULT_SUCCESS) {
  33014. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal capture device.");
  33015. return ma_result_from_OpenSL(resultSL);
  33016. }
  33017. MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture);
  33018. }
  33019. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  33020. ma_device_drain__opensl(pDevice, ma_device_type_playback);
  33021. resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED);
  33022. if (resultSL != SL_RESULT_SUCCESS) {
  33023. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal playback device.");
  33024. return ma_result_from_OpenSL(resultSL);
  33025. }
  33026. MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback);
  33027. }
  33028. /* Make sure the client is aware that the device has stopped. There may be an OpenSL|ES callback for this, but I haven't found it. */
  33029. ma_device__on_notification_stopped(pDevice);
  33030. return MA_SUCCESS;
  33031. }
  33032. static ma_result ma_context_uninit__opensl(ma_context* pContext)
  33033. {
  33034. MA_ASSERT(pContext != NULL);
  33035. MA_ASSERT(pContext->backend == ma_backend_opensl);
  33036. (void)pContext;
  33037. /* Uninit global data. */
  33038. ma_spinlock_lock(&g_maOpenSLSpinlock);
  33039. {
  33040. MA_ASSERT(g_maOpenSLInitCounter > 0); /* If you've triggered this, it means you have ma_context_init/uninit mismatch. Each successful call to ma_context_init() must be matched up with a call to ma_context_uninit(). */
  33041. g_maOpenSLInitCounter -= 1;
  33042. if (g_maOpenSLInitCounter == 0) {
  33043. (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL);
  33044. }
  33045. }
  33046. ma_spinlock_unlock(&g_maOpenSLSpinlock);
  33047. return MA_SUCCESS;
  33048. }
  33049. static ma_result ma_dlsym_SLInterfaceID__opensl(ma_context* pContext, const char* pName, ma_handle* pHandle)
  33050. {
  33051. /* We need to return an error if the symbol cannot be found. This is important because there have been reports that some symbols do not exist. */
  33052. ma_handle* p = (ma_handle*)ma_dlsym(pContext, pContext->opensl.libOpenSLES, pName);
  33053. if (p == NULL) {
  33054. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Cannot find symbol %s", pName);
  33055. return MA_NO_BACKEND;
  33056. }
  33057. *pHandle = *p;
  33058. return MA_SUCCESS;
  33059. }
  33060. static ma_result ma_context_init_engine_nolock__opensl(ma_context* pContext)
  33061. {
  33062. g_maOpenSLInitCounter += 1;
  33063. if (g_maOpenSLInitCounter == 1) {
  33064. SLresult resultSL;
  33065. resultSL = ((ma_slCreateEngine_proc)pContext->opensl.slCreateEngine)(&g_maEngineObjectSL, 0, NULL, 0, NULL, NULL);
  33066. if (resultSL != SL_RESULT_SUCCESS) {
  33067. g_maOpenSLInitCounter -= 1;
  33068. return ma_result_from_OpenSL(resultSL);
  33069. }
  33070. (*g_maEngineObjectSL)->Realize(g_maEngineObjectSL, SL_BOOLEAN_FALSE);
  33071. resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_ENGINE, &g_maEngineSL);
  33072. if (resultSL != SL_RESULT_SUCCESS) {
  33073. (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL);
  33074. g_maOpenSLInitCounter -= 1;
  33075. return ma_result_from_OpenSL(resultSL);
  33076. }
  33077. }
  33078. return MA_SUCCESS;
  33079. }
  33080. static ma_result ma_context_init__opensl(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  33081. {
  33082. ma_result result;
  33083. #if !defined(MA_NO_RUNTIME_LINKING)
  33084. size_t i;
  33085. const char* libOpenSLESNames[] = {
  33086. "libOpenSLES.so"
  33087. };
  33088. #endif
  33089. MA_ASSERT(pContext != NULL);
  33090. (void)pConfig;
  33091. #if !defined(MA_NO_RUNTIME_LINKING)
  33092. /*
  33093. Dynamically link against libOpenSLES.so. I have now had multiple reports that SL_IID_ANDROIDSIMPLEBUFFERQUEUE cannot be found. One
  33094. report was happening at compile time and another at runtime. To try working around this, I'm going to link to libOpenSLES at runtime
  33095. and extract the symbols rather than reference them directly. This should, hopefully, fix these issues as the compiler won't see any
  33096. references to the symbols and will hopefully skip the checks.
  33097. */
  33098. for (i = 0; i < ma_countof(libOpenSLESNames); i += 1) {
  33099. pContext->opensl.libOpenSLES = ma_dlopen(pContext, libOpenSLESNames[i]);
  33100. if (pContext->opensl.libOpenSLES != NULL) {
  33101. break;
  33102. }
  33103. }
  33104. if (pContext->opensl.libOpenSLES == NULL) {
  33105. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Could not find libOpenSLES.so");
  33106. return MA_NO_BACKEND;
  33107. }
  33108. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ENGINE", &pContext->opensl.SL_IID_ENGINE);
  33109. if (result != MA_SUCCESS) {
  33110. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  33111. return result;
  33112. }
  33113. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_AUDIOIODEVICECAPABILITIES", &pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES);
  33114. if (result != MA_SUCCESS) {
  33115. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  33116. return result;
  33117. }
  33118. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ANDROIDSIMPLEBUFFERQUEUE", &pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE);
  33119. if (result != MA_SUCCESS) {
  33120. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  33121. return result;
  33122. }
  33123. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_RECORD", &pContext->opensl.SL_IID_RECORD);
  33124. if (result != MA_SUCCESS) {
  33125. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  33126. return result;
  33127. }
  33128. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_PLAY", &pContext->opensl.SL_IID_PLAY);
  33129. if (result != MA_SUCCESS) {
  33130. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  33131. return result;
  33132. }
  33133. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_OUTPUTMIX", &pContext->opensl.SL_IID_OUTPUTMIX);
  33134. if (result != MA_SUCCESS) {
  33135. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  33136. return result;
  33137. }
  33138. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ANDROIDCONFIGURATION", &pContext->opensl.SL_IID_ANDROIDCONFIGURATION);
  33139. if (result != MA_SUCCESS) {
  33140. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  33141. return result;
  33142. }
  33143. pContext->opensl.slCreateEngine = (ma_proc)ma_dlsym(pContext, pContext->opensl.libOpenSLES, "slCreateEngine");
  33144. if (pContext->opensl.slCreateEngine == NULL) {
  33145. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  33146. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Cannot find symbol slCreateEngine.");
  33147. return MA_NO_BACKEND;
  33148. }
  33149. #else
  33150. pContext->opensl.SL_IID_ENGINE = (ma_handle)SL_IID_ENGINE;
  33151. pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES = (ma_handle)SL_IID_AUDIOIODEVICECAPABILITIES;
  33152. pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE = (ma_handle)SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
  33153. pContext->opensl.SL_IID_RECORD = (ma_handle)SL_IID_RECORD;
  33154. pContext->opensl.SL_IID_PLAY = (ma_handle)SL_IID_PLAY;
  33155. pContext->opensl.SL_IID_OUTPUTMIX = (ma_handle)SL_IID_OUTPUTMIX;
  33156. pContext->opensl.SL_IID_ANDROIDCONFIGURATION = (ma_handle)SL_IID_ANDROIDCONFIGURATION;
  33157. pContext->opensl.slCreateEngine = (ma_proc)slCreateEngine;
  33158. #endif
  33159. /* Initialize global data first if applicable. */
  33160. ma_spinlock_lock(&g_maOpenSLSpinlock);
  33161. {
  33162. result = ma_context_init_engine_nolock__opensl(pContext);
  33163. }
  33164. ma_spinlock_unlock(&g_maOpenSLSpinlock);
  33165. if (result != MA_SUCCESS) {
  33166. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  33167. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Failed to initialize OpenSL engine.");
  33168. return result;
  33169. }
  33170. pCallbacks->onContextInit = ma_context_init__opensl;
  33171. pCallbacks->onContextUninit = ma_context_uninit__opensl;
  33172. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__opensl;
  33173. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__opensl;
  33174. pCallbacks->onDeviceInit = ma_device_init__opensl;
  33175. pCallbacks->onDeviceUninit = ma_device_uninit__opensl;
  33176. pCallbacks->onDeviceStart = ma_device_start__opensl;
  33177. pCallbacks->onDeviceStop = ma_device_stop__opensl;
  33178. pCallbacks->onDeviceRead = NULL; /* Not needed because OpenSL|ES is asynchronous. */
  33179. pCallbacks->onDeviceWrite = NULL; /* Not needed because OpenSL|ES is asynchronous. */
  33180. pCallbacks->onDeviceDataLoop = NULL; /* Not needed because OpenSL|ES is asynchronous. */
  33181. return MA_SUCCESS;
  33182. }
  33183. #endif /* OpenSL|ES */
  33184. /******************************************************************************
  33185. Web Audio Backend
  33186. ******************************************************************************/
  33187. #ifdef MA_HAS_WEBAUDIO
  33188. #include <emscripten/emscripten.h>
  33189. #if (__EMSCRIPTEN_major__ > 3) || (__EMSCRIPTEN_major__ == 3 && (__EMSCRIPTEN_minor__ > 1 || (__EMSCRIPTEN_minor__ == 1 && __EMSCRIPTEN_tiny__ >= 32)))
  33190. #include <emscripten/webaudio.h>
  33191. #define MA_SUPPORT_AUDIO_WORKLETS
  33192. #endif
  33193. /*
  33194. TODO: Version 0.12: Swap this logic around so that AudioWorklets are used by default. Add MA_NO_AUDIO_WORKLETS.
  33195. */
  33196. #if defined(MA_ENABLE_AUDIO_WORKLETS) && defined(MA_SUPPORT_AUDIO_WORKLETS)
  33197. #define MA_USE_AUDIO_WORKLETS
  33198. #endif
  33199. /* The thread stack size must be a multiple of 16. */
  33200. #ifndef MA_AUDIO_WORKLETS_THREAD_STACK_SIZE
  33201. #define MA_AUDIO_WORKLETS_THREAD_STACK_SIZE 16384
  33202. #endif
  33203. #if defined(MA_USE_AUDIO_WORKLETS)
  33204. #define MA_WEBAUDIO_LATENCY_HINT_BALANCED "balanced"
  33205. #define MA_WEBAUDIO_LATENCY_HINT_INTERACTIVE "interactive"
  33206. #define MA_WEBAUDIO_LATENCY_HINT_PLAYBACK "playback"
  33207. #endif
  33208. static ma_bool32 ma_is_capture_supported__webaudio()
  33209. {
  33210. return EM_ASM_INT({
  33211. return (navigator.mediaDevices !== undefined && navigator.mediaDevices.getUserMedia !== undefined);
  33212. }, 0) != 0; /* Must pass in a dummy argument for C99 compatibility. */
  33213. }
  33214. #ifdef __cplusplus
  33215. extern "C" {
  33216. #endif
  33217. void* EMSCRIPTEN_KEEPALIVE ma_malloc_emscripten(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  33218. {
  33219. return ma_malloc(sz, pAllocationCallbacks);
  33220. }
  33221. void EMSCRIPTEN_KEEPALIVE ma_free_emscripten(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  33222. {
  33223. ma_free(p, pAllocationCallbacks);
  33224. }
  33225. void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_capture__webaudio(ma_device* pDevice, int frameCount, float* pFrames)
  33226. {
  33227. ma_device_handle_backend_data_callback(pDevice, NULL, pFrames, (ma_uint32)frameCount);
  33228. }
  33229. void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_playback__webaudio(ma_device* pDevice, int frameCount, float* pFrames)
  33230. {
  33231. ma_device_handle_backend_data_callback(pDevice, pFrames, NULL, (ma_uint32)frameCount);
  33232. }
  33233. #ifdef __cplusplus
  33234. }
  33235. #endif
  33236. static ma_result ma_context_enumerate_devices__webaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  33237. {
  33238. ma_bool32 cbResult = MA_TRUE;
  33239. MA_ASSERT(pContext != NULL);
  33240. MA_ASSERT(callback != NULL);
  33241. /* Only supporting default devices for now. */
  33242. /* Playback. */
  33243. if (cbResult) {
  33244. ma_device_info deviceInfo;
  33245. MA_ZERO_OBJECT(&deviceInfo);
  33246. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  33247. deviceInfo.isDefault = MA_TRUE; /* Only supporting default devices. */
  33248. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  33249. }
  33250. /* Capture. */
  33251. if (cbResult) {
  33252. if (ma_is_capture_supported__webaudio()) {
  33253. ma_device_info deviceInfo;
  33254. MA_ZERO_OBJECT(&deviceInfo);
  33255. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  33256. deviceInfo.isDefault = MA_TRUE; /* Only supporting default devices. */
  33257. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  33258. }
  33259. }
  33260. return MA_SUCCESS;
  33261. }
  33262. static ma_result ma_context_get_device_info__webaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  33263. {
  33264. MA_ASSERT(pContext != NULL);
  33265. if (deviceType == ma_device_type_capture && !ma_is_capture_supported__webaudio()) {
  33266. return MA_NO_DEVICE;
  33267. }
  33268. MA_ZERO_MEMORY(pDeviceInfo->id.webaudio, sizeof(pDeviceInfo->id.webaudio));
  33269. /* Only supporting default devices for now. */
  33270. (void)pDeviceID;
  33271. if (deviceType == ma_device_type_playback) {
  33272. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  33273. } else {
  33274. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  33275. }
  33276. /* Only supporting default devices. */
  33277. pDeviceInfo->isDefault = MA_TRUE;
  33278. /* Web Audio can support any number of channels and sample rates. It only supports f32 formats, however. */
  33279. pDeviceInfo->nativeDataFormats[0].flags = 0;
  33280. pDeviceInfo->nativeDataFormats[0].format = ma_format_unknown;
  33281. pDeviceInfo->nativeDataFormats[0].channels = 0; /* All channels are supported. */
  33282. pDeviceInfo->nativeDataFormats[0].sampleRate = EM_ASM_INT({
  33283. try {
  33284. var temp = new (window.AudioContext || window.webkitAudioContext)();
  33285. var sampleRate = temp.sampleRate;
  33286. temp.close();
  33287. return sampleRate;
  33288. } catch(e) {
  33289. return 0;
  33290. }
  33291. }, 0); /* Must pass in a dummy argument for C99 compatibility. */
  33292. if (pDeviceInfo->nativeDataFormats[0].sampleRate == 0) {
  33293. return MA_NO_DEVICE;
  33294. }
  33295. pDeviceInfo->nativeDataFormatCount = 1;
  33296. return MA_SUCCESS;
  33297. }
  33298. #if !defined(MA_USE_AUDIO_WORKLETS)
  33299. static void ma_device_uninit_by_index__webaudio(ma_device* pDevice, ma_device_type deviceType, int deviceIndex)
  33300. {
  33301. MA_ASSERT(pDevice != NULL);
  33302. EM_ASM({
  33303. var device = miniaudio.get_device_by_index($0);
  33304. var pAllocationCallbacks = $3;
  33305. /* Make sure all nodes are disconnected and marked for collection. */
  33306. if (device.scriptNode !== undefined) {
  33307. device.scriptNode.onaudioprocess = function(e) {}; /* We want to reset the callback to ensure it doesn't get called after AudioContext.close() has returned. Shouldn't happen since we're disconnecting, but just to be safe... */
  33308. device.scriptNode.disconnect();
  33309. device.scriptNode = undefined;
  33310. }
  33311. if (device.streamNode !== undefined) {
  33312. device.streamNode.disconnect();
  33313. device.streamNode = undefined;
  33314. }
  33315. /*
  33316. Stop the device. I think there is a chance the callback could get fired after calling this, hence why we want
  33317. to clear the callback before closing.
  33318. */
  33319. device.webaudio.close();
  33320. device.webaudio = undefined;
  33321. /* Can't forget to free the intermediary buffer. This is the buffer that's shared between JavaScript and C. */
  33322. if (device.intermediaryBuffer !== undefined) {
  33323. _ma_free_emscripten(device.intermediaryBuffer, pAllocationCallbacks);
  33324. device.intermediaryBuffer = undefined;
  33325. device.intermediaryBufferView = undefined;
  33326. device.intermediaryBufferSizeInBytes = undefined;
  33327. }
  33328. /* Make sure the device is untracked so the slot can be reused later. */
  33329. miniaudio.untrack_device_by_index($0);
  33330. }, deviceIndex, deviceType, &pDevice->pContext->allocationCallbacks);
  33331. }
  33332. #endif
  33333. static void ma_device_uninit_by_type__webaudio(ma_device* pDevice, ma_device_type deviceType)
  33334. {
  33335. MA_ASSERT(pDevice != NULL);
  33336. MA_ASSERT(deviceType == ma_device_type_capture || deviceType == ma_device_type_playback);
  33337. #if defined(MA_USE_AUDIO_WORKLETS)
  33338. if (deviceType == ma_device_type_capture) {
  33339. ma_free(pDevice->webaudio.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks);
  33340. ma_free(pDevice->webaudio.pStackBufferCapture, &pDevice->pContext->allocationCallbacks);
  33341. emscripten_destroy_audio_context(pDevice->webaudio.audioContextCapture);
  33342. } else {
  33343. ma_free(pDevice->webaudio.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks);
  33344. ma_free(pDevice->webaudio.pStackBufferPlayback, &pDevice->pContext->allocationCallbacks);
  33345. emscripten_destroy_audio_context(pDevice->webaudio.audioContextPlayback);
  33346. }
  33347. #else
  33348. if (deviceType == ma_device_type_capture) {
  33349. ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_capture, pDevice->webaudio.indexCapture);
  33350. } else {
  33351. ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_playback, pDevice->webaudio.indexPlayback);
  33352. }
  33353. #endif
  33354. }
  33355. static ma_result ma_device_uninit__webaudio(ma_device* pDevice)
  33356. {
  33357. MA_ASSERT(pDevice != NULL);
  33358. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  33359. ma_device_uninit_by_type__webaudio(pDevice, ma_device_type_capture);
  33360. }
  33361. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  33362. ma_device_uninit_by_type__webaudio(pDevice, ma_device_type_playback);
  33363. }
  33364. return MA_SUCCESS;
  33365. }
  33366. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__webaudio(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  33367. {
  33368. #if defined(MA_USE_AUDIO_WORKLETS)
  33369. (void)pDescriptor;
  33370. (void)nativeSampleRate;
  33371. (void)performanceProfile;
  33372. return 256;
  33373. #else
  33374. /*
  33375. There have been reports of the default buffer size being too small on some browsers. If we're using
  33376. the default buffer size, we'll make sure the period size is bigger than our standard defaults.
  33377. */
  33378. ma_uint32 periodSizeInFrames;
  33379. if (pDescriptor->periodSizeInFrames == 0) {
  33380. if (pDescriptor->periodSizeInMilliseconds == 0) {
  33381. if (performanceProfile == ma_performance_profile_low_latency) {
  33382. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(33, nativeSampleRate); /* 1 frame @ 30 FPS */
  33383. } else {
  33384. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(333, nativeSampleRate);
  33385. }
  33386. } else {
  33387. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate);
  33388. }
  33389. } else {
  33390. periodSizeInFrames = pDescriptor->periodSizeInFrames;
  33391. }
  33392. /* The size of the buffer must be a power of 2 and between 256 and 16384. */
  33393. if (periodSizeInFrames < 256) {
  33394. periodSizeInFrames = 256;
  33395. } else if (periodSizeInFrames > 16384) {
  33396. periodSizeInFrames = 16384;
  33397. } else {
  33398. periodSizeInFrames = ma_next_power_of_2(periodSizeInFrames);
  33399. }
  33400. return periodSizeInFrames;
  33401. #endif
  33402. }
  33403. #if defined(MA_USE_AUDIO_WORKLETS)
  33404. typedef struct
  33405. {
  33406. ma_device* pDevice;
  33407. const ma_device_config* pConfig;
  33408. ma_device_descriptor* pDescriptor;
  33409. ma_device_type deviceType;
  33410. ma_uint32 channels;
  33411. } ma_audio_worklet_thread_initialized_data;
  33412. static EM_BOOL ma_audio_worklet_process_callback__webaudio(int inputCount, const AudioSampleFrame* pInputs, int outputCount, AudioSampleFrame* pOutputs, int paramCount, const AudioParamFrame* pParams, void* pUserData)
  33413. {
  33414. ma_device* pDevice = (ma_device*)pUserData;
  33415. ma_uint32 frameCount;
  33416. ma_uint32 framesProcessed;
  33417. (void)paramCount;
  33418. (void)pParams;
  33419. /*
  33420. The Emscripten documentation says that it'll always be 128 frames being passed in. Hard coding it like that feels
  33421. like a very bad idea to me. Even if it's hard coded in the backend, the API and documentation should always refer
  33422. to variables instead of a hard coded number. In any case, will follow along for the time being.
  33423. Unfortunately the audio data is not interleaved so we'll need to convert it before we give the data to miniaudio
  33424. for further processing.
  33425. */
  33426. frameCount = 128;
  33427. /* Run the conversion logic in a loop for robustness. */
  33428. framesProcessed = 0;
  33429. while (framesProcessed < frameCount) {
  33430. ma_uint32 framesToProcessThisIteration = frameCount - framesProcessed;
  33431. if (inputCount > 0) {
  33432. if (framesToProcessThisIteration > pDevice->webaudio.intermediaryBufferSizeInFramesPlayback) {
  33433. framesToProcessThisIteration = pDevice->webaudio.intermediaryBufferSizeInFramesPlayback;
  33434. }
  33435. /* Input data needs to be interleaved before we hand it to the client. */
  33436. for (ma_uint32 iFrame = 0; iFrame < framesToProcessThisIteration; iFrame += 1) {
  33437. for (ma_uint32 iChannel = 0; iChannel < pDevice->capture.internalChannels; iChannel += 1) {
  33438. pDevice->webaudio.pIntermediaryBufferCapture[iFrame*pDevice->capture.internalChannels + iChannel] = pInputs[0].data[frameCount*iChannel + framesProcessed + iFrame];
  33439. }
  33440. }
  33441. ma_device_process_pcm_frames_capture__webaudio(pDevice, framesToProcessThisIteration, pDevice->webaudio.pIntermediaryBufferCapture);
  33442. }
  33443. if (outputCount > 0) {
  33444. ma_device_process_pcm_frames_playback__webaudio(pDevice, framesToProcessThisIteration, pDevice->webaudio.pIntermediaryBufferPlayback);
  33445. /* We've read the data from the client. Now we need to deinterleave the buffer and output to the output buffer. */
  33446. for (ma_uint32 iFrame = 0; iFrame < framesToProcessThisIteration; iFrame += 1) {
  33447. for (ma_uint32 iChannel = 0; iChannel < pDevice->playback.internalChannels; iChannel += 1) {
  33448. pOutputs[0].data[frameCount*iChannel + framesProcessed + iFrame] = pDevice->webaudio.pIntermediaryBufferPlayback[iFrame*pDevice->playback.internalChannels + iChannel];
  33449. }
  33450. }
  33451. }
  33452. framesProcessed += framesToProcessThisIteration;
  33453. }
  33454. return EM_TRUE;
  33455. }
  33456. static void ma_audio_worklet_processor_created__webaudio(EMSCRIPTEN_WEBAUDIO_T audioContext, EM_BOOL success, void* pUserData)
  33457. {
  33458. ma_audio_worklet_thread_initialized_data* pParameters = (ma_audio_worklet_thread_initialized_data*)pUserData;
  33459. EmscriptenAudioWorkletNodeCreateOptions workletNodeOptions;
  33460. EMSCRIPTEN_AUDIO_WORKLET_NODE_T workletNode;
  33461. int outputChannelCount = 0;
  33462. if (success == EM_FALSE) {
  33463. pParameters->pDevice->webaudio.isInitialized = MA_TRUE;
  33464. return;
  33465. }
  33466. MA_ZERO_OBJECT(&workletNodeOptions);
  33467. if (pParameters->deviceType == ma_device_type_capture) {
  33468. workletNodeOptions.numberOfInputs = 1;
  33469. } else {
  33470. outputChannelCount = (int)pParameters->channels; /* Safe cast. */
  33471. workletNodeOptions.numberOfOutputs = 1;
  33472. workletNodeOptions.outputChannelCounts = &outputChannelCount;
  33473. }
  33474. /* Here is where we create the node that will do our processing. */
  33475. workletNode = emscripten_create_wasm_audio_worklet_node(audioContext, "miniaudio", &workletNodeOptions, &ma_audio_worklet_process_callback__webaudio, pParameters->pDevice);
  33476. if (pParameters->deviceType == ma_device_type_capture) {
  33477. pParameters->pDevice->webaudio.workletNodeCapture = workletNode;
  33478. } else {
  33479. pParameters->pDevice->webaudio.workletNodePlayback = workletNode;
  33480. }
  33481. /*
  33482. With the worklet node created we can now attach it to the graph. This is done differently depending on whether or not
  33483. it's capture or playback mode.
  33484. */
  33485. if (pParameters->deviceType == ma_device_type_capture) {
  33486. EM_ASM({
  33487. var workletNode = emscriptenGetAudioObject($0);
  33488. var audioContext = emscriptenGetAudioObject($1);
  33489. navigator.mediaDevices.getUserMedia({audio:true, video:false})
  33490. .then(function(stream) {
  33491. audioContext.streamNode = audioContext.createMediaStreamSource(stream);
  33492. audioContext.streamNode.connect(workletNode);
  33493. /*
  33494. Now that the worklet node has been connected, do we need to inspect workletNode.channelCount
  33495. to check the actual channel count, or is it safe to assume it's always 2?
  33496. */
  33497. })
  33498. .catch(function(error) {
  33499. });
  33500. }, workletNode, audioContext);
  33501. } else {
  33502. EM_ASM({
  33503. var workletNode = emscriptenGetAudioObject($0);
  33504. var audioContext = emscriptenGetAudioObject($1);
  33505. workletNode.connect(audioContext.destination);
  33506. }, workletNode, audioContext);
  33507. }
  33508. pParameters->pDevice->webaudio.isInitialized = MA_TRUE;
  33509. ma_log_postf(ma_device_get_log(pParameters->pDevice), MA_LOG_LEVEL_DEBUG, "AudioWorklets: Created worklet node: %d\n", workletNode);
  33510. /* Our parameter data is no longer needed. */
  33511. ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks);
  33512. }
  33513. static void ma_audio_worklet_thread_initialized__webaudio(EMSCRIPTEN_WEBAUDIO_T audioContext, EM_BOOL success, void* pUserData)
  33514. {
  33515. ma_audio_worklet_thread_initialized_data* pParameters = (ma_audio_worklet_thread_initialized_data*)pUserData;
  33516. WebAudioWorkletProcessorCreateOptions workletProcessorOptions;
  33517. MA_ASSERT(pParameters != NULL);
  33518. if (success == EM_FALSE) {
  33519. pParameters->pDevice->webaudio.isInitialized = MA_TRUE;
  33520. return;
  33521. }
  33522. MA_ZERO_OBJECT(&workletProcessorOptions);
  33523. workletProcessorOptions.name = "miniaudio"; /* I'm not entirely sure what to call this. Does this need to be globally unique, or does it need only be unique for a given AudioContext? */
  33524. emscripten_create_wasm_audio_worklet_processor_async(audioContext, &workletProcessorOptions, ma_audio_worklet_processor_created__webaudio, pParameters);
  33525. }
  33526. #endif
  33527. static ma_result ma_device_init_by_type__webaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  33528. {
  33529. #if defined(MA_USE_AUDIO_WORKLETS)
  33530. EMSCRIPTEN_WEBAUDIO_T audioContext;
  33531. void* pStackBuffer;
  33532. size_t intermediaryBufferSizeInFrames;
  33533. float* pIntermediaryBuffer;
  33534. #endif
  33535. ma_uint32 channels;
  33536. ma_uint32 sampleRate;
  33537. ma_uint32 periodSizeInFrames;
  33538. MA_ASSERT(pDevice != NULL);
  33539. MA_ASSERT(pConfig != NULL);
  33540. MA_ASSERT(deviceType != ma_device_type_duplex);
  33541. if (deviceType == ma_device_type_capture && !ma_is_capture_supported__webaudio()) {
  33542. return MA_NO_DEVICE;
  33543. }
  33544. /* We're going to calculate some stuff in C just to simplify the JS code. */
  33545. channels = (pDescriptor->channels > 0) ? pDescriptor->channels : MA_DEFAULT_CHANNELS;
  33546. sampleRate = (pDescriptor->sampleRate > 0) ? pDescriptor->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  33547. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__webaudio(pDescriptor, sampleRate, pConfig->performanceProfile);
  33548. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "periodSizeInFrames = %d\n", (int)periodSizeInFrames);
  33549. #if defined(MA_USE_AUDIO_WORKLETS)
  33550. {
  33551. ma_audio_worklet_thread_initialized_data* pInitParameters;
  33552. EmscriptenWebAudioCreateAttributes audioContextAttributes;
  33553. audioContextAttributes.latencyHint = MA_WEBAUDIO_LATENCY_HINT_INTERACTIVE;
  33554. audioContextAttributes.sampleRate = sampleRate;
  33555. /* It's not clear if this can return an error. None of the tests in the Emscripten repository check for this, so neither am I for now. */
  33556. audioContext = emscripten_create_audio_context(&audioContextAttributes);
  33557. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "TRACE: AUDIO CONTEXT CREATED\n");
  33558. /*
  33559. We now need to create a worker thread. This is a bit weird because we need to allocate our
  33560. own buffer for the thread's stack. The stack needs to be aligned to 16 bytes. I'm going to
  33561. allocate this on the heap to keep it simple.
  33562. */
  33563. pStackBuffer = ma_aligned_malloc(MA_AUDIO_WORKLETS_THREAD_STACK_SIZE, 16, &pDevice->pContext->allocationCallbacks);
  33564. if (pStackBuffer == NULL) {
  33565. emscripten_destroy_audio_context(audioContext);
  33566. return MA_OUT_OF_MEMORY;
  33567. }
  33568. /*
  33569. We need an intermediary buffer for data conversion. WebAudio reports data in uninterleaved
  33570. format whereas we require it to be interleaved. We'll do this in chunks of 128 frames.
  33571. */
  33572. intermediaryBufferSizeInFrames = 128;
  33573. pIntermediaryBuffer = ma_malloc(intermediaryBufferSizeInFrames * channels * sizeof(float), &pDevice->pContext->allocationCallbacks);
  33574. if (pIntermediaryBuffer == NULL) {
  33575. ma_free(pStackBuffer, &pDevice->pContext->allocationCallbacks);
  33576. emscripten_destroy_audio_context(audioContext);
  33577. return MA_OUT_OF_MEMORY;
  33578. }
  33579. pInitParameters = ma_malloc(sizeof(*pInitParameters), &pDevice->pContext->allocationCallbacks);
  33580. if (pInitParameters == NULL) {
  33581. ma_free(pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks);
  33582. ma_free(pStackBuffer, &pDevice->pContext->allocationCallbacks);
  33583. emscripten_destroy_audio_context(audioContext);
  33584. return MA_OUT_OF_MEMORY;
  33585. }
  33586. pInitParameters->pDevice = pDevice;
  33587. pInitParameters->pConfig = pConfig;
  33588. pInitParameters->pDescriptor = pDescriptor;
  33589. pInitParameters->deviceType = deviceType;
  33590. pInitParameters->channels = channels;
  33591. /*
  33592. We need to flag the device as not yet initialized so we can wait on it later. Unfortunately all of
  33593. the Emscripten WebAudio stuff is asynchronous.
  33594. */
  33595. pDevice->webaudio.isInitialized = MA_FALSE;
  33596. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "TRACE: CREATING WORKLET\n");
  33597. emscripten_start_wasm_audio_worklet_thread_async(audioContext, pStackBuffer, MA_AUDIO_WORKLETS_THREAD_STACK_SIZE, ma_audio_worklet_thread_initialized__webaudio, pInitParameters);
  33598. /* We must wait for initialization to complete. We're just spinning here. The emscripten_sleep() call is why we need to build with `-sASYNCIFY`. */
  33599. while (pDevice->webaudio.isInitialized == MA_FALSE) {
  33600. emscripten_sleep(1);
  33601. }
  33602. /*
  33603. Now that initialization is finished we can go ahead and extract our channel count so that
  33604. miniaudio can set up a data converter at a higher level.
  33605. */
  33606. if (deviceType == ma_device_type_capture) {
  33607. /*
  33608. For capture we won't actually know what the channel count is. Everything I've seen seems
  33609. to indicate that the default channel count is 2, so I'm sticking with that.
  33610. */
  33611. channels = 2;
  33612. } else {
  33613. /* Get the channel count from the audio context. */
  33614. channels = (ma_uint32)EM_ASM_INT({
  33615. return emscriptenGetAudioObject($0).destination.channelCount;
  33616. }, audioContext);
  33617. }
  33618. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "TRACE: INITIALIZED. channels = %u\n", channels);
  33619. }
  33620. #else
  33621. /* We create the device on the JavaScript side and reference it using an index. We use this to make it possible to reference the device between JavaScript and C. */
  33622. int deviceIndex = EM_ASM_INT({
  33623. var channels = $0;
  33624. var sampleRate = $1;
  33625. var bufferSize = $2; /* In PCM frames. */
  33626. var isCapture = $3;
  33627. var pDevice = $4;
  33628. var pAllocationCallbacks = $5;
  33629. if (typeof(window.miniaudio) === 'undefined') {
  33630. return -1; /* Context not initialized. */
  33631. }
  33632. var device = {};
  33633. /* The AudioContext must be created in a suspended state. */
  33634. device.webaudio = new (window.AudioContext || window.webkitAudioContext)({sampleRate:sampleRate});
  33635. device.webaudio.suspend();
  33636. device.state = 1; /* ma_device_state_stopped */
  33637. /* We need an intermediary buffer which we use for JavaScript and C interop. This buffer stores interleaved f32 PCM data. */
  33638. device.intermediaryBufferSizeInBytes = channels * bufferSize * 4;
  33639. device.intermediaryBuffer = _ma_malloc_emscripten(device.intermediaryBufferSizeInBytes, pAllocationCallbacks);
  33640. device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, device.intermediaryBuffer, device.intermediaryBufferSizeInBytes);
  33641. /*
  33642. Both playback and capture devices use a ScriptProcessorNode for performing per-sample operations.
  33643. ScriptProcessorNode is actually deprecated so this is likely to be temporary. The way this works for playback is very simple. You just set a callback
  33644. that's periodically fired, just like a normal audio callback function. But apparently this design is "flawed" and is now deprecated in favour of
  33645. something called AudioWorklets which _forces_ you to load a _separate_ .js file at run time... nice... Hopefully ScriptProcessorNode will continue to
  33646. work for years to come, but this may need to change to use AudioSourceBufferNode instead, which I think is what Emscripten uses for it's built-in SDL
  33647. implementation. I'll be avoiding that insane AudioWorklet API like the plague...
  33648. For capture it is a bit unintuitive. We use the ScriptProccessorNode _only_ to get the raw PCM data. It is connected to an AudioContext just like the
  33649. playback case, however we just output silence to the AudioContext instead of passing any real data. It would make more sense to me to use the
  33650. MediaRecorder API, but unfortunately you need to specify a MIME time (Opus, Vorbis, etc.) for the binary blob that's returned to the client, but I've
  33651. been unable to figure out how to get this as raw PCM. The closest I can think is to use the MIME type for WAV files and just parse it, but I don't know
  33652. how well this would work. Although ScriptProccessorNode is deprecated, in practice it seems to have pretty good browser support so I'm leaving it like
  33653. this for now. If anyone knows how I could get raw PCM data using the MediaRecorder API please let me know!
  33654. */
  33655. device.scriptNode = device.webaudio.createScriptProcessor(bufferSize, (isCapture) ? channels : 0, (isCapture) ? 0 : channels);
  33656. if (isCapture) {
  33657. device.scriptNode.onaudioprocess = function(e) {
  33658. if (device.intermediaryBuffer === undefined) {
  33659. return; /* This means the device has been uninitialized. */
  33660. }
  33661. if (device.intermediaryBufferView.length == 0) {
  33662. /* Recreate intermediaryBufferView when losing reference to the underlying buffer, probably due to emscripten resizing heap. */
  33663. device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, device.intermediaryBuffer, device.intermediaryBufferSizeInBytes);
  33664. }
  33665. /* Make sure silence it output to the AudioContext destination. Not doing this will cause sound to come out of the speakers! */
  33666. for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
  33667. e.outputBuffer.getChannelData(iChannel).fill(0.0);
  33668. }
  33669. /* There are some situations where we may want to send silence to the client. */
  33670. var sendSilence = false;
  33671. if (device.streamNode === undefined) {
  33672. sendSilence = true;
  33673. }
  33674. /* Sanity check. This will never happen, right? */
  33675. if (e.inputBuffer.numberOfChannels != channels) {
  33676. console.log("Capture: Channel count mismatch. " + e.inputBufer.numberOfChannels + " != " + channels + ". Sending silence.");
  33677. sendSilence = true;
  33678. }
  33679. /* This looped design guards against the situation where e.inputBuffer is a different size to the original buffer size. Should never happen in practice. */
  33680. var totalFramesProcessed = 0;
  33681. while (totalFramesProcessed < e.inputBuffer.length) {
  33682. var framesRemaining = e.inputBuffer.length - totalFramesProcessed;
  33683. var framesToProcess = framesRemaining;
  33684. if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) {
  33685. framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4);
  33686. }
  33687. /* We need to do the reverse of the playback case. We need to interleave the input data and copy it into the intermediary buffer. Then we send it to the client. */
  33688. if (sendSilence) {
  33689. device.intermediaryBufferView.fill(0.0);
  33690. } else {
  33691. for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) {
  33692. for (var iChannel = 0; iChannel < e.inputBuffer.numberOfChannels; ++iChannel) {
  33693. device.intermediaryBufferView[iFrame*channels + iChannel] = e.inputBuffer.getChannelData(iChannel)[totalFramesProcessed + iFrame];
  33694. }
  33695. }
  33696. }
  33697. /* Send data to the client from our intermediary buffer. */
  33698. _ma_device_process_pcm_frames_capture__webaudio(pDevice, framesToProcess, device.intermediaryBuffer);
  33699. totalFramesProcessed += framesToProcess;
  33700. }
  33701. };
  33702. navigator.mediaDevices.getUserMedia({audio:true, video:false})
  33703. .then(function(stream) {
  33704. device.streamNode = device.webaudio.createMediaStreamSource(stream);
  33705. device.streamNode.connect(device.scriptNode);
  33706. device.scriptNode.connect(device.webaudio.destination);
  33707. })
  33708. .catch(function(error) {
  33709. /* I think this should output silence... */
  33710. device.scriptNode.connect(device.webaudio.destination);
  33711. });
  33712. } else {
  33713. device.scriptNode.onaudioprocess = function(e) {
  33714. if (device.intermediaryBuffer === undefined) {
  33715. return; /* This means the device has been uninitialized. */
  33716. }
  33717. if(device.intermediaryBufferView.length == 0) {
  33718. /* Recreate intermediaryBufferView when losing reference to the underlying buffer, probably due to emscripten resizing heap. */
  33719. device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, device.intermediaryBuffer, device.intermediaryBufferSizeInBytes);
  33720. }
  33721. var outputSilence = false;
  33722. /* Sanity check. This will never happen, right? */
  33723. if (e.outputBuffer.numberOfChannels != channels) {
  33724. console.log("Playback: Channel count mismatch. " + e.outputBufer.numberOfChannels + " != " + channels + ". Outputting silence.");
  33725. outputSilence = true;
  33726. return;
  33727. }
  33728. /* This looped design guards against the situation where e.outputBuffer is a different size to the original buffer size. Should never happen in practice. */
  33729. var totalFramesProcessed = 0;
  33730. while (totalFramesProcessed < e.outputBuffer.length) {
  33731. var framesRemaining = e.outputBuffer.length - totalFramesProcessed;
  33732. var framesToProcess = framesRemaining;
  33733. if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) {
  33734. framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4);
  33735. }
  33736. /* Read data from the client into our intermediary buffer. */
  33737. _ma_device_process_pcm_frames_playback__webaudio(pDevice, framesToProcess, device.intermediaryBuffer);
  33738. /* At this point we'll have data in our intermediary buffer which we now need to deinterleave and copy over to the output buffers. */
  33739. if (outputSilence) {
  33740. for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
  33741. e.outputBuffer.getChannelData(iChannel).fill(0.0);
  33742. }
  33743. } else {
  33744. for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
  33745. var outputBuffer = e.outputBuffer.getChannelData(iChannel);
  33746. var intermediaryBuffer = device.intermediaryBufferView;
  33747. for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) {
  33748. outputBuffer[totalFramesProcessed + iFrame] = intermediaryBuffer[iFrame*channels + iChannel];
  33749. }
  33750. }
  33751. }
  33752. totalFramesProcessed += framesToProcess;
  33753. }
  33754. };
  33755. device.scriptNode.connect(device.webaudio.destination);
  33756. }
  33757. return miniaudio.track_device(device);
  33758. }, channels, sampleRate, periodSizeInFrames, deviceType == ma_device_type_capture, pDevice, &pDevice->pContext->allocationCallbacks);
  33759. if (deviceIndex < 0) {
  33760. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  33761. }
  33762. #endif
  33763. #if defined(MA_USE_AUDIO_WORKLETS)
  33764. if (deviceType == ma_device_type_capture) {
  33765. pDevice->webaudio.audioContextCapture = audioContext;
  33766. pDevice->webaudio.pStackBufferCapture = pStackBuffer;
  33767. pDevice->webaudio.intermediaryBufferSizeInFramesCapture = intermediaryBufferSizeInFrames;
  33768. pDevice->webaudio.pIntermediaryBufferCapture = pIntermediaryBuffer;
  33769. } else {
  33770. pDevice->webaudio.audioContextPlayback = audioContext;
  33771. pDevice->webaudio.pStackBufferPlayback = pStackBuffer;
  33772. pDevice->webaudio.intermediaryBufferSizeInFramesPlayback = intermediaryBufferSizeInFrames;
  33773. pDevice->webaudio.pIntermediaryBufferPlayback = pIntermediaryBuffer;
  33774. }
  33775. #else
  33776. if (deviceType == ma_device_type_capture) {
  33777. pDevice->webaudio.indexCapture = deviceIndex;
  33778. } else {
  33779. pDevice->webaudio.indexPlayback = deviceIndex;
  33780. }
  33781. #endif
  33782. pDescriptor->format = ma_format_f32;
  33783. pDescriptor->channels = channels;
  33784. ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), pDescriptor->channels);
  33785. pDescriptor->periodSizeInFrames = periodSizeInFrames;
  33786. pDescriptor->periodCount = 1;
  33787. #if defined(MA_USE_AUDIO_WORKLETS)
  33788. pDescriptor->sampleRate = sampleRate; /* Is this good enough to be used in the general case? */
  33789. #else
  33790. pDescriptor->sampleRate = EM_ASM_INT({ return miniaudio.get_device_by_index($0).webaudio.sampleRate; }, deviceIndex);
  33791. #endif
  33792. return MA_SUCCESS;
  33793. }
  33794. static ma_result ma_device_init__webaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  33795. {
  33796. ma_result result;
  33797. if (pConfig->deviceType == ma_device_type_loopback) {
  33798. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  33799. }
  33800. /* No exclusive mode with Web Audio. */
  33801. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  33802. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  33803. return MA_SHARE_MODE_NOT_SUPPORTED;
  33804. }
  33805. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  33806. result = ma_device_init_by_type__webaudio(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  33807. if (result != MA_SUCCESS) {
  33808. return result;
  33809. }
  33810. }
  33811. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  33812. result = ma_device_init_by_type__webaudio(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  33813. if (result != MA_SUCCESS) {
  33814. if (pConfig->deviceType == ma_device_type_duplex) {
  33815. ma_device_uninit_by_type__webaudio(pDevice, ma_device_type_capture);
  33816. }
  33817. return result;
  33818. }
  33819. }
  33820. return MA_SUCCESS;
  33821. }
  33822. static ma_result ma_device_start__webaudio(ma_device* pDevice)
  33823. {
  33824. MA_ASSERT(pDevice != NULL);
  33825. #if defined(MA_USE_AUDIO_WORKLETS)
  33826. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  33827. emscripten_resume_audio_context_sync(pDevice->webaudio.audioContextCapture);
  33828. }
  33829. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  33830. emscripten_resume_audio_context_sync(pDevice->webaudio.audioContextPlayback);
  33831. }
  33832. #else
  33833. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  33834. EM_ASM({
  33835. var device = miniaudio.get_device_by_index($0);
  33836. device.webaudio.resume();
  33837. device.state = 2; /* ma_device_state_started */
  33838. }, pDevice->webaudio.indexCapture);
  33839. }
  33840. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  33841. EM_ASM({
  33842. var device = miniaudio.get_device_by_index($0);
  33843. device.webaudio.resume();
  33844. device.state = 2; /* ma_device_state_started */
  33845. }, pDevice->webaudio.indexPlayback);
  33846. }
  33847. #endif
  33848. return MA_SUCCESS;
  33849. }
  33850. static ma_result ma_device_stop__webaudio(ma_device* pDevice)
  33851. {
  33852. MA_ASSERT(pDevice != NULL);
  33853. /*
  33854. From the WebAudio API documentation for AudioContext.suspend():
  33855. Suspends the progression of AudioContext's currentTime, allows any current context processing blocks that are already processed to be played to the
  33856. destination, and then allows the system to release its claim on audio hardware.
  33857. I read this to mean that "any current context processing blocks" are processed by suspend() - i.e. They they are drained. We therefore shouldn't need to
  33858. do any kind of explicit draining.
  33859. */
  33860. #if defined(MA_USE_AUDIO_WORKLETS)
  33861. /* I can't seem to find a way to suspend an AudioContext via the C Emscripten API. Is this an oversight? */
  33862. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  33863. EM_ASM({
  33864. emscriptenGetAudioObject($0).suspend();
  33865. }, pDevice->webaudio.audioContextCapture);
  33866. }
  33867. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  33868. EM_ASM({
  33869. emscriptenGetAudioObject($0).suspend();
  33870. }, pDevice->webaudio.audioContextPlayback);
  33871. }
  33872. #else
  33873. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  33874. EM_ASM({
  33875. var device = miniaudio.get_device_by_index($0);
  33876. device.webaudio.suspend();
  33877. device.state = 1; /* ma_device_state_stopped */
  33878. }, pDevice->webaudio.indexCapture);
  33879. }
  33880. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  33881. EM_ASM({
  33882. var device = miniaudio.get_device_by_index($0);
  33883. device.webaudio.suspend();
  33884. device.state = 1; /* ma_device_state_stopped */
  33885. }, pDevice->webaudio.indexPlayback);
  33886. }
  33887. #endif
  33888. ma_device__on_notification_stopped(pDevice);
  33889. return MA_SUCCESS;
  33890. }
  33891. static ma_result ma_context_uninit__webaudio(ma_context* pContext)
  33892. {
  33893. MA_ASSERT(pContext != NULL);
  33894. MA_ASSERT(pContext->backend == ma_backend_webaudio);
  33895. (void)pContext; /* Unused. */
  33896. /* Remove the global miniaudio object from window if there are no more references to it. */
  33897. EM_ASM({
  33898. if (typeof(window.miniaudio) !== 'undefined') {
  33899. window.miniaudio.referenceCount--;
  33900. if (window.miniaudio.referenceCount === 0) {
  33901. delete window.miniaudio;
  33902. }
  33903. }
  33904. });
  33905. return MA_SUCCESS;
  33906. }
  33907. static ma_result ma_context_init__webaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  33908. {
  33909. int resultFromJS;
  33910. MA_ASSERT(pContext != NULL);
  33911. (void)pConfig; /* Unused. */
  33912. /* Here is where our global JavaScript object is initialized. */
  33913. resultFromJS = EM_ASM_INT({
  33914. if (typeof window === 'undefined' || (window.AudioContext || window.webkitAudioContext) === undefined) {
  33915. return 0; /* Web Audio not supported. */
  33916. }
  33917. if (typeof(window.miniaudio) === 'undefined') {
  33918. window.miniaudio = {
  33919. referenceCount: 0
  33920. };
  33921. miniaudio.devices = []; /* Device cache for mapping devices to indexes for JavaScript/C interop. */
  33922. miniaudio.track_device = function(device) {
  33923. /* Try inserting into a free slot first. */
  33924. for (var iDevice = 0; iDevice < miniaudio.devices.length; ++iDevice) {
  33925. if (miniaudio.devices[iDevice] == null) {
  33926. miniaudio.devices[iDevice] = device;
  33927. return iDevice;
  33928. }
  33929. }
  33930. /* Getting here means there is no empty slots in the array so we just push to the end. */
  33931. miniaudio.devices.push(device);
  33932. return miniaudio.devices.length - 1;
  33933. };
  33934. miniaudio.untrack_device_by_index = function(deviceIndex) {
  33935. /* We just set the device's slot to null. The slot will get reused in the next call to ma_track_device. */
  33936. miniaudio.devices[deviceIndex] = null;
  33937. /* Trim the array if possible. */
  33938. while (miniaudio.devices.length > 0) {
  33939. if (miniaudio.devices[miniaudio.devices.length-1] == null) {
  33940. miniaudio.devices.pop();
  33941. } else {
  33942. break;
  33943. }
  33944. }
  33945. };
  33946. miniaudio.untrack_device = function(device) {
  33947. for (var iDevice = 0; iDevice < miniaudio.devices.length; ++iDevice) {
  33948. if (miniaudio.devices[iDevice] == device) {
  33949. return miniaudio.untrack_device_by_index(iDevice);
  33950. }
  33951. }
  33952. };
  33953. miniaudio.get_device_by_index = function(deviceIndex) {
  33954. return miniaudio.devices[deviceIndex];
  33955. };
  33956. miniaudio.unlock_event_types = (function(){
  33957. return ['touchstart', 'touchend', 'click'];
  33958. })();
  33959. miniaudio.unlock = function() {
  33960. for(var i = 0; i < miniaudio.devices.length; ++i) {
  33961. var device = miniaudio.devices[i];
  33962. if (device != null && device.webaudio != null && device.state === 2 /* ma_device_state_started */) {
  33963. device.webaudio.resume();
  33964. }
  33965. }
  33966. miniaudio.unlock_event_types.map(function(event_type) {
  33967. document.removeEventListener(event_type, miniaudio.unlock, true);
  33968. });
  33969. };
  33970. miniaudio.unlock_event_types.map(function(event_type) {
  33971. document.addEventListener(event_type, miniaudio.unlock, true);
  33972. });
  33973. }
  33974. window.miniaudio.referenceCount++;
  33975. return 1;
  33976. }, 0); /* Must pass in a dummy argument for C99 compatibility. */
  33977. if (resultFromJS != 1) {
  33978. return MA_FAILED_TO_INIT_BACKEND;
  33979. }
  33980. pCallbacks->onContextInit = ma_context_init__webaudio;
  33981. pCallbacks->onContextUninit = ma_context_uninit__webaudio;
  33982. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__webaudio;
  33983. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__webaudio;
  33984. pCallbacks->onDeviceInit = ma_device_init__webaudio;
  33985. pCallbacks->onDeviceUninit = ma_device_uninit__webaudio;
  33986. pCallbacks->onDeviceStart = ma_device_start__webaudio;
  33987. pCallbacks->onDeviceStop = ma_device_stop__webaudio;
  33988. pCallbacks->onDeviceRead = NULL; /* Not needed because WebAudio is asynchronous. */
  33989. pCallbacks->onDeviceWrite = NULL; /* Not needed because WebAudio is asynchronous. */
  33990. pCallbacks->onDeviceDataLoop = NULL; /* Not needed because WebAudio is asynchronous. */
  33991. return MA_SUCCESS;
  33992. }
  33993. #endif /* Web Audio */
  33994. static ma_bool32 ma__is_channel_map_valid(const ma_channel* pChannelMap, ma_uint32 channels)
  33995. {
  33996. /* A blank channel map should be allowed, in which case it should use an appropriate default which will depend on context. */
  33997. if (pChannelMap != NULL && pChannelMap[0] != MA_CHANNEL_NONE) {
  33998. ma_uint32 iChannel;
  33999. if (channels == 0 || channels > MA_MAX_CHANNELS) {
  34000. return MA_FALSE; /* Channel count out of range. */
  34001. }
  34002. /* A channel cannot be present in the channel map more than once. */
  34003. for (iChannel = 0; iChannel < channels; ++iChannel) {
  34004. ma_uint32 jChannel;
  34005. for (jChannel = iChannel + 1; jChannel < channels; ++jChannel) {
  34006. if (pChannelMap[iChannel] == pChannelMap[jChannel]) {
  34007. return MA_FALSE;
  34008. }
  34009. }
  34010. }
  34011. }
  34012. return MA_TRUE;
  34013. }
  34014. static ma_bool32 ma_context_is_backend_asynchronous(ma_context* pContext)
  34015. {
  34016. MA_ASSERT(pContext != NULL);
  34017. if (pContext->callbacks.onDeviceRead == NULL && pContext->callbacks.onDeviceWrite == NULL) {
  34018. if (pContext->callbacks.onDeviceDataLoop == NULL) {
  34019. return MA_TRUE;
  34020. } else {
  34021. return MA_FALSE;
  34022. }
  34023. } else {
  34024. return MA_FALSE;
  34025. }
  34026. }
  34027. static ma_result ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType)
  34028. {
  34029. ma_result result;
  34030. MA_ASSERT(pDevice != NULL);
  34031. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  34032. if (pDevice->capture.format == ma_format_unknown) {
  34033. pDevice->capture.format = pDevice->capture.internalFormat;
  34034. }
  34035. if (pDevice->capture.channels == 0) {
  34036. pDevice->capture.channels = pDevice->capture.internalChannels;
  34037. }
  34038. if (pDevice->capture.channelMap[0] == MA_CHANNEL_NONE) {
  34039. MA_ASSERT(pDevice->capture.channels <= MA_MAX_CHANNELS);
  34040. if (pDevice->capture.internalChannels == pDevice->capture.channels) {
  34041. ma_channel_map_copy(pDevice->capture.channelMap, pDevice->capture.internalChannelMap, pDevice->capture.channels);
  34042. } else {
  34043. if (pDevice->capture.channelMixMode == ma_channel_mix_mode_simple) {
  34044. ma_channel_map_init_blank(pDevice->capture.channelMap, pDevice->capture.channels);
  34045. } else {
  34046. ma_channel_map_init_standard(ma_standard_channel_map_default, pDevice->capture.channelMap, ma_countof(pDevice->capture.channelMap), pDevice->capture.channels);
  34047. }
  34048. }
  34049. }
  34050. }
  34051. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34052. if (pDevice->playback.format == ma_format_unknown) {
  34053. pDevice->playback.format = pDevice->playback.internalFormat;
  34054. }
  34055. if (pDevice->playback.channels == 0) {
  34056. pDevice->playback.channels = pDevice->playback.internalChannels;
  34057. }
  34058. if (pDevice->playback.channelMap[0] == MA_CHANNEL_NONE) {
  34059. MA_ASSERT(pDevice->playback.channels <= MA_MAX_CHANNELS);
  34060. if (pDevice->playback.internalChannels == pDevice->playback.channels) {
  34061. ma_channel_map_copy(pDevice->playback.channelMap, pDevice->playback.internalChannelMap, pDevice->playback.channels);
  34062. } else {
  34063. if (pDevice->playback.channelMixMode == ma_channel_mix_mode_simple) {
  34064. ma_channel_map_init_blank(pDevice->playback.channelMap, pDevice->playback.channels);
  34065. } else {
  34066. ma_channel_map_init_standard(ma_standard_channel_map_default, pDevice->playback.channelMap, ma_countof(pDevice->playback.channelMap), pDevice->playback.channels);
  34067. }
  34068. }
  34069. }
  34070. }
  34071. if (pDevice->sampleRate == 0) {
  34072. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  34073. pDevice->sampleRate = pDevice->capture.internalSampleRate;
  34074. } else {
  34075. pDevice->sampleRate = pDevice->playback.internalSampleRate;
  34076. }
  34077. }
  34078. /* Data converters. */
  34079. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  34080. /* Converting from internal device format to client format. */
  34081. ma_data_converter_config converterConfig = ma_data_converter_config_init_default();
  34082. converterConfig.formatIn = pDevice->capture.internalFormat;
  34083. converterConfig.channelsIn = pDevice->capture.internalChannels;
  34084. converterConfig.sampleRateIn = pDevice->capture.internalSampleRate;
  34085. converterConfig.pChannelMapIn = pDevice->capture.internalChannelMap;
  34086. converterConfig.formatOut = pDevice->capture.format;
  34087. converterConfig.channelsOut = pDevice->capture.channels;
  34088. converterConfig.sampleRateOut = pDevice->sampleRate;
  34089. converterConfig.pChannelMapOut = pDevice->capture.channelMap;
  34090. converterConfig.channelMixMode = pDevice->capture.channelMixMode;
  34091. converterConfig.calculateLFEFromSpatialChannels = pDevice->capture.calculateLFEFromSpatialChannels;
  34092. converterConfig.allowDynamicSampleRate = MA_FALSE;
  34093. converterConfig.resampling.algorithm = pDevice->resampling.algorithm;
  34094. converterConfig.resampling.linear.lpfOrder = pDevice->resampling.linear.lpfOrder;
  34095. converterConfig.resampling.pBackendVTable = pDevice->resampling.pBackendVTable;
  34096. converterConfig.resampling.pBackendUserData = pDevice->resampling.pBackendUserData;
  34097. /* Make sure the old converter is uninitialized first. */
  34098. if (ma_device_get_state(pDevice) != ma_device_state_uninitialized) {
  34099. ma_data_converter_uninit(&pDevice->capture.converter, &pDevice->pContext->allocationCallbacks);
  34100. }
  34101. result = ma_data_converter_init(&converterConfig, &pDevice->pContext->allocationCallbacks, &pDevice->capture.converter);
  34102. if (result != MA_SUCCESS) {
  34103. return result;
  34104. }
  34105. }
  34106. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34107. /* Converting from client format to device format. */
  34108. ma_data_converter_config converterConfig = ma_data_converter_config_init_default();
  34109. converterConfig.formatIn = pDevice->playback.format;
  34110. converterConfig.channelsIn = pDevice->playback.channels;
  34111. converterConfig.sampleRateIn = pDevice->sampleRate;
  34112. converterConfig.pChannelMapIn = pDevice->playback.channelMap;
  34113. converterConfig.formatOut = pDevice->playback.internalFormat;
  34114. converterConfig.channelsOut = pDevice->playback.internalChannels;
  34115. converterConfig.sampleRateOut = pDevice->playback.internalSampleRate;
  34116. converterConfig.pChannelMapOut = pDevice->playback.internalChannelMap;
  34117. converterConfig.channelMixMode = pDevice->playback.channelMixMode;
  34118. converterConfig.calculateLFEFromSpatialChannels = pDevice->playback.calculateLFEFromSpatialChannels;
  34119. converterConfig.allowDynamicSampleRate = MA_FALSE;
  34120. converterConfig.resampling.algorithm = pDevice->resampling.algorithm;
  34121. converterConfig.resampling.linear.lpfOrder = pDevice->resampling.linear.lpfOrder;
  34122. converterConfig.resampling.pBackendVTable = pDevice->resampling.pBackendVTable;
  34123. converterConfig.resampling.pBackendUserData = pDevice->resampling.pBackendUserData;
  34124. /* Make sure the old converter is uninitialized first. */
  34125. if (ma_device_get_state(pDevice) != ma_device_state_uninitialized) {
  34126. ma_data_converter_uninit(&pDevice->playback.converter, &pDevice->pContext->allocationCallbacks);
  34127. }
  34128. result = ma_data_converter_init(&converterConfig, &pDevice->pContext->allocationCallbacks, &pDevice->playback.converter);
  34129. if (result != MA_SUCCESS) {
  34130. return result;
  34131. }
  34132. }
  34133. /*
  34134. If the device is doing playback (ma_device_type_playback or ma_device_type_duplex), there's
  34135. a couple of situations where we'll need a heap allocated cache.
  34136. The first is a duplex device for backends that use a callback for data delivery. The reason
  34137. this is needed is that the input stage needs to have a buffer to place the input data while it
  34138. waits for the playback stage, after which the miniaudio data callback will get fired. This is
  34139. not needed for backends that use a blocking API because miniaudio manages temporary buffers on
  34140. the stack to achieve this.
  34141. The other situation is when the data converter does not have the ability to query the number
  34142. of input frames that are required in order to process a given number of output frames. When
  34143. performing data conversion, it's useful if miniaudio know exactly how many frames it needs
  34144. from the client in order to generate a given number of output frames. This way, only exactly
  34145. the number of frames are needed to be read from the client which means no cache is necessary.
  34146. On the other hand, if miniaudio doesn't know how many frames to read, it is forced to read
  34147. in fixed sized chunks and then cache any residual unused input frames, those of which will be
  34148. processed at a later stage.
  34149. */
  34150. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34151. ma_uint64 unused;
  34152. pDevice->playback.inputCacheConsumed = 0;
  34153. pDevice->playback.inputCacheRemaining = 0;
  34154. if (pDevice->type == ma_device_type_duplex || /* Duplex. backend may decide to use ma_device_handle_backend_data_callback() which will require this cache. */
  34155. ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, 1, &unused) != MA_SUCCESS) /* Data conversion required input frame calculation not supported. */
  34156. {
  34157. /* We need a heap allocated cache. We want to size this based on the period size. */
  34158. void* pNewInputCache;
  34159. ma_uint64 newInputCacheCap;
  34160. ma_uint64 newInputCacheSizeInBytes;
  34161. newInputCacheCap = ma_calculate_frame_count_after_resampling(pDevice->playback.internalSampleRate, pDevice->sampleRate, pDevice->playback.internalPeriodSizeInFrames);
  34162. newInputCacheSizeInBytes = newInputCacheCap * ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  34163. if (newInputCacheSizeInBytes > MA_SIZE_MAX) {
  34164. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  34165. pDevice->playback.pInputCache = NULL;
  34166. pDevice->playback.inputCacheCap = 0;
  34167. return MA_OUT_OF_MEMORY; /* Allocation too big. Should never hit this, but makes the cast below safer for 32-bit builds. */
  34168. }
  34169. pNewInputCache = ma_realloc(pDevice->playback.pInputCache, (size_t)newInputCacheSizeInBytes, &pDevice->pContext->allocationCallbacks);
  34170. if (pNewInputCache == NULL) {
  34171. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  34172. pDevice->playback.pInputCache = NULL;
  34173. pDevice->playback.inputCacheCap = 0;
  34174. return MA_OUT_OF_MEMORY;
  34175. }
  34176. pDevice->playback.pInputCache = pNewInputCache;
  34177. pDevice->playback.inputCacheCap = newInputCacheCap;
  34178. } else {
  34179. /* Heap allocation not required. Make sure we clear out the old cache just in case this function was called in response to a route change. */
  34180. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  34181. pDevice->playback.pInputCache = NULL;
  34182. pDevice->playback.inputCacheCap = 0;
  34183. }
  34184. }
  34185. return MA_SUCCESS;
  34186. }
  34187. MA_API ma_result ma_device_post_init(ma_device* pDevice, ma_device_type deviceType, const ma_device_descriptor* pDescriptorPlayback, const ma_device_descriptor* pDescriptorCapture)
  34188. {
  34189. ma_result result;
  34190. if (pDevice == NULL) {
  34191. return MA_INVALID_ARGS;
  34192. }
  34193. /* Capture. */
  34194. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  34195. if (ma_device_descriptor_is_valid(pDescriptorCapture) == MA_FALSE) {
  34196. return MA_INVALID_ARGS;
  34197. }
  34198. pDevice->capture.internalFormat = pDescriptorCapture->format;
  34199. pDevice->capture.internalChannels = pDescriptorCapture->channels;
  34200. pDevice->capture.internalSampleRate = pDescriptorCapture->sampleRate;
  34201. MA_COPY_MEMORY(pDevice->capture.internalChannelMap, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
  34202. pDevice->capture.internalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
  34203. pDevice->capture.internalPeriods = pDescriptorCapture->periodCount;
  34204. if (pDevice->capture.internalPeriodSizeInFrames == 0) {
  34205. pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptorCapture->periodSizeInMilliseconds, pDescriptorCapture->sampleRate);
  34206. }
  34207. }
  34208. /* Playback. */
  34209. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34210. if (ma_device_descriptor_is_valid(pDescriptorPlayback) == MA_FALSE) {
  34211. return MA_INVALID_ARGS;
  34212. }
  34213. pDevice->playback.internalFormat = pDescriptorPlayback->format;
  34214. pDevice->playback.internalChannels = pDescriptorPlayback->channels;
  34215. pDevice->playback.internalSampleRate = pDescriptorPlayback->sampleRate;
  34216. MA_COPY_MEMORY(pDevice->playback.internalChannelMap, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
  34217. pDevice->playback.internalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
  34218. pDevice->playback.internalPeriods = pDescriptorPlayback->periodCount;
  34219. if (pDevice->playback.internalPeriodSizeInFrames == 0) {
  34220. pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptorPlayback->periodSizeInMilliseconds, pDescriptorPlayback->sampleRate);
  34221. }
  34222. }
  34223. /*
  34224. The name of the device can be retrieved from device info. This may be temporary and replaced with a `ma_device_get_info(pDevice, deviceType)` instead.
  34225. For loopback devices, we need to retrieve the name of the playback device.
  34226. */
  34227. {
  34228. ma_device_info deviceInfo;
  34229. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  34230. result = ma_device_get_info(pDevice, (deviceType == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, &deviceInfo);
  34231. if (result == MA_SUCCESS) {
  34232. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), deviceInfo.name, (size_t)-1);
  34233. } else {
  34234. /* We failed to retrieve the device info. Fall back to a default name. */
  34235. if (pDescriptorCapture->pDeviceID == NULL) {
  34236. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  34237. } else {
  34238. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "Capture Device", (size_t)-1);
  34239. }
  34240. }
  34241. }
  34242. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34243. result = ma_device_get_info(pDevice, ma_device_type_playback, &deviceInfo);
  34244. if (result == MA_SUCCESS) {
  34245. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), deviceInfo.name, (size_t)-1);
  34246. } else {
  34247. /* We failed to retrieve the device info. Fall back to a default name. */
  34248. if (pDescriptorPlayback->pDeviceID == NULL) {
  34249. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  34250. } else {
  34251. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "Playback Device", (size_t)-1);
  34252. }
  34253. }
  34254. }
  34255. }
  34256. /* Update data conversion. */
  34257. return ma_device__post_init_setup(pDevice, deviceType); /* TODO: Should probably rename ma_device__post_init_setup() to something better. */
  34258. }
  34259. static ma_thread_result MA_THREADCALL ma_worker_thread(void* pData)
  34260. {
  34261. ma_device* pDevice = (ma_device*)pData;
  34262. MA_ASSERT(pDevice != NULL);
  34263. #ifdef MA_WIN32
  34264. ma_CoInitializeEx(pDevice->pContext, NULL, MA_COINIT_VALUE);
  34265. #endif
  34266. /*
  34267. When the device is being initialized it's initial state is set to ma_device_state_uninitialized. Before returning from
  34268. ma_device_init(), the state needs to be set to something valid. In miniaudio the device's default state immediately
  34269. after initialization is stopped, so therefore we need to mark the device as such. miniaudio will wait on the worker
  34270. thread to signal an event to know when the worker thread is ready for action.
  34271. */
  34272. ma_device__set_state(pDevice, ma_device_state_stopped);
  34273. ma_event_signal(&pDevice->stopEvent);
  34274. for (;;) { /* <-- This loop just keeps the thread alive. The main audio loop is inside. */
  34275. ma_result startResult;
  34276. ma_result stopResult; /* <-- This will store the result from onDeviceStop(). If it returns an error, we don't fire the stopped notification callback. */
  34277. /* We wait on an event to know when something has requested that the device be started and the main loop entered. */
  34278. ma_event_wait(&pDevice->wakeupEvent);
  34279. /* Default result code. */
  34280. pDevice->workResult = MA_SUCCESS;
  34281. /* If the reason for the wake up is that we are terminating, just break from the loop. */
  34282. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  34283. break;
  34284. }
  34285. /*
  34286. Getting to this point means the device is wanting to get started. The function that has requested that the device
  34287. be started will be waiting on an event (pDevice->startEvent) which means we need to make sure we signal the event
  34288. in both the success and error case. It's important that the state of the device is set _before_ signaling the event.
  34289. */
  34290. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_starting);
  34291. /* If the device has a start callback, start it now. */
  34292. if (pDevice->pContext->callbacks.onDeviceStart != NULL) {
  34293. startResult = pDevice->pContext->callbacks.onDeviceStart(pDevice);
  34294. } else {
  34295. startResult = MA_SUCCESS;
  34296. }
  34297. /*
  34298. If starting was not successful we'll need to loop back to the start and wait for something
  34299. to happen (pDevice->wakeupEvent).
  34300. */
  34301. if (startResult != MA_SUCCESS) {
  34302. pDevice->workResult = startResult;
  34303. ma_event_signal(&pDevice->startEvent); /* <-- Always signal the start event so ma_device_start() can return as it'll be waiting on it. */
  34304. continue;
  34305. }
  34306. /* Make sure the state is set appropriately. */
  34307. ma_device__set_state(pDevice, ma_device_state_started); /* <-- Set this before signaling the event so that the state is always guaranteed to be good after ma_device_start() has returned. */
  34308. ma_event_signal(&pDevice->startEvent);
  34309. ma_device__on_notification_started(pDevice);
  34310. if (pDevice->pContext->callbacks.onDeviceDataLoop != NULL) {
  34311. pDevice->pContext->callbacks.onDeviceDataLoop(pDevice);
  34312. } else {
  34313. /* The backend is not using a custom main loop implementation, so now fall back to the blocking read-write implementation. */
  34314. ma_device_audio_thread__default_read_write(pDevice);
  34315. }
  34316. /* Getting here means we have broken from the main loop which happens the application has requested that device be stopped. */
  34317. if (pDevice->pContext->callbacks.onDeviceStop != NULL) {
  34318. stopResult = pDevice->pContext->callbacks.onDeviceStop(pDevice);
  34319. } else {
  34320. stopResult = MA_SUCCESS; /* No stop callback with the backend. Just assume successful. */
  34321. }
  34322. /*
  34323. After the device has stopped, make sure an event is posted. Don't post a stopped event if
  34324. stopping failed. This can happen on some backends when the underlying stream has been
  34325. stopped due to the device being physically unplugged or disabled via an OS setting.
  34326. */
  34327. if (stopResult == MA_SUCCESS) {
  34328. ma_device__on_notification_stopped(pDevice);
  34329. }
  34330. /* A function somewhere is waiting for the device to have stopped for real so we need to signal an event to allow it to continue. */
  34331. ma_device__set_state(pDevice, ma_device_state_stopped);
  34332. ma_event_signal(&pDevice->stopEvent);
  34333. }
  34334. #ifdef MA_WIN32
  34335. ma_CoUninitialize(pDevice->pContext);
  34336. #endif
  34337. return (ma_thread_result)0;
  34338. }
  34339. /* Helper for determining whether or not the given device is initialized. */
  34340. static ma_bool32 ma_device__is_initialized(ma_device* pDevice)
  34341. {
  34342. if (pDevice == NULL) {
  34343. return MA_FALSE;
  34344. }
  34345. return ma_device_get_state(pDevice) != ma_device_state_uninitialized;
  34346. }
  34347. #ifdef MA_WIN32
  34348. static ma_result ma_context_uninit_backend_apis__win32(ma_context* pContext)
  34349. {
  34350. /* For some reason UWP complains when CoUninitialize() is called. I'm just not going to call it on UWP. */
  34351. #ifdef MA_WIN32_DESKTOP
  34352. ma_CoUninitialize(pContext);
  34353. ma_dlclose(pContext, pContext->win32.hUser32DLL);
  34354. ma_dlclose(pContext, pContext->win32.hOle32DLL);
  34355. ma_dlclose(pContext, pContext->win32.hAdvapi32DLL);
  34356. #else
  34357. (void)pContext;
  34358. #endif
  34359. return MA_SUCCESS;
  34360. }
  34361. static ma_result ma_context_init_backend_apis__win32(ma_context* pContext)
  34362. {
  34363. #ifdef MA_WIN32_DESKTOP
  34364. /* Ole32.dll */
  34365. pContext->win32.hOle32DLL = ma_dlopen(pContext, "ole32.dll");
  34366. if (pContext->win32.hOle32DLL == NULL) {
  34367. return MA_FAILED_TO_INIT_BACKEND;
  34368. }
  34369. pContext->win32.CoInitialize = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "CoInitialize");
  34370. pContext->win32.CoInitializeEx = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "CoInitializeEx");
  34371. pContext->win32.CoUninitialize = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "CoUninitialize");
  34372. pContext->win32.CoCreateInstance = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "CoCreateInstance");
  34373. pContext->win32.CoTaskMemFree = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "CoTaskMemFree");
  34374. pContext->win32.PropVariantClear = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "PropVariantClear");
  34375. pContext->win32.StringFromGUID2 = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "StringFromGUID2");
  34376. /* User32.dll */
  34377. pContext->win32.hUser32DLL = ma_dlopen(pContext, "user32.dll");
  34378. if (pContext->win32.hUser32DLL == NULL) {
  34379. return MA_FAILED_TO_INIT_BACKEND;
  34380. }
  34381. pContext->win32.GetForegroundWindow = (ma_proc)ma_dlsym(pContext, pContext->win32.hUser32DLL, "GetForegroundWindow");
  34382. pContext->win32.GetDesktopWindow = (ma_proc)ma_dlsym(pContext, pContext->win32.hUser32DLL, "GetDesktopWindow");
  34383. /* Advapi32.dll */
  34384. pContext->win32.hAdvapi32DLL = ma_dlopen(pContext, "advapi32.dll");
  34385. if (pContext->win32.hAdvapi32DLL == NULL) {
  34386. return MA_FAILED_TO_INIT_BACKEND;
  34387. }
  34388. pContext->win32.RegOpenKeyExA = (ma_proc)ma_dlsym(pContext, pContext->win32.hAdvapi32DLL, "RegOpenKeyExA");
  34389. pContext->win32.RegCloseKey = (ma_proc)ma_dlsym(pContext, pContext->win32.hAdvapi32DLL, "RegCloseKey");
  34390. pContext->win32.RegQueryValueExA = (ma_proc)ma_dlsym(pContext, pContext->win32.hAdvapi32DLL, "RegQueryValueExA");
  34391. #else
  34392. (void)pContext; /* Unused. */
  34393. #endif
  34394. ma_CoInitializeEx(pContext, NULL, MA_COINIT_VALUE);
  34395. return MA_SUCCESS;
  34396. }
  34397. #else
  34398. static ma_result ma_context_uninit_backend_apis__nix(ma_context* pContext)
  34399. {
  34400. (void)pContext;
  34401. return MA_SUCCESS;
  34402. }
  34403. static ma_result ma_context_init_backend_apis__nix(ma_context* pContext)
  34404. {
  34405. (void)pContext;
  34406. return MA_SUCCESS;
  34407. }
  34408. #endif
  34409. static ma_result ma_context_init_backend_apis(ma_context* pContext)
  34410. {
  34411. ma_result result;
  34412. #ifdef MA_WIN32
  34413. result = ma_context_init_backend_apis__win32(pContext);
  34414. #else
  34415. result = ma_context_init_backend_apis__nix(pContext);
  34416. #endif
  34417. return result;
  34418. }
  34419. static ma_result ma_context_uninit_backend_apis(ma_context* pContext)
  34420. {
  34421. ma_result result;
  34422. #ifdef MA_WIN32
  34423. result = ma_context_uninit_backend_apis__win32(pContext);
  34424. #else
  34425. result = ma_context_uninit_backend_apis__nix(pContext);
  34426. #endif
  34427. return result;
  34428. }
  34429. /* The default capacity doesn't need to be too big. */
  34430. #ifndef MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY
  34431. #define MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY 32
  34432. #endif
  34433. MA_API ma_device_job_thread_config ma_device_job_thread_config_init(void)
  34434. {
  34435. ma_device_job_thread_config config;
  34436. MA_ZERO_OBJECT(&config);
  34437. config.noThread = MA_FALSE;
  34438. config.jobQueueCapacity = MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY;
  34439. config.jobQueueFlags = 0;
  34440. return config;
  34441. }
  34442. static ma_thread_result MA_THREADCALL ma_device_job_thread_entry(void* pUserData)
  34443. {
  34444. ma_device_job_thread* pJobThread = (ma_device_job_thread*)pUserData;
  34445. MA_ASSERT(pJobThread != NULL);
  34446. for (;;) {
  34447. ma_result result;
  34448. ma_job job;
  34449. result = ma_device_job_thread_next(pJobThread, &job);
  34450. if (result != MA_SUCCESS) {
  34451. break;
  34452. }
  34453. if (job.toc.breakup.code == MA_JOB_TYPE_QUIT) {
  34454. break;
  34455. }
  34456. ma_job_process(&job);
  34457. }
  34458. return (ma_thread_result)0;
  34459. }
  34460. MA_API ma_result ma_device_job_thread_init(const ma_device_job_thread_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_device_job_thread* pJobThread)
  34461. {
  34462. ma_result result;
  34463. ma_job_queue_config jobQueueConfig;
  34464. if (pJobThread == NULL) {
  34465. return MA_INVALID_ARGS;
  34466. }
  34467. MA_ZERO_OBJECT(pJobThread);
  34468. if (pConfig == NULL) {
  34469. return MA_INVALID_ARGS;
  34470. }
  34471. /* Initialize the job queue before the thread to ensure it's in a valid state. */
  34472. jobQueueConfig = ma_job_queue_config_init(pConfig->jobQueueFlags, pConfig->jobQueueCapacity);
  34473. result = ma_job_queue_init(&jobQueueConfig, pAllocationCallbacks, &pJobThread->jobQueue);
  34474. if (result != MA_SUCCESS) {
  34475. return result; /* Failed to initialize job queue. */
  34476. }
  34477. /* The thread needs to be initialized after the job queue to ensure the thread doesn't try to access it prematurely. */
  34478. if (pConfig->noThread == MA_FALSE) {
  34479. result = ma_thread_create(&pJobThread->thread, ma_thread_priority_normal, 0, ma_device_job_thread_entry, pJobThread, pAllocationCallbacks);
  34480. if (result != MA_SUCCESS) {
  34481. ma_job_queue_uninit(&pJobThread->jobQueue, pAllocationCallbacks);
  34482. return result; /* Failed to create the job thread. */
  34483. }
  34484. pJobThread->_hasThread = MA_TRUE;
  34485. } else {
  34486. pJobThread->_hasThread = MA_FALSE;
  34487. }
  34488. return MA_SUCCESS;
  34489. }
  34490. MA_API void ma_device_job_thread_uninit(ma_device_job_thread* pJobThread, const ma_allocation_callbacks* pAllocationCallbacks)
  34491. {
  34492. if (pJobThread == NULL) {
  34493. return;
  34494. }
  34495. /* The first thing to do is post a quit message to the job queue. If we're using a thread we'll need to wait for it. */
  34496. {
  34497. ma_job job = ma_job_init(MA_JOB_TYPE_QUIT);
  34498. ma_device_job_thread_post(pJobThread, &job);
  34499. }
  34500. /* Wait for the thread to terminate naturally. */
  34501. if (pJobThread->_hasThread) {
  34502. ma_thread_wait(&pJobThread->thread);
  34503. }
  34504. /* At this point the thread should be terminated so we can safely uninitialize the job queue. */
  34505. ma_job_queue_uninit(&pJobThread->jobQueue, pAllocationCallbacks);
  34506. }
  34507. MA_API ma_result ma_device_job_thread_post(ma_device_job_thread* pJobThread, const ma_job* pJob)
  34508. {
  34509. if (pJobThread == NULL || pJob == NULL) {
  34510. return MA_INVALID_ARGS;
  34511. }
  34512. return ma_job_queue_post(&pJobThread->jobQueue, pJob);
  34513. }
  34514. MA_API ma_result ma_device_job_thread_next(ma_device_job_thread* pJobThread, ma_job* pJob)
  34515. {
  34516. if (pJob == NULL) {
  34517. return MA_INVALID_ARGS;
  34518. }
  34519. MA_ZERO_OBJECT(pJob);
  34520. if (pJobThread == NULL) {
  34521. return MA_INVALID_ARGS;
  34522. }
  34523. return ma_job_queue_next(&pJobThread->jobQueue, pJob);
  34524. }
  34525. MA_API ma_context_config ma_context_config_init(void)
  34526. {
  34527. ma_context_config config;
  34528. MA_ZERO_OBJECT(&config);
  34529. return config;
  34530. }
  34531. MA_API ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext)
  34532. {
  34533. ma_result result;
  34534. ma_context_config defaultConfig;
  34535. ma_backend defaultBackends[ma_backend_null+1];
  34536. ma_uint32 iBackend;
  34537. ma_backend* pBackendsToIterate;
  34538. ma_uint32 backendsToIterateCount;
  34539. if (pContext == NULL) {
  34540. return MA_INVALID_ARGS;
  34541. }
  34542. MA_ZERO_OBJECT(pContext);
  34543. /* Always make sure the config is set first to ensure properties are available as soon as possible. */
  34544. if (pConfig == NULL) {
  34545. defaultConfig = ma_context_config_init();
  34546. pConfig = &defaultConfig;
  34547. }
  34548. /* Allocation callbacks need to come first because they'll be passed around to other areas. */
  34549. result = ma_allocation_callbacks_init_copy(&pContext->allocationCallbacks, &pConfig->allocationCallbacks);
  34550. if (result != MA_SUCCESS) {
  34551. return result;
  34552. }
  34553. /* Get a lot set up first so we can start logging ASAP. */
  34554. if (pConfig->pLog != NULL) {
  34555. pContext->pLog = pConfig->pLog;
  34556. } else {
  34557. result = ma_log_init(&pContext->allocationCallbacks, &pContext->log);
  34558. if (result == MA_SUCCESS) {
  34559. pContext->pLog = &pContext->log;
  34560. } else {
  34561. pContext->pLog = NULL; /* Logging is not available. */
  34562. }
  34563. }
  34564. pContext->threadPriority = pConfig->threadPriority;
  34565. pContext->threadStackSize = pConfig->threadStackSize;
  34566. pContext->pUserData = pConfig->pUserData;
  34567. /* Backend APIs need to be initialized first. This is where external libraries will be loaded and linked. */
  34568. result = ma_context_init_backend_apis(pContext);
  34569. if (result != MA_SUCCESS) {
  34570. return result;
  34571. }
  34572. for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) {
  34573. defaultBackends[iBackend] = (ma_backend)iBackend;
  34574. }
  34575. pBackendsToIterate = (ma_backend*)backends;
  34576. backendsToIterateCount = backendCount;
  34577. if (pBackendsToIterate == NULL) {
  34578. pBackendsToIterate = (ma_backend*)defaultBackends;
  34579. backendsToIterateCount = ma_countof(defaultBackends);
  34580. }
  34581. MA_ASSERT(pBackendsToIterate != NULL);
  34582. for (iBackend = 0; iBackend < backendsToIterateCount; iBackend += 1) {
  34583. ma_backend backend = pBackendsToIterate[iBackend];
  34584. /* Make sure all callbacks are reset so we don't accidentally drag in any from previously failed initialization attempts. */
  34585. MA_ZERO_OBJECT(&pContext->callbacks);
  34586. /* These backends are using the new callback system. */
  34587. switch (backend) {
  34588. #ifdef MA_HAS_WASAPI
  34589. case ma_backend_wasapi:
  34590. {
  34591. pContext->callbacks.onContextInit = ma_context_init__wasapi;
  34592. } break;
  34593. #endif
  34594. #ifdef MA_HAS_DSOUND
  34595. case ma_backend_dsound:
  34596. {
  34597. pContext->callbacks.onContextInit = ma_context_init__dsound;
  34598. } break;
  34599. #endif
  34600. #ifdef MA_HAS_WINMM
  34601. case ma_backend_winmm:
  34602. {
  34603. pContext->callbacks.onContextInit = ma_context_init__winmm;
  34604. } break;
  34605. #endif
  34606. #ifdef MA_HAS_COREAUDIO
  34607. case ma_backend_coreaudio:
  34608. {
  34609. pContext->callbacks.onContextInit = ma_context_init__coreaudio;
  34610. } break;
  34611. #endif
  34612. #ifdef MA_HAS_SNDIO
  34613. case ma_backend_sndio:
  34614. {
  34615. pContext->callbacks.onContextInit = ma_context_init__sndio;
  34616. } break;
  34617. #endif
  34618. #ifdef MA_HAS_AUDIO4
  34619. case ma_backend_audio4:
  34620. {
  34621. pContext->callbacks.onContextInit = ma_context_init__audio4;
  34622. } break;
  34623. #endif
  34624. #ifdef MA_HAS_OSS
  34625. case ma_backend_oss:
  34626. {
  34627. pContext->callbacks.onContextInit = ma_context_init__oss;
  34628. } break;
  34629. #endif
  34630. #ifdef MA_HAS_PULSEAUDIO
  34631. case ma_backend_pulseaudio:
  34632. {
  34633. pContext->callbacks.onContextInit = ma_context_init__pulse;
  34634. } break;
  34635. #endif
  34636. #ifdef MA_HAS_ALSA
  34637. case ma_backend_alsa:
  34638. {
  34639. pContext->callbacks.onContextInit = ma_context_init__alsa;
  34640. } break;
  34641. #endif
  34642. #ifdef MA_HAS_JACK
  34643. case ma_backend_jack:
  34644. {
  34645. pContext->callbacks.onContextInit = ma_context_init__jack;
  34646. } break;
  34647. #endif
  34648. #ifdef MA_HAS_AAUDIO
  34649. case ma_backend_aaudio:
  34650. {
  34651. if (ma_is_backend_enabled(backend)) {
  34652. pContext->callbacks.onContextInit = ma_context_init__aaudio;
  34653. }
  34654. } break;
  34655. #endif
  34656. #ifdef MA_HAS_OPENSL
  34657. case ma_backend_opensl:
  34658. {
  34659. if (ma_is_backend_enabled(backend)) {
  34660. pContext->callbacks.onContextInit = ma_context_init__opensl;
  34661. }
  34662. } break;
  34663. #endif
  34664. #ifdef MA_HAS_WEBAUDIO
  34665. case ma_backend_webaudio:
  34666. {
  34667. pContext->callbacks.onContextInit = ma_context_init__webaudio;
  34668. } break;
  34669. #endif
  34670. #ifdef MA_HAS_CUSTOM
  34671. case ma_backend_custom:
  34672. {
  34673. /* Slightly different logic for custom backends. Custom backends can optionally set all of their callbacks in the config. */
  34674. pContext->callbacks = pConfig->custom;
  34675. } break;
  34676. #endif
  34677. #ifdef MA_HAS_NULL
  34678. case ma_backend_null:
  34679. {
  34680. pContext->callbacks.onContextInit = ma_context_init__null;
  34681. } break;
  34682. #endif
  34683. default: break;
  34684. }
  34685. if (pContext->callbacks.onContextInit != NULL) {
  34686. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Attempting to initialize %s backend...\n", ma_get_backend_name(backend));
  34687. result = pContext->callbacks.onContextInit(pContext, pConfig, &pContext->callbacks);
  34688. } else {
  34689. /* Getting here means the onContextInit callback is not set which means the backend is not enabled. Special case for the custom backend. */
  34690. if (backend != ma_backend_custom) {
  34691. result = MA_BACKEND_NOT_ENABLED;
  34692. } else {
  34693. #if !defined(MA_HAS_CUSTOM)
  34694. result = MA_BACKEND_NOT_ENABLED;
  34695. #else
  34696. result = MA_NO_BACKEND;
  34697. #endif
  34698. }
  34699. }
  34700. /* If this iteration was successful, return. */
  34701. if (result == MA_SUCCESS) {
  34702. result = ma_mutex_init(&pContext->deviceEnumLock);
  34703. if (result != MA_SUCCESS) {
  34704. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Failed to initialize mutex for device enumeration. ma_context_get_devices() is not thread safe.\n");
  34705. }
  34706. result = ma_mutex_init(&pContext->deviceInfoLock);
  34707. if (result != MA_SUCCESS) {
  34708. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Failed to initialize mutex for device info retrieval. ma_context_get_device_info() is not thread safe.\n");
  34709. }
  34710. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "System Architecture:\n");
  34711. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " Endian: %s\n", ma_is_little_endian() ? "LE" : "BE");
  34712. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " SSE2: %s\n", ma_has_sse2() ? "YES" : "NO");
  34713. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " AVX2: %s\n", ma_has_avx2() ? "YES" : "NO");
  34714. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " NEON: %s\n", ma_has_neon() ? "YES" : "NO");
  34715. pContext->backend = backend;
  34716. return result;
  34717. } else {
  34718. if (result == MA_BACKEND_NOT_ENABLED) {
  34719. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "%s backend is disabled.\n", ma_get_backend_name(backend));
  34720. } else {
  34721. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Failed to initialize %s backend.\n", ma_get_backend_name(backend));
  34722. }
  34723. }
  34724. }
  34725. /* If we get here it means an error occurred. */
  34726. MA_ZERO_OBJECT(pContext); /* Safety. */
  34727. return MA_NO_BACKEND;
  34728. }
  34729. MA_API ma_result ma_context_uninit(ma_context* pContext)
  34730. {
  34731. if (pContext == NULL) {
  34732. return MA_INVALID_ARGS;
  34733. }
  34734. if (pContext->callbacks.onContextUninit != NULL) {
  34735. pContext->callbacks.onContextUninit(pContext);
  34736. }
  34737. ma_mutex_uninit(&pContext->deviceEnumLock);
  34738. ma_mutex_uninit(&pContext->deviceInfoLock);
  34739. ma_free(pContext->pDeviceInfos, &pContext->allocationCallbacks);
  34740. ma_context_uninit_backend_apis(pContext);
  34741. if (pContext->pLog == &pContext->log) {
  34742. ma_log_uninit(&pContext->log);
  34743. }
  34744. return MA_SUCCESS;
  34745. }
  34746. MA_API size_t ma_context_sizeof(void)
  34747. {
  34748. return sizeof(ma_context);
  34749. }
  34750. MA_API ma_log* ma_context_get_log(ma_context* pContext)
  34751. {
  34752. if (pContext == NULL) {
  34753. return NULL;
  34754. }
  34755. return pContext->pLog;
  34756. }
  34757. MA_API ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  34758. {
  34759. ma_result result;
  34760. if (pContext == NULL || callback == NULL) {
  34761. return MA_INVALID_ARGS;
  34762. }
  34763. if (pContext->callbacks.onContextEnumerateDevices == NULL) {
  34764. return MA_INVALID_OPERATION;
  34765. }
  34766. ma_mutex_lock(&pContext->deviceEnumLock);
  34767. {
  34768. result = pContext->callbacks.onContextEnumerateDevices(pContext, callback, pUserData);
  34769. }
  34770. ma_mutex_unlock(&pContext->deviceEnumLock);
  34771. return result;
  34772. }
  34773. static ma_bool32 ma_context_get_devices__enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData)
  34774. {
  34775. /*
  34776. We need to insert the device info into our main internal buffer. Where it goes depends on the device type. If it's a capture device
  34777. it's just appended to the end. If it's a playback device it's inserted just before the first capture device.
  34778. */
  34779. /*
  34780. First make sure we have room. Since the number of devices we add to the list is usually relatively small I've decided to use a
  34781. simple fixed size increment for buffer expansion.
  34782. */
  34783. const ma_uint32 bufferExpansionCount = 2;
  34784. const ma_uint32 totalDeviceInfoCount = pContext->playbackDeviceInfoCount + pContext->captureDeviceInfoCount;
  34785. if (totalDeviceInfoCount >= pContext->deviceInfoCapacity) {
  34786. ma_uint32 newCapacity = pContext->deviceInfoCapacity + bufferExpansionCount;
  34787. ma_device_info* pNewInfos = (ma_device_info*)ma_realloc(pContext->pDeviceInfos, sizeof(*pContext->pDeviceInfos)*newCapacity, &pContext->allocationCallbacks);
  34788. if (pNewInfos == NULL) {
  34789. return MA_FALSE; /* Out of memory. */
  34790. }
  34791. pContext->pDeviceInfos = pNewInfos;
  34792. pContext->deviceInfoCapacity = newCapacity;
  34793. }
  34794. if (deviceType == ma_device_type_playback) {
  34795. /* Playback. Insert just before the first capture device. */
  34796. /* The first thing to do is move all of the capture devices down a slot. */
  34797. ma_uint32 iFirstCaptureDevice = pContext->playbackDeviceInfoCount;
  34798. size_t iCaptureDevice;
  34799. for (iCaptureDevice = totalDeviceInfoCount; iCaptureDevice > iFirstCaptureDevice; --iCaptureDevice) {
  34800. pContext->pDeviceInfos[iCaptureDevice] = pContext->pDeviceInfos[iCaptureDevice-1];
  34801. }
  34802. /* Now just insert where the first capture device was before moving it down a slot. */
  34803. pContext->pDeviceInfos[iFirstCaptureDevice] = *pInfo;
  34804. pContext->playbackDeviceInfoCount += 1;
  34805. } else {
  34806. /* Capture. Insert at the end. */
  34807. pContext->pDeviceInfos[totalDeviceInfoCount] = *pInfo;
  34808. pContext->captureDeviceInfoCount += 1;
  34809. }
  34810. (void)pUserData;
  34811. return MA_TRUE;
  34812. }
  34813. MA_API ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlaybackDeviceInfos, ma_uint32* pPlaybackDeviceCount, ma_device_info** ppCaptureDeviceInfos, ma_uint32* pCaptureDeviceCount)
  34814. {
  34815. ma_result result;
  34816. /* Safety. */
  34817. if (ppPlaybackDeviceInfos != NULL) *ppPlaybackDeviceInfos = NULL;
  34818. if (pPlaybackDeviceCount != NULL) *pPlaybackDeviceCount = 0;
  34819. if (ppCaptureDeviceInfos != NULL) *ppCaptureDeviceInfos = NULL;
  34820. if (pCaptureDeviceCount != NULL) *pCaptureDeviceCount = 0;
  34821. if (pContext == NULL) {
  34822. return MA_INVALID_ARGS;
  34823. }
  34824. if (pContext->callbacks.onContextEnumerateDevices == NULL) {
  34825. return MA_INVALID_OPERATION;
  34826. }
  34827. /* Note that we don't use ma_context_enumerate_devices() here because we want to do locking at a higher level. */
  34828. ma_mutex_lock(&pContext->deviceEnumLock);
  34829. {
  34830. /* Reset everything first. */
  34831. pContext->playbackDeviceInfoCount = 0;
  34832. pContext->captureDeviceInfoCount = 0;
  34833. /* Now enumerate over available devices. */
  34834. result = pContext->callbacks.onContextEnumerateDevices(pContext, ma_context_get_devices__enum_callback, NULL);
  34835. if (result == MA_SUCCESS) {
  34836. /* Playback devices. */
  34837. if (ppPlaybackDeviceInfos != NULL) {
  34838. *ppPlaybackDeviceInfos = pContext->pDeviceInfos;
  34839. }
  34840. if (pPlaybackDeviceCount != NULL) {
  34841. *pPlaybackDeviceCount = pContext->playbackDeviceInfoCount;
  34842. }
  34843. /* Capture devices. */
  34844. if (ppCaptureDeviceInfos != NULL) {
  34845. *ppCaptureDeviceInfos = pContext->pDeviceInfos;
  34846. /* Capture devices come after playback devices. */
  34847. if (pContext->playbackDeviceInfoCount > 0) {
  34848. /* Conditional, because NULL+0 is undefined behavior. */
  34849. *ppCaptureDeviceInfos += pContext->playbackDeviceInfoCount;
  34850. }
  34851. }
  34852. if (pCaptureDeviceCount != NULL) {
  34853. *pCaptureDeviceCount = pContext->captureDeviceInfoCount;
  34854. }
  34855. }
  34856. }
  34857. ma_mutex_unlock(&pContext->deviceEnumLock);
  34858. return result;
  34859. }
  34860. MA_API ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
  34861. {
  34862. ma_result result;
  34863. ma_device_info deviceInfo;
  34864. /* NOTE: Do not clear pDeviceInfo on entry. The reason is the pDeviceID may actually point to pDeviceInfo->id which will break things. */
  34865. if (pContext == NULL || pDeviceInfo == NULL) {
  34866. return MA_INVALID_ARGS;
  34867. }
  34868. MA_ZERO_OBJECT(&deviceInfo);
  34869. /* Help the backend out by copying over the device ID if we have one. */
  34870. if (pDeviceID != NULL) {
  34871. MA_COPY_MEMORY(&deviceInfo.id, pDeviceID, sizeof(*pDeviceID));
  34872. }
  34873. if (pContext->callbacks.onContextGetDeviceInfo == NULL) {
  34874. return MA_INVALID_OPERATION;
  34875. }
  34876. ma_mutex_lock(&pContext->deviceInfoLock);
  34877. {
  34878. result = pContext->callbacks.onContextGetDeviceInfo(pContext, deviceType, pDeviceID, &deviceInfo);
  34879. }
  34880. ma_mutex_unlock(&pContext->deviceInfoLock);
  34881. *pDeviceInfo = deviceInfo;
  34882. return result;
  34883. }
  34884. MA_API ma_bool32 ma_context_is_loopback_supported(ma_context* pContext)
  34885. {
  34886. if (pContext == NULL) {
  34887. return MA_FALSE;
  34888. }
  34889. return ma_is_loopback_supported(pContext->backend);
  34890. }
  34891. MA_API ma_device_config ma_device_config_init(ma_device_type deviceType)
  34892. {
  34893. ma_device_config config;
  34894. MA_ZERO_OBJECT(&config);
  34895. config.deviceType = deviceType;
  34896. config.resampling = ma_resampler_config_init(ma_format_unknown, 0, 0, 0, ma_resample_algorithm_linear); /* Format/channels/rate don't matter here. */
  34897. return config;
  34898. }
  34899. MA_API ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
  34900. {
  34901. ma_result result;
  34902. ma_device_descriptor descriptorPlayback;
  34903. ma_device_descriptor descriptorCapture;
  34904. /* The context can be null, in which case we self-manage it. */
  34905. if (pContext == NULL) {
  34906. return ma_device_init_ex(NULL, 0, NULL, pConfig, pDevice);
  34907. }
  34908. if (pDevice == NULL) {
  34909. return MA_INVALID_ARGS;
  34910. }
  34911. MA_ZERO_OBJECT(pDevice);
  34912. if (pConfig == NULL) {
  34913. return MA_INVALID_ARGS;
  34914. }
  34915. /* Check that we have our callbacks defined. */
  34916. if (pContext->callbacks.onDeviceInit == NULL) {
  34917. return MA_INVALID_OPERATION;
  34918. }
  34919. /* Basic config validation. */
  34920. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  34921. if (pConfig->capture.channels > MA_MAX_CHANNELS) {
  34922. return MA_INVALID_ARGS;
  34923. }
  34924. if (!ma__is_channel_map_valid(pConfig->capture.pChannelMap, pConfig->capture.channels)) {
  34925. return MA_INVALID_ARGS;
  34926. }
  34927. }
  34928. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  34929. if (pConfig->playback.channels > MA_MAX_CHANNELS) {
  34930. return MA_INVALID_ARGS;
  34931. }
  34932. if (!ma__is_channel_map_valid(pConfig->playback.pChannelMap, pConfig->playback.channels)) {
  34933. return MA_INVALID_ARGS;
  34934. }
  34935. }
  34936. pDevice->pContext = pContext;
  34937. /* Set the user data and log callback ASAP to ensure it is available for the entire initialization process. */
  34938. pDevice->pUserData = pConfig->pUserData;
  34939. pDevice->onData = pConfig->dataCallback;
  34940. pDevice->onNotification = pConfig->notificationCallback;
  34941. pDevice->onStop = pConfig->stopCallback;
  34942. if (pConfig->playback.pDeviceID != NULL) {
  34943. MA_COPY_MEMORY(&pDevice->playback.id, pConfig->playback.pDeviceID, sizeof(pDevice->playback.id));
  34944. pDevice->playback.pID = &pDevice->playback.id;
  34945. } else {
  34946. pDevice->playback.pID = NULL;
  34947. }
  34948. if (pConfig->capture.pDeviceID != NULL) {
  34949. MA_COPY_MEMORY(&pDevice->capture.id, pConfig->capture.pDeviceID, sizeof(pDevice->capture.id));
  34950. pDevice->capture.pID = &pDevice->capture.id;
  34951. } else {
  34952. pDevice->capture.pID = NULL;
  34953. }
  34954. pDevice->noPreSilencedOutputBuffer = pConfig->noPreSilencedOutputBuffer;
  34955. pDevice->noClip = pConfig->noClip;
  34956. pDevice->noDisableDenormals = pConfig->noDisableDenormals;
  34957. pDevice->noFixedSizedCallback = pConfig->noFixedSizedCallback;
  34958. ma_atomic_float_set(&pDevice->masterVolumeFactor, 1);
  34959. pDevice->type = pConfig->deviceType;
  34960. pDevice->sampleRate = pConfig->sampleRate;
  34961. pDevice->resampling.algorithm = pConfig->resampling.algorithm;
  34962. pDevice->resampling.linear.lpfOrder = pConfig->resampling.linear.lpfOrder;
  34963. pDevice->resampling.pBackendVTable = pConfig->resampling.pBackendVTable;
  34964. pDevice->resampling.pBackendUserData = pConfig->resampling.pBackendUserData;
  34965. pDevice->capture.shareMode = pConfig->capture.shareMode;
  34966. pDevice->capture.format = pConfig->capture.format;
  34967. pDevice->capture.channels = pConfig->capture.channels;
  34968. ma_channel_map_copy_or_default(pDevice->capture.channelMap, ma_countof(pDevice->capture.channelMap), pConfig->capture.pChannelMap, pConfig->capture.channels);
  34969. pDevice->capture.channelMixMode = pConfig->capture.channelMixMode;
  34970. pDevice->capture.calculateLFEFromSpatialChannels = pConfig->capture.calculateLFEFromSpatialChannels;
  34971. pDevice->playback.shareMode = pConfig->playback.shareMode;
  34972. pDevice->playback.format = pConfig->playback.format;
  34973. pDevice->playback.channels = pConfig->playback.channels;
  34974. ma_channel_map_copy_or_default(pDevice->playback.channelMap, ma_countof(pDevice->playback.channelMap), pConfig->playback.pChannelMap, pConfig->playback.channels);
  34975. pDevice->playback.channelMixMode = pConfig->playback.channelMixMode;
  34976. pDevice->playback.calculateLFEFromSpatialChannels = pConfig->playback.calculateLFEFromSpatialChannels;
  34977. result = ma_mutex_init(&pDevice->startStopLock);
  34978. if (result != MA_SUCCESS) {
  34979. return result;
  34980. }
  34981. /*
  34982. When the device is started, the worker thread is the one that does the actual startup of the backend device. We
  34983. use a semaphore to wait for the background thread to finish the work. The same applies for stopping the device.
  34984. Each of these semaphores is released internally by the worker thread when the work is completed. The start
  34985. semaphore is also used to wake up the worker thread.
  34986. */
  34987. result = ma_event_init(&pDevice->wakeupEvent);
  34988. if (result != MA_SUCCESS) {
  34989. ma_mutex_uninit(&pDevice->startStopLock);
  34990. return result;
  34991. }
  34992. result = ma_event_init(&pDevice->startEvent);
  34993. if (result != MA_SUCCESS) {
  34994. ma_event_uninit(&pDevice->wakeupEvent);
  34995. ma_mutex_uninit(&pDevice->startStopLock);
  34996. return result;
  34997. }
  34998. result = ma_event_init(&pDevice->stopEvent);
  34999. if (result != MA_SUCCESS) {
  35000. ma_event_uninit(&pDevice->startEvent);
  35001. ma_event_uninit(&pDevice->wakeupEvent);
  35002. ma_mutex_uninit(&pDevice->startStopLock);
  35003. return result;
  35004. }
  35005. MA_ZERO_OBJECT(&descriptorPlayback);
  35006. descriptorPlayback.pDeviceID = pConfig->playback.pDeviceID;
  35007. descriptorPlayback.shareMode = pConfig->playback.shareMode;
  35008. descriptorPlayback.format = pConfig->playback.format;
  35009. descriptorPlayback.channels = pConfig->playback.channels;
  35010. descriptorPlayback.sampleRate = pConfig->sampleRate;
  35011. ma_channel_map_copy_or_default(descriptorPlayback.channelMap, ma_countof(descriptorPlayback.channelMap), pConfig->playback.pChannelMap, pConfig->playback.channels);
  35012. descriptorPlayback.periodSizeInFrames = pConfig->periodSizeInFrames;
  35013. descriptorPlayback.periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
  35014. descriptorPlayback.periodCount = pConfig->periods;
  35015. if (descriptorPlayback.periodCount == 0) {
  35016. descriptorPlayback.periodCount = MA_DEFAULT_PERIODS;
  35017. }
  35018. MA_ZERO_OBJECT(&descriptorCapture);
  35019. descriptorCapture.pDeviceID = pConfig->capture.pDeviceID;
  35020. descriptorCapture.shareMode = pConfig->capture.shareMode;
  35021. descriptorCapture.format = pConfig->capture.format;
  35022. descriptorCapture.channels = pConfig->capture.channels;
  35023. descriptorCapture.sampleRate = pConfig->sampleRate;
  35024. ma_channel_map_copy_or_default(descriptorCapture.channelMap, ma_countof(descriptorCapture.channelMap), pConfig->capture.pChannelMap, pConfig->capture.channels);
  35025. descriptorCapture.periodSizeInFrames = pConfig->periodSizeInFrames;
  35026. descriptorCapture.periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
  35027. descriptorCapture.periodCount = pConfig->periods;
  35028. if (descriptorCapture.periodCount == 0) {
  35029. descriptorCapture.periodCount = MA_DEFAULT_PERIODS;
  35030. }
  35031. result = pContext->callbacks.onDeviceInit(pDevice, pConfig, &descriptorPlayback, &descriptorCapture);
  35032. if (result != MA_SUCCESS) {
  35033. ma_event_uninit(&pDevice->startEvent);
  35034. ma_event_uninit(&pDevice->wakeupEvent);
  35035. ma_mutex_uninit(&pDevice->startStopLock);
  35036. return result;
  35037. }
  35038. #if 0
  35039. /*
  35040. On output the descriptors will contain the *actual* data format of the device. We need this to know how to convert the data between
  35041. the requested format and the internal format.
  35042. */
  35043. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  35044. if (!ma_device_descriptor_is_valid(&descriptorCapture)) {
  35045. ma_device_uninit(pDevice);
  35046. return MA_INVALID_ARGS;
  35047. }
  35048. pDevice->capture.internalFormat = descriptorCapture.format;
  35049. pDevice->capture.internalChannels = descriptorCapture.channels;
  35050. pDevice->capture.internalSampleRate = descriptorCapture.sampleRate;
  35051. ma_channel_map_copy(pDevice->capture.internalChannelMap, descriptorCapture.channelMap, descriptorCapture.channels);
  35052. pDevice->capture.internalPeriodSizeInFrames = descriptorCapture.periodSizeInFrames;
  35053. pDevice->capture.internalPeriods = descriptorCapture.periodCount;
  35054. if (pDevice->capture.internalPeriodSizeInFrames == 0) {
  35055. pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(descriptorCapture.periodSizeInMilliseconds, descriptorCapture.sampleRate);
  35056. }
  35057. }
  35058. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  35059. if (!ma_device_descriptor_is_valid(&descriptorPlayback)) {
  35060. ma_device_uninit(pDevice);
  35061. return MA_INVALID_ARGS;
  35062. }
  35063. pDevice->playback.internalFormat = descriptorPlayback.format;
  35064. pDevice->playback.internalChannels = descriptorPlayback.channels;
  35065. pDevice->playback.internalSampleRate = descriptorPlayback.sampleRate;
  35066. ma_channel_map_copy(pDevice->playback.internalChannelMap, descriptorPlayback.channelMap, descriptorPlayback.channels);
  35067. pDevice->playback.internalPeriodSizeInFrames = descriptorPlayback.periodSizeInFrames;
  35068. pDevice->playback.internalPeriods = descriptorPlayback.periodCount;
  35069. if (pDevice->playback.internalPeriodSizeInFrames == 0) {
  35070. pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(descriptorPlayback.periodSizeInMilliseconds, descriptorPlayback.sampleRate);
  35071. }
  35072. }
  35073. /*
  35074. The name of the device can be retrieved from device info. This may be temporary and replaced with a `ma_device_get_info(pDevice, deviceType)` instead.
  35075. For loopback devices, we need to retrieve the name of the playback device.
  35076. */
  35077. {
  35078. ma_device_info deviceInfo;
  35079. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  35080. result = ma_device_get_info(pDevice, (pConfig->deviceType == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, &deviceInfo);
  35081. if (result == MA_SUCCESS) {
  35082. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), deviceInfo.name, (size_t)-1);
  35083. } else {
  35084. /* We failed to retrieve the device info. Fall back to a default name. */
  35085. if (descriptorCapture.pDeviceID == NULL) {
  35086. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  35087. } else {
  35088. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "Capture Device", (size_t)-1);
  35089. }
  35090. }
  35091. }
  35092. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  35093. result = ma_device_get_info(pDevice, ma_device_type_playback, &deviceInfo);
  35094. if (result == MA_SUCCESS) {
  35095. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), deviceInfo.name, (size_t)-1);
  35096. } else {
  35097. /* We failed to retrieve the device info. Fall back to a default name. */
  35098. if (descriptorPlayback.pDeviceID == NULL) {
  35099. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  35100. } else {
  35101. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "Playback Device", (size_t)-1);
  35102. }
  35103. }
  35104. }
  35105. }
  35106. ma_device__post_init_setup(pDevice, pConfig->deviceType);
  35107. #endif
  35108. result = ma_device_post_init(pDevice, pConfig->deviceType, &descriptorPlayback, &descriptorCapture);
  35109. if (result != MA_SUCCESS) {
  35110. ma_device_uninit(pDevice);
  35111. return result;
  35112. }
  35113. /*
  35114. If we're using fixed sized callbacks we'll need to make use of an intermediary buffer. Needs to
  35115. be done after post_init_setup() because we'll need access to the sample rate.
  35116. */
  35117. if (pConfig->noFixedSizedCallback == MA_FALSE) {
  35118. /* We're using a fixed sized data callback so we'll need an intermediary buffer. */
  35119. ma_uint32 intermediaryBufferCap = pConfig->periodSizeInFrames;
  35120. if (intermediaryBufferCap == 0) {
  35121. intermediaryBufferCap = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, pDevice->sampleRate);
  35122. }
  35123. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  35124. ma_uint32 intermediaryBufferSizeInBytes;
  35125. pDevice->capture.intermediaryBufferLen = 0;
  35126. pDevice->capture.intermediaryBufferCap = intermediaryBufferCap;
  35127. if (pDevice->capture.intermediaryBufferCap == 0) {
  35128. pDevice->capture.intermediaryBufferCap = pDevice->capture.internalPeriodSizeInFrames;
  35129. }
  35130. intermediaryBufferSizeInBytes = pDevice->capture.intermediaryBufferCap * ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  35131. pDevice->capture.pIntermediaryBuffer = ma_malloc((size_t)intermediaryBufferSizeInBytes, &pContext->allocationCallbacks);
  35132. if (pDevice->capture.pIntermediaryBuffer == NULL) {
  35133. ma_device_uninit(pDevice);
  35134. return MA_OUT_OF_MEMORY;
  35135. }
  35136. /* Silence the buffer for safety. */
  35137. ma_silence_pcm_frames(pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap, pDevice->capture.format, pDevice->capture.channels);
  35138. pDevice->capture.intermediaryBufferLen = pDevice->capture.intermediaryBufferCap;
  35139. }
  35140. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  35141. ma_uint64 intermediaryBufferSizeInBytes;
  35142. pDevice->playback.intermediaryBufferLen = 0;
  35143. if (pConfig->deviceType == ma_device_type_duplex) {
  35144. pDevice->playback.intermediaryBufferCap = pDevice->capture.intermediaryBufferCap; /* In duplex mode, make sure the intermediary buffer is always the same size as the capture side. */
  35145. } else {
  35146. pDevice->playback.intermediaryBufferCap = intermediaryBufferCap;
  35147. if (pDevice->playback.intermediaryBufferCap == 0) {
  35148. pDevice->playback.intermediaryBufferCap = pDevice->playback.internalPeriodSizeInFrames;
  35149. }
  35150. }
  35151. intermediaryBufferSizeInBytes = pDevice->playback.intermediaryBufferCap * ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  35152. pDevice->playback.pIntermediaryBuffer = ma_malloc((size_t)intermediaryBufferSizeInBytes, &pContext->allocationCallbacks);
  35153. if (pDevice->playback.pIntermediaryBuffer == NULL) {
  35154. ma_device_uninit(pDevice);
  35155. return MA_OUT_OF_MEMORY;
  35156. }
  35157. /* Silence the buffer for safety. */
  35158. ma_silence_pcm_frames(pDevice->playback.pIntermediaryBuffer, pDevice->playback.intermediaryBufferCap, pDevice->playback.format, pDevice->playback.channels);
  35159. pDevice->playback.intermediaryBufferLen = 0;
  35160. }
  35161. } else {
  35162. /* Not using a fixed sized data callback so no need for an intermediary buffer. */
  35163. }
  35164. /* Some backends don't require the worker thread. */
  35165. if (!ma_context_is_backend_asynchronous(pContext)) {
  35166. /* The worker thread. */
  35167. result = ma_thread_create(&pDevice->thread, pContext->threadPriority, pContext->threadStackSize, ma_worker_thread, pDevice, &pContext->allocationCallbacks);
  35168. if (result != MA_SUCCESS) {
  35169. ma_device_uninit(pDevice);
  35170. return result;
  35171. }
  35172. /* Wait for the worker thread to put the device into it's stopped state for real. */
  35173. ma_event_wait(&pDevice->stopEvent);
  35174. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped);
  35175. } else {
  35176. /*
  35177. If the backend is asynchronous and the device is duplex, we'll need an intermediary ring buffer. Note that this needs to be done
  35178. after ma_device__post_init_setup().
  35179. */
  35180. if (ma_context_is_backend_asynchronous(pContext)) {
  35181. if (pConfig->deviceType == ma_device_type_duplex) {
  35182. result = ma_duplex_rb_init(pDevice->capture.format, pDevice->capture.channels, pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalPeriodSizeInFrames, &pDevice->pContext->allocationCallbacks, &pDevice->duplexRB);
  35183. if (result != MA_SUCCESS) {
  35184. ma_device_uninit(pDevice);
  35185. return result;
  35186. }
  35187. }
  35188. }
  35189. ma_device__set_state(pDevice, ma_device_state_stopped);
  35190. }
  35191. /* Log device information. */
  35192. {
  35193. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[%s]\n", ma_get_backend_name(pDevice->pContext->backend));
  35194. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  35195. char name[MA_MAX_DEVICE_NAME_LENGTH + 1];
  35196. ma_device_get_name(pDevice, (pDevice->type == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, name, sizeof(name), NULL);
  35197. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " %s (%s)\n", name, "Capture");
  35198. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Format: %s -> %s\n", ma_get_format_name(pDevice->capture.internalFormat), ma_get_format_name(pDevice->capture.format));
  35199. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channels: %d -> %d\n", pDevice->capture.internalChannels, pDevice->capture.channels);
  35200. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Sample Rate: %d -> %d\n", pDevice->capture.internalSampleRate, pDevice->sampleRate);
  35201. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Buffer Size: %d*%d (%d)\n", pDevice->capture.internalPeriodSizeInFrames, pDevice->capture.internalPeriods, (pDevice->capture.internalPeriodSizeInFrames * pDevice->capture.internalPeriods));
  35202. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Conversion:\n");
  35203. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Pre Format Conversion: %s\n", pDevice->capture.converter.hasPreFormatConversion ? "YES" : "NO");
  35204. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Post Format Conversion: %s\n", pDevice->capture.converter.hasPostFormatConversion ? "YES" : "NO");
  35205. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Routing: %s\n", pDevice->capture.converter.hasChannelConverter ? "YES" : "NO");
  35206. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Resampling: %s\n", pDevice->capture.converter.hasResampler ? "YES" : "NO");
  35207. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Passthrough: %s\n", pDevice->capture.converter.isPassthrough ? "YES" : "NO");
  35208. {
  35209. char channelMapStr[1024];
  35210. ma_channel_map_to_string(pDevice->capture.internalChannelMap, pDevice->capture.internalChannels, channelMapStr, sizeof(channelMapStr));
  35211. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map In: {%s}\n", channelMapStr);
  35212. ma_channel_map_to_string(pDevice->capture.channelMap, pDevice->capture.channels, channelMapStr, sizeof(channelMapStr));
  35213. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map Out: {%s}\n", channelMapStr);
  35214. }
  35215. }
  35216. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  35217. char name[MA_MAX_DEVICE_NAME_LENGTH + 1];
  35218. ma_device_get_name(pDevice, ma_device_type_playback, name, sizeof(name), NULL);
  35219. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " %s (%s)\n", name, "Playback");
  35220. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Format: %s -> %s\n", ma_get_format_name(pDevice->playback.format), ma_get_format_name(pDevice->playback.internalFormat));
  35221. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channels: %d -> %d\n", pDevice->playback.channels, pDevice->playback.internalChannels);
  35222. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Sample Rate: %d -> %d\n", pDevice->sampleRate, pDevice->playback.internalSampleRate);
  35223. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Buffer Size: %d*%d (%d)\n", pDevice->playback.internalPeriodSizeInFrames, pDevice->playback.internalPeriods, (pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods));
  35224. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Conversion:\n");
  35225. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Pre Format Conversion: %s\n", pDevice->playback.converter.hasPreFormatConversion ? "YES" : "NO");
  35226. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Post Format Conversion: %s\n", pDevice->playback.converter.hasPostFormatConversion ? "YES" : "NO");
  35227. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Routing: %s\n", pDevice->playback.converter.hasChannelConverter ? "YES" : "NO");
  35228. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Resampling: %s\n", pDevice->playback.converter.hasResampler ? "YES" : "NO");
  35229. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Passthrough: %s\n", pDevice->playback.converter.isPassthrough ? "YES" : "NO");
  35230. {
  35231. char channelMapStr[1024];
  35232. ma_channel_map_to_string(pDevice->playback.channelMap, pDevice->playback.channels, channelMapStr, sizeof(channelMapStr));
  35233. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map In: {%s}\n", channelMapStr);
  35234. ma_channel_map_to_string(pDevice->playback.internalChannelMap, pDevice->playback.internalChannels, channelMapStr, sizeof(channelMapStr));
  35235. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map Out: {%s}\n", channelMapStr);
  35236. }
  35237. }
  35238. }
  35239. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped);
  35240. return MA_SUCCESS;
  35241. }
  35242. MA_API ma_result ma_device_init_ex(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pContextConfig, const ma_device_config* pConfig, ma_device* pDevice)
  35243. {
  35244. ma_result result;
  35245. ma_context* pContext;
  35246. ma_backend defaultBackends[ma_backend_null+1];
  35247. ma_uint32 iBackend;
  35248. ma_backend* pBackendsToIterate;
  35249. ma_uint32 backendsToIterateCount;
  35250. ma_allocation_callbacks allocationCallbacks;
  35251. if (pConfig == NULL) {
  35252. return MA_INVALID_ARGS;
  35253. }
  35254. if (pContextConfig != NULL) {
  35255. result = ma_allocation_callbacks_init_copy(&allocationCallbacks, &pContextConfig->allocationCallbacks);
  35256. if (result != MA_SUCCESS) {
  35257. return result;
  35258. }
  35259. } else {
  35260. allocationCallbacks = ma_allocation_callbacks_init_default();
  35261. }
  35262. pContext = (ma_context*)ma_malloc(sizeof(*pContext), &allocationCallbacks);
  35263. if (pContext == NULL) {
  35264. return MA_OUT_OF_MEMORY;
  35265. }
  35266. for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) {
  35267. defaultBackends[iBackend] = (ma_backend)iBackend;
  35268. }
  35269. pBackendsToIterate = (ma_backend*)backends;
  35270. backendsToIterateCount = backendCount;
  35271. if (pBackendsToIterate == NULL) {
  35272. pBackendsToIterate = (ma_backend*)defaultBackends;
  35273. backendsToIterateCount = ma_countof(defaultBackends);
  35274. }
  35275. result = MA_NO_BACKEND;
  35276. for (iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) {
  35277. /*
  35278. This is a hack for iOS. If the context config is null, there's a good chance the
  35279. `ma_device_init(NULL, &deviceConfig, pDevice);` pattern is being used. In this
  35280. case, set the session category based on the device type.
  35281. */
  35282. #if defined(MA_APPLE_MOBILE)
  35283. ma_context_config contextConfig;
  35284. if (pContextConfig == NULL) {
  35285. contextConfig = ma_context_config_init();
  35286. switch (pConfig->deviceType) {
  35287. case ma_device_type_duplex: {
  35288. contextConfig.coreaudio.sessionCategory = ma_ios_session_category_play_and_record;
  35289. } break;
  35290. case ma_device_type_capture: {
  35291. contextConfig.coreaudio.sessionCategory = ma_ios_session_category_record;
  35292. } break;
  35293. case ma_device_type_playback:
  35294. default: {
  35295. contextConfig.coreaudio.sessionCategory = ma_ios_session_category_playback;
  35296. } break;
  35297. }
  35298. pContextConfig = &contextConfig;
  35299. }
  35300. #endif
  35301. result = ma_context_init(&pBackendsToIterate[iBackend], 1, pContextConfig, pContext);
  35302. if (result == MA_SUCCESS) {
  35303. result = ma_device_init(pContext, pConfig, pDevice);
  35304. if (result == MA_SUCCESS) {
  35305. break; /* Success. */
  35306. } else {
  35307. ma_context_uninit(pContext); /* Failure. */
  35308. }
  35309. }
  35310. }
  35311. if (result != MA_SUCCESS) {
  35312. ma_free(pContext, &allocationCallbacks);
  35313. return result;
  35314. }
  35315. pDevice->isOwnerOfContext = MA_TRUE;
  35316. return result;
  35317. }
  35318. MA_API void ma_device_uninit(ma_device* pDevice)
  35319. {
  35320. if (!ma_device__is_initialized(pDevice)) {
  35321. return;
  35322. }
  35323. /* Make sure the device is stopped first. The backends will probably handle this naturally, but I like to do it explicitly for my own sanity. */
  35324. if (ma_device_is_started(pDevice)) {
  35325. ma_device_stop(pDevice);
  35326. }
  35327. /* Putting the device into an uninitialized state will make the worker thread return. */
  35328. ma_device__set_state(pDevice, ma_device_state_uninitialized);
  35329. /* Wake up the worker thread and wait for it to properly terminate. */
  35330. if (!ma_context_is_backend_asynchronous(pDevice->pContext)) {
  35331. ma_event_signal(&pDevice->wakeupEvent);
  35332. ma_thread_wait(&pDevice->thread);
  35333. }
  35334. if (pDevice->pContext->callbacks.onDeviceUninit != NULL) {
  35335. pDevice->pContext->callbacks.onDeviceUninit(pDevice);
  35336. }
  35337. ma_event_uninit(&pDevice->stopEvent);
  35338. ma_event_uninit(&pDevice->startEvent);
  35339. ma_event_uninit(&pDevice->wakeupEvent);
  35340. ma_mutex_uninit(&pDevice->startStopLock);
  35341. if (ma_context_is_backend_asynchronous(pDevice->pContext)) {
  35342. if (pDevice->type == ma_device_type_duplex) {
  35343. ma_duplex_rb_uninit(&pDevice->duplexRB);
  35344. }
  35345. }
  35346. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  35347. ma_data_converter_uninit(&pDevice->capture.converter, &pDevice->pContext->allocationCallbacks);
  35348. }
  35349. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  35350. ma_data_converter_uninit(&pDevice->playback.converter, &pDevice->pContext->allocationCallbacks);
  35351. }
  35352. if (pDevice->playback.pInputCache != NULL) {
  35353. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  35354. }
  35355. if (pDevice->capture.pIntermediaryBuffer != NULL) {
  35356. ma_free(pDevice->capture.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks);
  35357. }
  35358. if (pDevice->playback.pIntermediaryBuffer != NULL) {
  35359. ma_free(pDevice->playback.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks);
  35360. }
  35361. if (pDevice->isOwnerOfContext) {
  35362. ma_allocation_callbacks allocationCallbacks = pDevice->pContext->allocationCallbacks;
  35363. ma_context_uninit(pDevice->pContext);
  35364. ma_free(pDevice->pContext, &allocationCallbacks);
  35365. }
  35366. MA_ZERO_OBJECT(pDevice);
  35367. }
  35368. MA_API ma_context* ma_device_get_context(ma_device* pDevice)
  35369. {
  35370. if (pDevice == NULL) {
  35371. return NULL;
  35372. }
  35373. return pDevice->pContext;
  35374. }
  35375. MA_API ma_log* ma_device_get_log(ma_device* pDevice)
  35376. {
  35377. return ma_context_get_log(ma_device_get_context(pDevice));
  35378. }
  35379. MA_API ma_result ma_device_get_info(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo)
  35380. {
  35381. if (pDeviceInfo == NULL) {
  35382. return MA_INVALID_ARGS;
  35383. }
  35384. MA_ZERO_OBJECT(pDeviceInfo);
  35385. if (pDevice == NULL) {
  35386. return MA_INVALID_ARGS;
  35387. }
  35388. /* If the onDeviceGetInfo() callback is set, use that. Otherwise we'll fall back to ma_context_get_device_info(). */
  35389. if (pDevice->pContext->callbacks.onDeviceGetInfo != NULL) {
  35390. return pDevice->pContext->callbacks.onDeviceGetInfo(pDevice, type, pDeviceInfo);
  35391. }
  35392. /* Getting here means onDeviceGetInfo is not implemented so we need to fall back to an alternative. */
  35393. if (type == ma_device_type_playback) {
  35394. return ma_context_get_device_info(pDevice->pContext, type, pDevice->playback.pID, pDeviceInfo);
  35395. } else {
  35396. return ma_context_get_device_info(pDevice->pContext, type, pDevice->capture.pID, pDeviceInfo);
  35397. }
  35398. }
  35399. MA_API ma_result ma_device_get_name(ma_device* pDevice, ma_device_type type, char* pName, size_t nameCap, size_t* pLengthNotIncludingNullTerminator)
  35400. {
  35401. ma_result result;
  35402. ma_device_info deviceInfo;
  35403. if (pLengthNotIncludingNullTerminator != NULL) {
  35404. *pLengthNotIncludingNullTerminator = 0;
  35405. }
  35406. if (pName != NULL && nameCap > 0) {
  35407. pName[0] = '\0';
  35408. }
  35409. result = ma_device_get_info(pDevice, type, &deviceInfo);
  35410. if (result != MA_SUCCESS) {
  35411. return result;
  35412. }
  35413. if (pName != NULL) {
  35414. ma_strncpy_s(pName, nameCap, deviceInfo.name, (size_t)-1);
  35415. /*
  35416. For safety, make sure the length is based on the truncated output string rather than the
  35417. source. Otherwise the caller might assume the output buffer contains more content than it
  35418. actually does.
  35419. */
  35420. if (pLengthNotIncludingNullTerminator != NULL) {
  35421. *pLengthNotIncludingNullTerminator = strlen(pName);
  35422. }
  35423. } else {
  35424. /* Name not specified. Just report the length of the source string. */
  35425. if (pLengthNotIncludingNullTerminator != NULL) {
  35426. *pLengthNotIncludingNullTerminator = strlen(deviceInfo.name);
  35427. }
  35428. }
  35429. return MA_SUCCESS;
  35430. }
  35431. MA_API ma_result ma_device_start(ma_device* pDevice)
  35432. {
  35433. ma_result result;
  35434. if (pDevice == NULL) {
  35435. return MA_INVALID_ARGS;
  35436. }
  35437. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  35438. return MA_INVALID_OPERATION; /* Not initialized. */
  35439. }
  35440. if (ma_device_get_state(pDevice) == ma_device_state_started) {
  35441. return MA_SUCCESS; /* Already started. */
  35442. }
  35443. ma_mutex_lock(&pDevice->startStopLock);
  35444. {
  35445. /* Starting and stopping are wrapped in a mutex which means we can assert that the device is in a stopped or paused state. */
  35446. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped);
  35447. ma_device__set_state(pDevice, ma_device_state_starting);
  35448. /* Asynchronous backends need to be handled differently. */
  35449. if (ma_context_is_backend_asynchronous(pDevice->pContext)) {
  35450. if (pDevice->pContext->callbacks.onDeviceStart != NULL) {
  35451. result = pDevice->pContext->callbacks.onDeviceStart(pDevice);
  35452. } else {
  35453. result = MA_INVALID_OPERATION;
  35454. }
  35455. if (result == MA_SUCCESS) {
  35456. ma_device__set_state(pDevice, ma_device_state_started);
  35457. ma_device__on_notification_started(pDevice);
  35458. }
  35459. } else {
  35460. /*
  35461. Synchronous backends are started by signaling an event that's being waited on in the worker thread. We first wake up the
  35462. thread and then wait for the start event.
  35463. */
  35464. ma_event_signal(&pDevice->wakeupEvent);
  35465. /*
  35466. Wait for the worker thread to finish starting the device. Note that the worker thread will be the one who puts the device
  35467. into the started state. Don't call ma_device__set_state() here.
  35468. */
  35469. ma_event_wait(&pDevice->startEvent);
  35470. result = pDevice->workResult;
  35471. }
  35472. /* We changed the state from stopped to started, so if we failed, make sure we put the state back to stopped. */
  35473. if (result != MA_SUCCESS) {
  35474. ma_device__set_state(pDevice, ma_device_state_stopped);
  35475. }
  35476. }
  35477. ma_mutex_unlock(&pDevice->startStopLock);
  35478. return result;
  35479. }
  35480. MA_API ma_result ma_device_stop(ma_device* pDevice)
  35481. {
  35482. ma_result result;
  35483. if (pDevice == NULL) {
  35484. return MA_INVALID_ARGS;
  35485. }
  35486. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  35487. return MA_INVALID_OPERATION; /* Not initialized. */
  35488. }
  35489. if (ma_device_get_state(pDevice) == ma_device_state_stopped) {
  35490. return MA_SUCCESS; /* Already stopped. */
  35491. }
  35492. ma_mutex_lock(&pDevice->startStopLock);
  35493. {
  35494. /* Starting and stopping are wrapped in a mutex which means we can assert that the device is in a started or paused state. */
  35495. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_started);
  35496. ma_device__set_state(pDevice, ma_device_state_stopping);
  35497. /* Asynchronous backends need to be handled differently. */
  35498. if (ma_context_is_backend_asynchronous(pDevice->pContext)) {
  35499. /* Asynchronous backends must have a stop operation. */
  35500. if (pDevice->pContext->callbacks.onDeviceStop != NULL) {
  35501. result = pDevice->pContext->callbacks.onDeviceStop(pDevice);
  35502. } else {
  35503. result = MA_INVALID_OPERATION;
  35504. }
  35505. ma_device__set_state(pDevice, ma_device_state_stopped);
  35506. } else {
  35507. /*
  35508. Synchronous backends. The stop callback is always called from the worker thread. Do not call the stop callback here. If
  35509. the backend is implementing it's own audio thread loop we'll need to wake it up if required. Note that we need to make
  35510. sure the state of the device is *not* playing right now, which it shouldn't be since we set it above. This is super
  35511. important though, so I'm asserting it here as well for extra safety in case we accidentally change something later.
  35512. */
  35513. MA_ASSERT(ma_device_get_state(pDevice) != ma_device_state_started);
  35514. if (pDevice->pContext->callbacks.onDeviceDataLoopWakeup != NULL) {
  35515. pDevice->pContext->callbacks.onDeviceDataLoopWakeup(pDevice);
  35516. }
  35517. /*
  35518. We need to wait for the worker thread to become available for work before returning. Note that the worker thread will be
  35519. the one who puts the device into the stopped state. Don't call ma_device__set_state() here.
  35520. */
  35521. ma_event_wait(&pDevice->stopEvent);
  35522. result = MA_SUCCESS;
  35523. }
  35524. /*
  35525. This is a safety measure to ensure the internal buffer has been cleared so any leftover
  35526. does not get played the next time the device starts. Ideally this should be drained by
  35527. the backend first.
  35528. */
  35529. pDevice->playback.intermediaryBufferLen = 0;
  35530. pDevice->playback.inputCacheConsumed = 0;
  35531. pDevice->playback.inputCacheRemaining = 0;
  35532. }
  35533. ma_mutex_unlock(&pDevice->startStopLock);
  35534. return result;
  35535. }
  35536. MA_API ma_bool32 ma_device_is_started(const ma_device* pDevice)
  35537. {
  35538. return ma_device_get_state(pDevice) == ma_device_state_started;
  35539. }
  35540. MA_API ma_device_state ma_device_get_state(const ma_device* pDevice)
  35541. {
  35542. if (pDevice == NULL) {
  35543. return ma_device_state_uninitialized;
  35544. }
  35545. return ma_atomic_device_state_get((ma_atomic_device_state*)&pDevice->state); /* Naughty cast to get rid of a const warning. */
  35546. }
  35547. MA_API ma_result ma_device_set_master_volume(ma_device* pDevice, float volume)
  35548. {
  35549. if (pDevice == NULL) {
  35550. return MA_INVALID_ARGS;
  35551. }
  35552. if (volume < 0.0f) {
  35553. return MA_INVALID_ARGS;
  35554. }
  35555. ma_atomic_float_set(&pDevice->masterVolumeFactor, volume);
  35556. return MA_SUCCESS;
  35557. }
  35558. MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume)
  35559. {
  35560. if (pVolume == NULL) {
  35561. return MA_INVALID_ARGS;
  35562. }
  35563. if (pDevice == NULL) {
  35564. *pVolume = 0;
  35565. return MA_INVALID_ARGS;
  35566. }
  35567. *pVolume = ma_atomic_float_get(&pDevice->masterVolumeFactor);
  35568. return MA_SUCCESS;
  35569. }
  35570. MA_API ma_result ma_device_set_master_volume_db(ma_device* pDevice, float gainDB)
  35571. {
  35572. if (gainDB > 0) {
  35573. return MA_INVALID_ARGS;
  35574. }
  35575. return ma_device_set_master_volume(pDevice, ma_volume_db_to_linear(gainDB));
  35576. }
  35577. MA_API ma_result ma_device_get_master_volume_db(ma_device* pDevice, float* pGainDB)
  35578. {
  35579. float factor;
  35580. ma_result result;
  35581. if (pGainDB == NULL) {
  35582. return MA_INVALID_ARGS;
  35583. }
  35584. result = ma_device_get_master_volume(pDevice, &factor);
  35585. if (result != MA_SUCCESS) {
  35586. *pGainDB = 0;
  35587. return result;
  35588. }
  35589. *pGainDB = ma_volume_linear_to_db(factor);
  35590. return MA_SUCCESS;
  35591. }
  35592. MA_API ma_result ma_device_handle_backend_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
  35593. {
  35594. if (pDevice == NULL) {
  35595. return MA_INVALID_ARGS;
  35596. }
  35597. if (pOutput == NULL && pInput == NULL) {
  35598. return MA_INVALID_ARGS;
  35599. }
  35600. if (pDevice->type == ma_device_type_duplex) {
  35601. if (pInput != NULL) {
  35602. ma_device__handle_duplex_callback_capture(pDevice, frameCount, pInput, &pDevice->duplexRB.rb);
  35603. }
  35604. if (pOutput != NULL) {
  35605. ma_device__handle_duplex_callback_playback(pDevice, frameCount, pOutput, &pDevice->duplexRB.rb);
  35606. }
  35607. } else {
  35608. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_loopback) {
  35609. if (pInput == NULL) {
  35610. return MA_INVALID_ARGS;
  35611. }
  35612. ma_device__send_frames_to_client(pDevice, frameCount, pInput);
  35613. }
  35614. if (pDevice->type == ma_device_type_playback) {
  35615. if (pOutput == NULL) {
  35616. return MA_INVALID_ARGS;
  35617. }
  35618. ma_device__read_frames_from_client(pDevice, frameCount, pOutput);
  35619. }
  35620. }
  35621. return MA_SUCCESS;
  35622. }
  35623. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_descriptor(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  35624. {
  35625. if (pDescriptor == NULL) {
  35626. return 0;
  35627. }
  35628. /*
  35629. We must have a non-0 native sample rate, but some backends don't allow retrieval of this at the
  35630. time when the size of the buffer needs to be determined. In this case we need to just take a best
  35631. guess and move on. We'll try using the sample rate in pDescriptor first. If that's not set we'll
  35632. just fall back to MA_DEFAULT_SAMPLE_RATE.
  35633. */
  35634. if (nativeSampleRate == 0) {
  35635. nativeSampleRate = pDescriptor->sampleRate;
  35636. }
  35637. if (nativeSampleRate == 0) {
  35638. nativeSampleRate = MA_DEFAULT_SAMPLE_RATE;
  35639. }
  35640. MA_ASSERT(nativeSampleRate != 0);
  35641. if (pDescriptor->periodSizeInFrames == 0) {
  35642. if (pDescriptor->periodSizeInMilliseconds == 0) {
  35643. if (performanceProfile == ma_performance_profile_low_latency) {
  35644. return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, nativeSampleRate);
  35645. } else {
  35646. return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, nativeSampleRate);
  35647. }
  35648. } else {
  35649. return ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate);
  35650. }
  35651. } else {
  35652. return pDescriptor->periodSizeInFrames;
  35653. }
  35654. }
  35655. #endif /* MA_NO_DEVICE_IO */
  35656. MA_API ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate)
  35657. {
  35658. /* Prevent a division by zero. */
  35659. if (sampleRate == 0) {
  35660. return 0;
  35661. }
  35662. return bufferSizeInFrames*1000 / sampleRate;
  35663. }
  35664. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate)
  35665. {
  35666. /* Prevent a division by zero. */
  35667. if (sampleRate == 0) {
  35668. return 0;
  35669. }
  35670. return bufferSizeInMilliseconds*sampleRate / 1000;
  35671. }
  35672. MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
  35673. {
  35674. if (dst == src) {
  35675. return; /* No-op. */
  35676. }
  35677. ma_copy_memory_64(dst, src, frameCount * ma_get_bytes_per_frame(format, channels));
  35678. }
  35679. MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
  35680. {
  35681. if (format == ma_format_u8) {
  35682. ma_uint64 sampleCount = frameCount * channels;
  35683. ma_uint64 iSample;
  35684. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35685. ((ma_uint8*)p)[iSample] = 128;
  35686. }
  35687. } else {
  35688. ma_zero_memory_64(p, frameCount * ma_get_bytes_per_frame(format, channels));
  35689. }
  35690. }
  35691. MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels)
  35692. {
  35693. return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels));
  35694. }
  35695. MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels)
  35696. {
  35697. return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels));
  35698. }
  35699. MA_API void ma_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count)
  35700. {
  35701. ma_uint64 iSample;
  35702. MA_ASSERT(pDst != NULL);
  35703. MA_ASSERT(pSrc != NULL);
  35704. for (iSample = 0; iSample < count; iSample += 1) {
  35705. pDst[iSample] = ma_clip_u8(pSrc[iSample]);
  35706. }
  35707. }
  35708. MA_API void ma_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count)
  35709. {
  35710. ma_uint64 iSample;
  35711. MA_ASSERT(pDst != NULL);
  35712. MA_ASSERT(pSrc != NULL);
  35713. for (iSample = 0; iSample < count; iSample += 1) {
  35714. pDst[iSample] = ma_clip_s16(pSrc[iSample]);
  35715. }
  35716. }
  35717. MA_API void ma_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count)
  35718. {
  35719. ma_uint64 iSample;
  35720. MA_ASSERT(pDst != NULL);
  35721. MA_ASSERT(pSrc != NULL);
  35722. for (iSample = 0; iSample < count; iSample += 1) {
  35723. ma_int64 s = ma_clip_s24(pSrc[iSample]);
  35724. pDst[iSample*3 + 0] = (ma_uint8)((s & 0x000000FF) >> 0);
  35725. pDst[iSample*3 + 1] = (ma_uint8)((s & 0x0000FF00) >> 8);
  35726. pDst[iSample*3 + 2] = (ma_uint8)((s & 0x00FF0000) >> 16);
  35727. }
  35728. }
  35729. MA_API void ma_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count)
  35730. {
  35731. ma_uint64 iSample;
  35732. MA_ASSERT(pDst != NULL);
  35733. MA_ASSERT(pSrc != NULL);
  35734. for (iSample = 0; iSample < count; iSample += 1) {
  35735. pDst[iSample] = ma_clip_s32(pSrc[iSample]);
  35736. }
  35737. }
  35738. MA_API void ma_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count)
  35739. {
  35740. ma_uint64 iSample;
  35741. MA_ASSERT(pDst != NULL);
  35742. MA_ASSERT(pSrc != NULL);
  35743. for (iSample = 0; iSample < count; iSample += 1) {
  35744. pDst[iSample] = ma_clip_f32(pSrc[iSample]);
  35745. }
  35746. }
  35747. MA_API void ma_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
  35748. {
  35749. ma_uint64 sampleCount;
  35750. MA_ASSERT(pDst != NULL);
  35751. MA_ASSERT(pSrc != NULL);
  35752. sampleCount = frameCount * channels;
  35753. switch (format) {
  35754. case ma_format_u8: ma_clip_samples_u8( (ma_uint8*)pDst, (const ma_int16*)pSrc, sampleCount); break;
  35755. case ma_format_s16: ma_clip_samples_s16((ma_int16*)pDst, (const ma_int32*)pSrc, sampleCount); break;
  35756. case ma_format_s24: ma_clip_samples_s24((ma_uint8*)pDst, (const ma_int64*)pSrc, sampleCount); break;
  35757. case ma_format_s32: ma_clip_samples_s32((ma_int32*)pDst, (const ma_int64*)pSrc, sampleCount); break;
  35758. case ma_format_f32: ma_clip_samples_f32(( float*)pDst, (const float*)pSrc, sampleCount); break;
  35759. /* Do nothing if we don't know the format. We're including these here to silence a compiler warning about enums not being handled by the switch. */
  35760. case ma_format_unknown:
  35761. case ma_format_count:
  35762. break;
  35763. }
  35764. }
  35765. MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor)
  35766. {
  35767. ma_uint64 iSample;
  35768. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35769. return;
  35770. }
  35771. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35772. pSamplesOut[iSample] = (ma_uint8)(pSamplesIn[iSample] * factor);
  35773. }
  35774. }
  35775. MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor)
  35776. {
  35777. ma_uint64 iSample;
  35778. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35779. return;
  35780. }
  35781. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35782. pSamplesOut[iSample] = (ma_int16)(pSamplesIn[iSample] * factor);
  35783. }
  35784. }
  35785. MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor)
  35786. {
  35787. ma_uint64 iSample;
  35788. ma_uint8* pSamplesOut8;
  35789. ma_uint8* pSamplesIn8;
  35790. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35791. return;
  35792. }
  35793. pSamplesOut8 = (ma_uint8*)pSamplesOut;
  35794. pSamplesIn8 = (ma_uint8*)pSamplesIn;
  35795. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35796. ma_int32 sampleS32;
  35797. sampleS32 = (ma_int32)(((ma_uint32)(pSamplesIn8[iSample*3+0]) << 8) | ((ma_uint32)(pSamplesIn8[iSample*3+1]) << 16) | ((ma_uint32)(pSamplesIn8[iSample*3+2])) << 24);
  35798. sampleS32 = (ma_int32)(sampleS32 * factor);
  35799. pSamplesOut8[iSample*3+0] = (ma_uint8)(((ma_uint32)sampleS32 & 0x0000FF00) >> 8);
  35800. pSamplesOut8[iSample*3+1] = (ma_uint8)(((ma_uint32)sampleS32 & 0x00FF0000) >> 16);
  35801. pSamplesOut8[iSample*3+2] = (ma_uint8)(((ma_uint32)sampleS32 & 0xFF000000) >> 24);
  35802. }
  35803. }
  35804. MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor)
  35805. {
  35806. ma_uint64 iSample;
  35807. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35808. return;
  35809. }
  35810. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35811. pSamplesOut[iSample] = (ma_int32)(pSamplesIn[iSample] * factor);
  35812. }
  35813. }
  35814. MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor)
  35815. {
  35816. ma_uint64 iSample;
  35817. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35818. return;
  35819. }
  35820. if (factor == 1) {
  35821. if (pSamplesOut == pSamplesIn) {
  35822. /* In place. No-op. */
  35823. } else {
  35824. /* Just a copy. */
  35825. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35826. pSamplesOut[iSample] = pSamplesIn[iSample];
  35827. }
  35828. }
  35829. } else {
  35830. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35831. pSamplesOut[iSample] = pSamplesIn[iSample] * factor;
  35832. }
  35833. }
  35834. }
  35835. MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor)
  35836. {
  35837. ma_copy_and_apply_volume_factor_u8(pSamples, pSamples, sampleCount, factor);
  35838. }
  35839. MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor)
  35840. {
  35841. ma_copy_and_apply_volume_factor_s16(pSamples, pSamples, sampleCount, factor);
  35842. }
  35843. MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor)
  35844. {
  35845. ma_copy_and_apply_volume_factor_s24(pSamples, pSamples, sampleCount, factor);
  35846. }
  35847. MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor)
  35848. {
  35849. ma_copy_and_apply_volume_factor_s32(pSamples, pSamples, sampleCount, factor);
  35850. }
  35851. MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor)
  35852. {
  35853. ma_copy_and_apply_volume_factor_f32(pSamples, pSamples, sampleCount, factor);
  35854. }
  35855. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_u8(ma_uint8* pFramesOut, const ma_uint8* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35856. {
  35857. ma_copy_and_apply_volume_factor_u8(pFramesOut, pFramesIn, frameCount*channels, factor);
  35858. }
  35859. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s16(ma_int16* pFramesOut, const ma_int16* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35860. {
  35861. ma_copy_and_apply_volume_factor_s16(pFramesOut, pFramesIn, frameCount*channels, factor);
  35862. }
  35863. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s24(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35864. {
  35865. ma_copy_and_apply_volume_factor_s24(pFramesOut, pFramesIn, frameCount*channels, factor);
  35866. }
  35867. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s32(ma_int32* pFramesOut, const ma_int32* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35868. {
  35869. ma_copy_and_apply_volume_factor_s32(pFramesOut, pFramesIn, frameCount*channels, factor);
  35870. }
  35871. MA_API void ma_copy_and_apply_volume_factor_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35872. {
  35873. ma_copy_and_apply_volume_factor_f32(pFramesOut, pFramesIn, frameCount*channels, factor);
  35874. }
  35875. MA_API void ma_copy_and_apply_volume_factor_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor)
  35876. {
  35877. switch (format)
  35878. {
  35879. case ma_format_u8: ma_copy_and_apply_volume_factor_pcm_frames_u8 ((ma_uint8*)pFramesOut, (const ma_uint8*)pFramesIn, frameCount, channels, factor); return;
  35880. case ma_format_s16: ma_copy_and_apply_volume_factor_pcm_frames_s16((ma_int16*)pFramesOut, (const ma_int16*)pFramesIn, frameCount, channels, factor); return;
  35881. case ma_format_s24: ma_copy_and_apply_volume_factor_pcm_frames_s24( pFramesOut, pFramesIn, frameCount, channels, factor); return;
  35882. case ma_format_s32: ma_copy_and_apply_volume_factor_pcm_frames_s32((ma_int32*)pFramesOut, (const ma_int32*)pFramesIn, frameCount, channels, factor); return;
  35883. case ma_format_f32: ma_copy_and_apply_volume_factor_pcm_frames_f32( (float*)pFramesOut, (const float*)pFramesIn, frameCount, channels, factor); return;
  35884. default: return; /* Do nothing. */
  35885. }
  35886. }
  35887. MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35888. {
  35889. ma_copy_and_apply_volume_factor_pcm_frames_u8(pFrames, pFrames, frameCount, channels, factor);
  35890. }
  35891. MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35892. {
  35893. ma_copy_and_apply_volume_factor_pcm_frames_s16(pFrames, pFrames, frameCount, channels, factor);
  35894. }
  35895. MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35896. {
  35897. ma_copy_and_apply_volume_factor_pcm_frames_s24(pFrames, pFrames, frameCount, channels, factor);
  35898. }
  35899. MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35900. {
  35901. ma_copy_and_apply_volume_factor_pcm_frames_s32(pFrames, pFrames, frameCount, channels, factor);
  35902. }
  35903. MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35904. {
  35905. ma_copy_and_apply_volume_factor_pcm_frames_f32(pFrames, pFrames, frameCount, channels, factor);
  35906. }
  35907. MA_API void ma_apply_volume_factor_pcm_frames(void* pFramesOut, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor)
  35908. {
  35909. ma_copy_and_apply_volume_factor_pcm_frames(pFramesOut, pFramesOut, frameCount, format, channels, factor);
  35910. }
  35911. MA_API void ma_copy_and_apply_volume_factor_per_channel_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, ma_uint32 channels, float* pChannelGains)
  35912. {
  35913. ma_uint64 iFrame;
  35914. if (channels == 2) {
  35915. /* TODO: Do an optimized implementation for stereo and mono. Can do a SIMD optimized implementation as well. */
  35916. }
  35917. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35918. ma_uint32 iChannel;
  35919. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  35920. pFramesOut[iFrame * channels + iChannel] = pFramesIn[iFrame * channels + iChannel] * pChannelGains[iChannel];
  35921. }
  35922. }
  35923. }
  35924. static MA_INLINE ma_int16 ma_apply_volume_unclipped_u8(ma_int16 x, ma_int16 volume)
  35925. {
  35926. return (ma_int16)(((ma_int32)x * (ma_int32)volume) >> 8);
  35927. }
  35928. static MA_INLINE ma_int32 ma_apply_volume_unclipped_s16(ma_int32 x, ma_int16 volume)
  35929. {
  35930. return (ma_int32)((x * volume) >> 8);
  35931. }
  35932. static MA_INLINE ma_int64 ma_apply_volume_unclipped_s24(ma_int64 x, ma_int16 volume)
  35933. {
  35934. return (ma_int64)((x * volume) >> 8);
  35935. }
  35936. static MA_INLINE ma_int64 ma_apply_volume_unclipped_s32(ma_int64 x, ma_int16 volume)
  35937. {
  35938. return (ma_int64)((x * volume) >> 8);
  35939. }
  35940. static MA_INLINE float ma_apply_volume_unclipped_f32(float x, float volume)
  35941. {
  35942. return x * volume;
  35943. }
  35944. MA_API void ma_copy_and_apply_volume_and_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count, float volume)
  35945. {
  35946. ma_uint64 iSample;
  35947. ma_int16 volumeFixed;
  35948. MA_ASSERT(pDst != NULL);
  35949. MA_ASSERT(pSrc != NULL);
  35950. volumeFixed = ma_float_to_fixed_16(volume);
  35951. for (iSample = 0; iSample < count; iSample += 1) {
  35952. pDst[iSample] = ma_clip_u8(ma_apply_volume_unclipped_u8(pSrc[iSample], volumeFixed));
  35953. }
  35954. }
  35955. MA_API void ma_copy_and_apply_volume_and_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count, float volume)
  35956. {
  35957. ma_uint64 iSample;
  35958. ma_int16 volumeFixed;
  35959. MA_ASSERT(pDst != NULL);
  35960. MA_ASSERT(pSrc != NULL);
  35961. volumeFixed = ma_float_to_fixed_16(volume);
  35962. for (iSample = 0; iSample < count; iSample += 1) {
  35963. pDst[iSample] = ma_clip_s16(ma_apply_volume_unclipped_s16(pSrc[iSample], volumeFixed));
  35964. }
  35965. }
  35966. MA_API void ma_copy_and_apply_volume_and_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count, float volume)
  35967. {
  35968. ma_uint64 iSample;
  35969. ma_int16 volumeFixed;
  35970. MA_ASSERT(pDst != NULL);
  35971. MA_ASSERT(pSrc != NULL);
  35972. volumeFixed = ma_float_to_fixed_16(volume);
  35973. for (iSample = 0; iSample < count; iSample += 1) {
  35974. ma_int64 s = ma_clip_s24(ma_apply_volume_unclipped_s24(pSrc[iSample], volumeFixed));
  35975. pDst[iSample*3 + 0] = (ma_uint8)((s & 0x000000FF) >> 0);
  35976. pDst[iSample*3 + 1] = (ma_uint8)((s & 0x0000FF00) >> 8);
  35977. pDst[iSample*3 + 2] = (ma_uint8)((s & 0x00FF0000) >> 16);
  35978. }
  35979. }
  35980. MA_API void ma_copy_and_apply_volume_and_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count, float volume)
  35981. {
  35982. ma_uint64 iSample;
  35983. ma_int16 volumeFixed;
  35984. MA_ASSERT(pDst != NULL);
  35985. MA_ASSERT(pSrc != NULL);
  35986. volumeFixed = ma_float_to_fixed_16(volume);
  35987. for (iSample = 0; iSample < count; iSample += 1) {
  35988. pDst[iSample] = ma_clip_s32(ma_apply_volume_unclipped_s32(pSrc[iSample], volumeFixed));
  35989. }
  35990. }
  35991. MA_API void ma_copy_and_apply_volume_and_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count, float volume)
  35992. {
  35993. ma_uint64 iSample;
  35994. MA_ASSERT(pDst != NULL);
  35995. MA_ASSERT(pSrc != NULL);
  35996. /* For the f32 case we need to make sure this supports in-place processing where the input and output buffers are the same. */
  35997. for (iSample = 0; iSample < count; iSample += 1) {
  35998. pDst[iSample] = ma_clip_f32(ma_apply_volume_unclipped_f32(pSrc[iSample], volume));
  35999. }
  36000. }
  36001. MA_API void ma_copy_and_apply_volume_and_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float volume)
  36002. {
  36003. MA_ASSERT(pDst != NULL);
  36004. MA_ASSERT(pSrc != NULL);
  36005. if (volume == 1) {
  36006. ma_clip_pcm_frames(pDst, pSrc, frameCount, format, channels); /* Optimized case for volume = 1. */
  36007. } else if (volume == 0) {
  36008. ma_silence_pcm_frames(pDst, frameCount, format, channels); /* Optimized case for volume = 0. */
  36009. } else {
  36010. ma_uint64 sampleCount = frameCount * channels;
  36011. switch (format) {
  36012. case ma_format_u8: ma_copy_and_apply_volume_and_clip_samples_u8( (ma_uint8*)pDst, (const ma_int16*)pSrc, sampleCount, volume); break;
  36013. case ma_format_s16: ma_copy_and_apply_volume_and_clip_samples_s16((ma_int16*)pDst, (const ma_int32*)pSrc, sampleCount, volume); break;
  36014. case ma_format_s24: ma_copy_and_apply_volume_and_clip_samples_s24((ma_uint8*)pDst, (const ma_int64*)pSrc, sampleCount, volume); break;
  36015. case ma_format_s32: ma_copy_and_apply_volume_and_clip_samples_s32((ma_int32*)pDst, (const ma_int64*)pSrc, sampleCount, volume); break;
  36016. case ma_format_f32: ma_copy_and_apply_volume_and_clip_samples_f32(( float*)pDst, (const float*)pSrc, sampleCount, volume); break;
  36017. /* Do nothing if we don't know the format. We're including these here to silence a compiler warning about enums not being handled by the switch. */
  36018. case ma_format_unknown:
  36019. case ma_format_count:
  36020. break;
  36021. }
  36022. }
  36023. }
  36024. MA_API float ma_volume_linear_to_db(float factor)
  36025. {
  36026. return 20*ma_log10f(factor);
  36027. }
  36028. MA_API float ma_volume_db_to_linear(float gain)
  36029. {
  36030. return ma_powf(10, gain/20.0f);
  36031. }
  36032. MA_API ma_result ma_mix_pcm_frames_f32(float* pDst, const float* pSrc, ma_uint64 frameCount, ma_uint32 channels, float volume)
  36033. {
  36034. ma_uint64 iSample;
  36035. ma_uint64 sampleCount;
  36036. if (pDst == NULL || pSrc == NULL || channels == 0) {
  36037. return MA_INVALID_ARGS;
  36038. }
  36039. if (volume == 0) {
  36040. return MA_SUCCESS; /* No changes if the volume is 0. */
  36041. }
  36042. sampleCount = frameCount * channels;
  36043. if (volume == 1) {
  36044. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  36045. pDst[iSample] += pSrc[iSample];
  36046. }
  36047. } else {
  36048. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  36049. pDst[iSample] += ma_apply_volume_unclipped_f32(pSrc[iSample], volume);
  36050. }
  36051. }
  36052. return MA_SUCCESS;
  36053. }
  36054. /**************************************************************************************************************************************************************
  36055. Format Conversion
  36056. **************************************************************************************************************************************************************/
  36057. static MA_INLINE ma_int16 ma_pcm_sample_f32_to_s16(float x)
  36058. {
  36059. return (ma_int16)(x * 32767.0f);
  36060. }
  36061. static MA_INLINE ma_int16 ma_pcm_sample_u8_to_s16_no_scale(ma_uint8 x)
  36062. {
  36063. return (ma_int16)((ma_int16)x - 128);
  36064. }
  36065. static MA_INLINE ma_int64 ma_pcm_sample_s24_to_s32_no_scale(const ma_uint8* x)
  36066. {
  36067. return (ma_int64)(((ma_uint64)x[0] << 40) | ((ma_uint64)x[1] << 48) | ((ma_uint64)x[2] << 56)) >> 40; /* Make sure the sign bits are maintained. */
  36068. }
  36069. static MA_INLINE void ma_pcm_sample_s32_to_s24_no_scale(ma_int64 x, ma_uint8* s24)
  36070. {
  36071. s24[0] = (ma_uint8)((x & 0x000000FF) >> 0);
  36072. s24[1] = (ma_uint8)((x & 0x0000FF00) >> 8);
  36073. s24[2] = (ma_uint8)((x & 0x00FF0000) >> 16);
  36074. }
  36075. /* u8 */
  36076. MA_API void ma_pcm_u8_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36077. {
  36078. (void)ditherMode;
  36079. ma_copy_memory_64(dst, src, count * sizeof(ma_uint8));
  36080. }
  36081. static MA_INLINE void ma_pcm_u8_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36082. {
  36083. ma_int16* dst_s16 = (ma_int16*)dst;
  36084. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36085. ma_uint64 i;
  36086. for (i = 0; i < count; i += 1) {
  36087. ma_int16 x = src_u8[i];
  36088. x = (ma_int16)(x - 128);
  36089. x = (ma_int16)(x << 8);
  36090. dst_s16[i] = x;
  36091. }
  36092. (void)ditherMode;
  36093. }
  36094. static MA_INLINE void ma_pcm_u8_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36095. {
  36096. ma_pcm_u8_to_s16__reference(dst, src, count, ditherMode);
  36097. }
  36098. #if defined(MA_SUPPORT_SSE2)
  36099. static MA_INLINE void ma_pcm_u8_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36100. {
  36101. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  36102. }
  36103. #endif
  36104. #if defined(MA_SUPPORT_NEON)
  36105. static MA_INLINE void ma_pcm_u8_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36106. {
  36107. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  36108. }
  36109. #endif
  36110. MA_API void ma_pcm_u8_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36111. {
  36112. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36113. ma_pcm_u8_to_s16__reference(dst, src, count, ditherMode);
  36114. #else
  36115. # if defined(MA_SUPPORT_SSE2)
  36116. if (ma_has_sse2()) {
  36117. ma_pcm_u8_to_s16__sse2(dst, src, count, ditherMode);
  36118. } else
  36119. #elif defined(MA_SUPPORT_NEON)
  36120. if (ma_has_neon()) {
  36121. ma_pcm_u8_to_s16__neon(dst, src, count, ditherMode);
  36122. } else
  36123. #endif
  36124. {
  36125. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  36126. }
  36127. #endif
  36128. }
  36129. static MA_INLINE void ma_pcm_u8_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36130. {
  36131. ma_uint8* dst_s24 = (ma_uint8*)dst;
  36132. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36133. ma_uint64 i;
  36134. for (i = 0; i < count; i += 1) {
  36135. ma_int16 x = src_u8[i];
  36136. x = (ma_int16)(x - 128);
  36137. dst_s24[i*3+0] = 0;
  36138. dst_s24[i*3+1] = 0;
  36139. dst_s24[i*3+2] = (ma_uint8)((ma_int8)x);
  36140. }
  36141. (void)ditherMode;
  36142. }
  36143. static MA_INLINE void ma_pcm_u8_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36144. {
  36145. ma_pcm_u8_to_s24__reference(dst, src, count, ditherMode);
  36146. }
  36147. #if defined(MA_SUPPORT_SSE2)
  36148. static MA_INLINE void ma_pcm_u8_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36149. {
  36150. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  36151. }
  36152. #endif
  36153. #if defined(MA_SUPPORT_NEON)
  36154. static MA_INLINE void ma_pcm_u8_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36155. {
  36156. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  36157. }
  36158. #endif
  36159. MA_API void ma_pcm_u8_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36160. {
  36161. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36162. ma_pcm_u8_to_s24__reference(dst, src, count, ditherMode);
  36163. #else
  36164. # if defined(MA_SUPPORT_SSE2)
  36165. if (ma_has_sse2()) {
  36166. ma_pcm_u8_to_s24__sse2(dst, src, count, ditherMode);
  36167. } else
  36168. #elif defined(MA_SUPPORT_NEON)
  36169. if (ma_has_neon()) {
  36170. ma_pcm_u8_to_s24__neon(dst, src, count, ditherMode);
  36171. } else
  36172. #endif
  36173. {
  36174. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  36175. }
  36176. #endif
  36177. }
  36178. static MA_INLINE void ma_pcm_u8_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36179. {
  36180. ma_int32* dst_s32 = (ma_int32*)dst;
  36181. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36182. ma_uint64 i;
  36183. for (i = 0; i < count; i += 1) {
  36184. ma_int32 x = src_u8[i];
  36185. x = x - 128;
  36186. x = x << 24;
  36187. dst_s32[i] = x;
  36188. }
  36189. (void)ditherMode;
  36190. }
  36191. static MA_INLINE void ma_pcm_u8_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36192. {
  36193. ma_pcm_u8_to_s32__reference(dst, src, count, ditherMode);
  36194. }
  36195. #if defined(MA_SUPPORT_SSE2)
  36196. static MA_INLINE void ma_pcm_u8_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36197. {
  36198. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  36199. }
  36200. #endif
  36201. #if defined(MA_SUPPORT_NEON)
  36202. static MA_INLINE void ma_pcm_u8_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36203. {
  36204. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  36205. }
  36206. #endif
  36207. MA_API void ma_pcm_u8_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36208. {
  36209. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36210. ma_pcm_u8_to_s32__reference(dst, src, count, ditherMode);
  36211. #else
  36212. # if defined(MA_SUPPORT_SSE2)
  36213. if (ma_has_sse2()) {
  36214. ma_pcm_u8_to_s32__sse2(dst, src, count, ditherMode);
  36215. } else
  36216. #elif defined(MA_SUPPORT_NEON)
  36217. if (ma_has_neon()) {
  36218. ma_pcm_u8_to_s32__neon(dst, src, count, ditherMode);
  36219. } else
  36220. #endif
  36221. {
  36222. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  36223. }
  36224. #endif
  36225. }
  36226. static MA_INLINE void ma_pcm_u8_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36227. {
  36228. float* dst_f32 = (float*)dst;
  36229. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36230. ma_uint64 i;
  36231. for (i = 0; i < count; i += 1) {
  36232. float x = (float)src_u8[i];
  36233. x = x * 0.00784313725490196078f; /* 0..255 to 0..2 */
  36234. x = x - 1; /* 0..2 to -1..1 */
  36235. dst_f32[i] = x;
  36236. }
  36237. (void)ditherMode;
  36238. }
  36239. static MA_INLINE void ma_pcm_u8_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36240. {
  36241. ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode);
  36242. }
  36243. #if defined(MA_SUPPORT_SSE2)
  36244. static MA_INLINE void ma_pcm_u8_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36245. {
  36246. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  36247. }
  36248. #endif
  36249. #if defined(MA_SUPPORT_NEON)
  36250. static MA_INLINE void ma_pcm_u8_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36251. {
  36252. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  36253. }
  36254. #endif
  36255. MA_API void ma_pcm_u8_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36256. {
  36257. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36258. ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode);
  36259. #else
  36260. # if defined(MA_SUPPORT_SSE2)
  36261. if (ma_has_sse2()) {
  36262. ma_pcm_u8_to_f32__sse2(dst, src, count, ditherMode);
  36263. } else
  36264. #elif defined(MA_SUPPORT_NEON)
  36265. if (ma_has_neon()) {
  36266. ma_pcm_u8_to_f32__neon(dst, src, count, ditherMode);
  36267. } else
  36268. #endif
  36269. {
  36270. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  36271. }
  36272. #endif
  36273. }
  36274. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36275. static MA_INLINE void ma_pcm_interleave_u8__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36276. {
  36277. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36278. const ma_uint8** src_u8 = (const ma_uint8**)src;
  36279. ma_uint64 iFrame;
  36280. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36281. ma_uint32 iChannel;
  36282. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36283. dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame];
  36284. }
  36285. }
  36286. }
  36287. #else
  36288. static MA_INLINE void ma_pcm_interleave_u8__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36289. {
  36290. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36291. const ma_uint8** src_u8 = (const ma_uint8**)src;
  36292. if (channels == 1) {
  36293. ma_copy_memory_64(dst, src[0], frameCount * sizeof(ma_uint8));
  36294. } else if (channels == 2) {
  36295. ma_uint64 iFrame;
  36296. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36297. dst_u8[iFrame*2 + 0] = src_u8[0][iFrame];
  36298. dst_u8[iFrame*2 + 1] = src_u8[1][iFrame];
  36299. }
  36300. } else {
  36301. ma_uint64 iFrame;
  36302. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36303. ma_uint32 iChannel;
  36304. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36305. dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame];
  36306. }
  36307. }
  36308. }
  36309. }
  36310. #endif
  36311. MA_API void ma_pcm_interleave_u8(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36312. {
  36313. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36314. ma_pcm_interleave_u8__reference(dst, src, frameCount, channels);
  36315. #else
  36316. ma_pcm_interleave_u8__optimized(dst, src, frameCount, channels);
  36317. #endif
  36318. }
  36319. static MA_INLINE void ma_pcm_deinterleave_u8__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36320. {
  36321. ma_uint8** dst_u8 = (ma_uint8**)dst;
  36322. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36323. ma_uint64 iFrame;
  36324. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36325. ma_uint32 iChannel;
  36326. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36327. dst_u8[iChannel][iFrame] = src_u8[iFrame*channels + iChannel];
  36328. }
  36329. }
  36330. }
  36331. static MA_INLINE void ma_pcm_deinterleave_u8__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36332. {
  36333. ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels);
  36334. }
  36335. MA_API void ma_pcm_deinterleave_u8(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36336. {
  36337. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36338. ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels);
  36339. #else
  36340. ma_pcm_deinterleave_u8__optimized(dst, src, frameCount, channels);
  36341. #endif
  36342. }
  36343. /* s16 */
  36344. static MA_INLINE void ma_pcm_s16_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36345. {
  36346. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36347. const ma_int16* src_s16 = (const ma_int16*)src;
  36348. if (ditherMode == ma_dither_mode_none) {
  36349. ma_uint64 i;
  36350. for (i = 0; i < count; i += 1) {
  36351. ma_int16 x = src_s16[i];
  36352. x = (ma_int16)(x >> 8);
  36353. x = (ma_int16)(x + 128);
  36354. dst_u8[i] = (ma_uint8)x;
  36355. }
  36356. } else {
  36357. ma_uint64 i;
  36358. for (i = 0; i < count; i += 1) {
  36359. ma_int16 x = src_s16[i];
  36360. /* Dither. Don't overflow. */
  36361. ma_int32 dither = ma_dither_s32(ditherMode, -0x80, 0x7F);
  36362. if ((x + dither) <= 0x7FFF) {
  36363. x = (ma_int16)(x + dither);
  36364. } else {
  36365. x = 0x7FFF;
  36366. }
  36367. x = (ma_int16)(x >> 8);
  36368. x = (ma_int16)(x + 128);
  36369. dst_u8[i] = (ma_uint8)x;
  36370. }
  36371. }
  36372. }
  36373. static MA_INLINE void ma_pcm_s16_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36374. {
  36375. ma_pcm_s16_to_u8__reference(dst, src, count, ditherMode);
  36376. }
  36377. #if defined(MA_SUPPORT_SSE2)
  36378. static MA_INLINE void ma_pcm_s16_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36379. {
  36380. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  36381. }
  36382. #endif
  36383. #if defined(MA_SUPPORT_NEON)
  36384. static MA_INLINE void ma_pcm_s16_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36385. {
  36386. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  36387. }
  36388. #endif
  36389. MA_API void ma_pcm_s16_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36390. {
  36391. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36392. ma_pcm_s16_to_u8__reference(dst, src, count, ditherMode);
  36393. #else
  36394. # if defined(MA_SUPPORT_SSE2)
  36395. if (ma_has_sse2()) {
  36396. ma_pcm_s16_to_u8__sse2(dst, src, count, ditherMode);
  36397. } else
  36398. #elif defined(MA_SUPPORT_NEON)
  36399. if (ma_has_neon()) {
  36400. ma_pcm_s16_to_u8__neon(dst, src, count, ditherMode);
  36401. } else
  36402. #endif
  36403. {
  36404. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  36405. }
  36406. #endif
  36407. }
  36408. MA_API void ma_pcm_s16_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36409. {
  36410. (void)ditherMode;
  36411. ma_copy_memory_64(dst, src, count * sizeof(ma_int16));
  36412. }
  36413. static MA_INLINE void ma_pcm_s16_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36414. {
  36415. ma_uint8* dst_s24 = (ma_uint8*)dst;
  36416. const ma_int16* src_s16 = (const ma_int16*)src;
  36417. ma_uint64 i;
  36418. for (i = 0; i < count; i += 1) {
  36419. dst_s24[i*3+0] = 0;
  36420. dst_s24[i*3+1] = (ma_uint8)(src_s16[i] & 0xFF);
  36421. dst_s24[i*3+2] = (ma_uint8)(src_s16[i] >> 8);
  36422. }
  36423. (void)ditherMode;
  36424. }
  36425. static MA_INLINE void ma_pcm_s16_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36426. {
  36427. ma_pcm_s16_to_s24__reference(dst, src, count, ditherMode);
  36428. }
  36429. #if defined(MA_SUPPORT_SSE2)
  36430. static MA_INLINE void ma_pcm_s16_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36431. {
  36432. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  36433. }
  36434. #endif
  36435. #if defined(MA_SUPPORT_NEON)
  36436. static MA_INLINE void ma_pcm_s16_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36437. {
  36438. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  36439. }
  36440. #endif
  36441. MA_API void ma_pcm_s16_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36442. {
  36443. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36444. ma_pcm_s16_to_s24__reference(dst, src, count, ditherMode);
  36445. #else
  36446. # if defined(MA_SUPPORT_SSE2)
  36447. if (ma_has_sse2()) {
  36448. ma_pcm_s16_to_s24__sse2(dst, src, count, ditherMode);
  36449. } else
  36450. #elif defined(MA_SUPPORT_NEON)
  36451. if (ma_has_neon()) {
  36452. ma_pcm_s16_to_s24__neon(dst, src, count, ditherMode);
  36453. } else
  36454. #endif
  36455. {
  36456. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  36457. }
  36458. #endif
  36459. }
  36460. static MA_INLINE void ma_pcm_s16_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36461. {
  36462. ma_int32* dst_s32 = (ma_int32*)dst;
  36463. const ma_int16* src_s16 = (const ma_int16*)src;
  36464. ma_uint64 i;
  36465. for (i = 0; i < count; i += 1) {
  36466. dst_s32[i] = src_s16[i] << 16;
  36467. }
  36468. (void)ditherMode;
  36469. }
  36470. static MA_INLINE void ma_pcm_s16_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36471. {
  36472. ma_pcm_s16_to_s32__reference(dst, src, count, ditherMode);
  36473. }
  36474. #if defined(MA_SUPPORT_SSE2)
  36475. static MA_INLINE void ma_pcm_s16_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36476. {
  36477. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  36478. }
  36479. #endif
  36480. #if defined(MA_SUPPORT_NEON)
  36481. static MA_INLINE void ma_pcm_s16_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36482. {
  36483. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  36484. }
  36485. #endif
  36486. MA_API void ma_pcm_s16_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36487. {
  36488. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36489. ma_pcm_s16_to_s32__reference(dst, src, count, ditherMode);
  36490. #else
  36491. # if defined(MA_SUPPORT_SSE2)
  36492. if (ma_has_sse2()) {
  36493. ma_pcm_s16_to_s32__sse2(dst, src, count, ditherMode);
  36494. } else
  36495. #elif defined(MA_SUPPORT_NEON)
  36496. if (ma_has_neon()) {
  36497. ma_pcm_s16_to_s32__neon(dst, src, count, ditherMode);
  36498. } else
  36499. #endif
  36500. {
  36501. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  36502. }
  36503. #endif
  36504. }
  36505. static MA_INLINE void ma_pcm_s16_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36506. {
  36507. float* dst_f32 = (float*)dst;
  36508. const ma_int16* src_s16 = (const ma_int16*)src;
  36509. ma_uint64 i;
  36510. for (i = 0; i < count; i += 1) {
  36511. float x = (float)src_s16[i];
  36512. #if 0
  36513. /* The accurate way. */
  36514. x = x + 32768.0f; /* -32768..32767 to 0..65535 */
  36515. x = x * 0.00003051804379339284f; /* 0..65535 to 0..2 */
  36516. x = x - 1; /* 0..2 to -1..1 */
  36517. #else
  36518. /* The fast way. */
  36519. x = x * 0.000030517578125f; /* -32768..32767 to -1..0.999969482421875 */
  36520. #endif
  36521. dst_f32[i] = x;
  36522. }
  36523. (void)ditherMode;
  36524. }
  36525. static MA_INLINE void ma_pcm_s16_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36526. {
  36527. ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode);
  36528. }
  36529. #if defined(MA_SUPPORT_SSE2)
  36530. static MA_INLINE void ma_pcm_s16_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36531. {
  36532. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  36533. }
  36534. #endif
  36535. #if defined(MA_SUPPORT_NEON)
  36536. static MA_INLINE void ma_pcm_s16_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36537. {
  36538. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  36539. }
  36540. #endif
  36541. MA_API void ma_pcm_s16_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36542. {
  36543. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36544. ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode);
  36545. #else
  36546. # if defined(MA_SUPPORT_SSE2)
  36547. if (ma_has_sse2()) {
  36548. ma_pcm_s16_to_f32__sse2(dst, src, count, ditherMode);
  36549. } else
  36550. #elif defined(MA_SUPPORT_NEON)
  36551. if (ma_has_neon()) {
  36552. ma_pcm_s16_to_f32__neon(dst, src, count, ditherMode);
  36553. } else
  36554. #endif
  36555. {
  36556. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  36557. }
  36558. #endif
  36559. }
  36560. static MA_INLINE void ma_pcm_interleave_s16__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36561. {
  36562. ma_int16* dst_s16 = (ma_int16*)dst;
  36563. const ma_int16** src_s16 = (const ma_int16**)src;
  36564. ma_uint64 iFrame;
  36565. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36566. ma_uint32 iChannel;
  36567. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36568. dst_s16[iFrame*channels + iChannel] = src_s16[iChannel][iFrame];
  36569. }
  36570. }
  36571. }
  36572. static MA_INLINE void ma_pcm_interleave_s16__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36573. {
  36574. ma_pcm_interleave_s16__reference(dst, src, frameCount, channels);
  36575. }
  36576. MA_API void ma_pcm_interleave_s16(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36577. {
  36578. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36579. ma_pcm_interleave_s16__reference(dst, src, frameCount, channels);
  36580. #else
  36581. ma_pcm_interleave_s16__optimized(dst, src, frameCount, channels);
  36582. #endif
  36583. }
  36584. static MA_INLINE void ma_pcm_deinterleave_s16__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36585. {
  36586. ma_int16** dst_s16 = (ma_int16**)dst;
  36587. const ma_int16* src_s16 = (const ma_int16*)src;
  36588. ma_uint64 iFrame;
  36589. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36590. ma_uint32 iChannel;
  36591. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36592. dst_s16[iChannel][iFrame] = src_s16[iFrame*channels + iChannel];
  36593. }
  36594. }
  36595. }
  36596. static MA_INLINE void ma_pcm_deinterleave_s16__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36597. {
  36598. ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels);
  36599. }
  36600. MA_API void ma_pcm_deinterleave_s16(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36601. {
  36602. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36603. ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels);
  36604. #else
  36605. ma_pcm_deinterleave_s16__optimized(dst, src, frameCount, channels);
  36606. #endif
  36607. }
  36608. /* s24 */
  36609. static MA_INLINE void ma_pcm_s24_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36610. {
  36611. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36612. const ma_uint8* src_s24 = (const ma_uint8*)src;
  36613. if (ditherMode == ma_dither_mode_none) {
  36614. ma_uint64 i;
  36615. for (i = 0; i < count; i += 1) {
  36616. dst_u8[i] = (ma_uint8)((ma_int8)src_s24[i*3 + 2] + 128);
  36617. }
  36618. } else {
  36619. ma_uint64 i;
  36620. for (i = 0; i < count; i += 1) {
  36621. ma_int32 x = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24);
  36622. /* Dither. Don't overflow. */
  36623. ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF);
  36624. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  36625. x = x + dither;
  36626. } else {
  36627. x = 0x7FFFFFFF;
  36628. }
  36629. x = x >> 24;
  36630. x = x + 128;
  36631. dst_u8[i] = (ma_uint8)x;
  36632. }
  36633. }
  36634. }
  36635. static MA_INLINE void ma_pcm_s24_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36636. {
  36637. ma_pcm_s24_to_u8__reference(dst, src, count, ditherMode);
  36638. }
  36639. #if defined(MA_SUPPORT_SSE2)
  36640. static MA_INLINE void ma_pcm_s24_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36641. {
  36642. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  36643. }
  36644. #endif
  36645. #if defined(MA_SUPPORT_NEON)
  36646. static MA_INLINE void ma_pcm_s24_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36647. {
  36648. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  36649. }
  36650. #endif
  36651. MA_API void ma_pcm_s24_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36652. {
  36653. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36654. ma_pcm_s24_to_u8__reference(dst, src, count, ditherMode);
  36655. #else
  36656. # if defined(MA_SUPPORT_SSE2)
  36657. if (ma_has_sse2()) {
  36658. ma_pcm_s24_to_u8__sse2(dst, src, count, ditherMode);
  36659. } else
  36660. #elif defined(MA_SUPPORT_NEON)
  36661. if (ma_has_neon()) {
  36662. ma_pcm_s24_to_u8__neon(dst, src, count, ditherMode);
  36663. } else
  36664. #endif
  36665. {
  36666. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  36667. }
  36668. #endif
  36669. }
  36670. static MA_INLINE void ma_pcm_s24_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36671. {
  36672. ma_int16* dst_s16 = (ma_int16*)dst;
  36673. const ma_uint8* src_s24 = (const ma_uint8*)src;
  36674. if (ditherMode == ma_dither_mode_none) {
  36675. ma_uint64 i;
  36676. for (i = 0; i < count; i += 1) {
  36677. ma_uint16 dst_lo = ((ma_uint16)src_s24[i*3 + 1]);
  36678. ma_uint16 dst_hi = (ma_uint16)((ma_uint16)src_s24[i*3 + 2] << 8);
  36679. dst_s16[i] = (ma_int16)(dst_lo | dst_hi);
  36680. }
  36681. } else {
  36682. ma_uint64 i;
  36683. for (i = 0; i < count; i += 1) {
  36684. ma_int32 x = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24);
  36685. /* Dither. Don't overflow. */
  36686. ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF);
  36687. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  36688. x = x + dither;
  36689. } else {
  36690. x = 0x7FFFFFFF;
  36691. }
  36692. x = x >> 16;
  36693. dst_s16[i] = (ma_int16)x;
  36694. }
  36695. }
  36696. }
  36697. static MA_INLINE void ma_pcm_s24_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36698. {
  36699. ma_pcm_s24_to_s16__reference(dst, src, count, ditherMode);
  36700. }
  36701. #if defined(MA_SUPPORT_SSE2)
  36702. static MA_INLINE void ma_pcm_s24_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36703. {
  36704. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  36705. }
  36706. #endif
  36707. #if defined(MA_SUPPORT_NEON)
  36708. static MA_INLINE void ma_pcm_s24_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36709. {
  36710. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  36711. }
  36712. #endif
  36713. MA_API void ma_pcm_s24_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36714. {
  36715. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36716. ma_pcm_s24_to_s16__reference(dst, src, count, ditherMode);
  36717. #else
  36718. # if defined(MA_SUPPORT_SSE2)
  36719. if (ma_has_sse2()) {
  36720. ma_pcm_s24_to_s16__sse2(dst, src, count, ditherMode);
  36721. } else
  36722. #elif defined(MA_SUPPORT_NEON)
  36723. if (ma_has_neon()) {
  36724. ma_pcm_s24_to_s16__neon(dst, src, count, ditherMode);
  36725. } else
  36726. #endif
  36727. {
  36728. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  36729. }
  36730. #endif
  36731. }
  36732. MA_API void ma_pcm_s24_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36733. {
  36734. (void)ditherMode;
  36735. ma_copy_memory_64(dst, src, count * 3);
  36736. }
  36737. static MA_INLINE void ma_pcm_s24_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36738. {
  36739. ma_int32* dst_s32 = (ma_int32*)dst;
  36740. const ma_uint8* src_s24 = (const ma_uint8*)src;
  36741. ma_uint64 i;
  36742. for (i = 0; i < count; i += 1) {
  36743. dst_s32[i] = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24);
  36744. }
  36745. (void)ditherMode;
  36746. }
  36747. static MA_INLINE void ma_pcm_s24_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36748. {
  36749. ma_pcm_s24_to_s32__reference(dst, src, count, ditherMode);
  36750. }
  36751. #if defined(MA_SUPPORT_SSE2)
  36752. static MA_INLINE void ma_pcm_s24_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36753. {
  36754. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  36755. }
  36756. #endif
  36757. #if defined(MA_SUPPORT_NEON)
  36758. static MA_INLINE void ma_pcm_s24_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36759. {
  36760. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  36761. }
  36762. #endif
  36763. MA_API void ma_pcm_s24_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36764. {
  36765. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36766. ma_pcm_s24_to_s32__reference(dst, src, count, ditherMode);
  36767. #else
  36768. # if defined(MA_SUPPORT_SSE2)
  36769. if (ma_has_sse2()) {
  36770. ma_pcm_s24_to_s32__sse2(dst, src, count, ditherMode);
  36771. } else
  36772. #elif defined(MA_SUPPORT_NEON)
  36773. if (ma_has_neon()) {
  36774. ma_pcm_s24_to_s32__neon(dst, src, count, ditherMode);
  36775. } else
  36776. #endif
  36777. {
  36778. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  36779. }
  36780. #endif
  36781. }
  36782. static MA_INLINE void ma_pcm_s24_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36783. {
  36784. float* dst_f32 = (float*)dst;
  36785. const ma_uint8* src_s24 = (const ma_uint8*)src;
  36786. ma_uint64 i;
  36787. for (i = 0; i < count; i += 1) {
  36788. float x = (float)(((ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24)) >> 8);
  36789. #if 0
  36790. /* The accurate way. */
  36791. x = x + 8388608.0f; /* -8388608..8388607 to 0..16777215 */
  36792. x = x * 0.00000011920929665621f; /* 0..16777215 to 0..2 */
  36793. x = x - 1; /* 0..2 to -1..1 */
  36794. #else
  36795. /* The fast way. */
  36796. x = x * 0.00000011920928955078125f; /* -8388608..8388607 to -1..0.999969482421875 */
  36797. #endif
  36798. dst_f32[i] = x;
  36799. }
  36800. (void)ditherMode;
  36801. }
  36802. static MA_INLINE void ma_pcm_s24_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36803. {
  36804. ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode);
  36805. }
  36806. #if defined(MA_SUPPORT_SSE2)
  36807. static MA_INLINE void ma_pcm_s24_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36808. {
  36809. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  36810. }
  36811. #endif
  36812. #if defined(MA_SUPPORT_NEON)
  36813. static MA_INLINE void ma_pcm_s24_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36814. {
  36815. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  36816. }
  36817. #endif
  36818. MA_API void ma_pcm_s24_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36819. {
  36820. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36821. ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode);
  36822. #else
  36823. # if defined(MA_SUPPORT_SSE2)
  36824. if (ma_has_sse2()) {
  36825. ma_pcm_s24_to_f32__sse2(dst, src, count, ditherMode);
  36826. } else
  36827. #elif defined(MA_SUPPORT_NEON)
  36828. if (ma_has_neon()) {
  36829. ma_pcm_s24_to_f32__neon(dst, src, count, ditherMode);
  36830. } else
  36831. #endif
  36832. {
  36833. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  36834. }
  36835. #endif
  36836. }
  36837. static MA_INLINE void ma_pcm_interleave_s24__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36838. {
  36839. ma_uint8* dst8 = (ma_uint8*)dst;
  36840. const ma_uint8** src8 = (const ma_uint8**)src;
  36841. ma_uint64 iFrame;
  36842. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36843. ma_uint32 iChannel;
  36844. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36845. dst8[iFrame*3*channels + iChannel*3 + 0] = src8[iChannel][iFrame*3 + 0];
  36846. dst8[iFrame*3*channels + iChannel*3 + 1] = src8[iChannel][iFrame*3 + 1];
  36847. dst8[iFrame*3*channels + iChannel*3 + 2] = src8[iChannel][iFrame*3 + 2];
  36848. }
  36849. }
  36850. }
  36851. static MA_INLINE void ma_pcm_interleave_s24__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36852. {
  36853. ma_pcm_interleave_s24__reference(dst, src, frameCount, channels);
  36854. }
  36855. MA_API void ma_pcm_interleave_s24(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36856. {
  36857. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36858. ma_pcm_interleave_s24__reference(dst, src, frameCount, channels);
  36859. #else
  36860. ma_pcm_interleave_s24__optimized(dst, src, frameCount, channels);
  36861. #endif
  36862. }
  36863. static MA_INLINE void ma_pcm_deinterleave_s24__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36864. {
  36865. ma_uint8** dst8 = (ma_uint8**)dst;
  36866. const ma_uint8* src8 = (const ma_uint8*)src;
  36867. ma_uint32 iFrame;
  36868. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36869. ma_uint32 iChannel;
  36870. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36871. dst8[iChannel][iFrame*3 + 0] = src8[iFrame*3*channels + iChannel*3 + 0];
  36872. dst8[iChannel][iFrame*3 + 1] = src8[iFrame*3*channels + iChannel*3 + 1];
  36873. dst8[iChannel][iFrame*3 + 2] = src8[iFrame*3*channels + iChannel*3 + 2];
  36874. }
  36875. }
  36876. }
  36877. static MA_INLINE void ma_pcm_deinterleave_s24__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36878. {
  36879. ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels);
  36880. }
  36881. MA_API void ma_pcm_deinterleave_s24(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36882. {
  36883. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36884. ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels);
  36885. #else
  36886. ma_pcm_deinterleave_s24__optimized(dst, src, frameCount, channels);
  36887. #endif
  36888. }
  36889. /* s32 */
  36890. static MA_INLINE void ma_pcm_s32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36891. {
  36892. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36893. const ma_int32* src_s32 = (const ma_int32*)src;
  36894. if (ditherMode == ma_dither_mode_none) {
  36895. ma_uint64 i;
  36896. for (i = 0; i < count; i += 1) {
  36897. ma_int32 x = src_s32[i];
  36898. x = x >> 24;
  36899. x = x + 128;
  36900. dst_u8[i] = (ma_uint8)x;
  36901. }
  36902. } else {
  36903. ma_uint64 i;
  36904. for (i = 0; i < count; i += 1) {
  36905. ma_int32 x = src_s32[i];
  36906. /* Dither. Don't overflow. */
  36907. ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF);
  36908. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  36909. x = x + dither;
  36910. } else {
  36911. x = 0x7FFFFFFF;
  36912. }
  36913. x = x >> 24;
  36914. x = x + 128;
  36915. dst_u8[i] = (ma_uint8)x;
  36916. }
  36917. }
  36918. }
  36919. static MA_INLINE void ma_pcm_s32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36920. {
  36921. ma_pcm_s32_to_u8__reference(dst, src, count, ditherMode);
  36922. }
  36923. #if defined(MA_SUPPORT_SSE2)
  36924. static MA_INLINE void ma_pcm_s32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36925. {
  36926. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  36927. }
  36928. #endif
  36929. #if defined(MA_SUPPORT_NEON)
  36930. static MA_INLINE void ma_pcm_s32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36931. {
  36932. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  36933. }
  36934. #endif
  36935. MA_API void ma_pcm_s32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36936. {
  36937. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36938. ma_pcm_s32_to_u8__reference(dst, src, count, ditherMode);
  36939. #else
  36940. # if defined(MA_SUPPORT_SSE2)
  36941. if (ma_has_sse2()) {
  36942. ma_pcm_s32_to_u8__sse2(dst, src, count, ditherMode);
  36943. } else
  36944. #elif defined(MA_SUPPORT_NEON)
  36945. if (ma_has_neon()) {
  36946. ma_pcm_s32_to_u8__neon(dst, src, count, ditherMode);
  36947. } else
  36948. #endif
  36949. {
  36950. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  36951. }
  36952. #endif
  36953. }
  36954. static MA_INLINE void ma_pcm_s32_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36955. {
  36956. ma_int16* dst_s16 = (ma_int16*)dst;
  36957. const ma_int32* src_s32 = (const ma_int32*)src;
  36958. if (ditherMode == ma_dither_mode_none) {
  36959. ma_uint64 i;
  36960. for (i = 0; i < count; i += 1) {
  36961. ma_int32 x = src_s32[i];
  36962. x = x >> 16;
  36963. dst_s16[i] = (ma_int16)x;
  36964. }
  36965. } else {
  36966. ma_uint64 i;
  36967. for (i = 0; i < count; i += 1) {
  36968. ma_int32 x = src_s32[i];
  36969. /* Dither. Don't overflow. */
  36970. ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF);
  36971. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  36972. x = x + dither;
  36973. } else {
  36974. x = 0x7FFFFFFF;
  36975. }
  36976. x = x >> 16;
  36977. dst_s16[i] = (ma_int16)x;
  36978. }
  36979. }
  36980. }
  36981. static MA_INLINE void ma_pcm_s32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36982. {
  36983. ma_pcm_s32_to_s16__reference(dst, src, count, ditherMode);
  36984. }
  36985. #if defined(MA_SUPPORT_SSE2)
  36986. static MA_INLINE void ma_pcm_s32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36987. {
  36988. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  36989. }
  36990. #endif
  36991. #if defined(MA_SUPPORT_NEON)
  36992. static MA_INLINE void ma_pcm_s32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36993. {
  36994. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  36995. }
  36996. #endif
  36997. MA_API void ma_pcm_s32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36998. {
  36999. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37000. ma_pcm_s32_to_s16__reference(dst, src, count, ditherMode);
  37001. #else
  37002. # if defined(MA_SUPPORT_SSE2)
  37003. if (ma_has_sse2()) {
  37004. ma_pcm_s32_to_s16__sse2(dst, src, count, ditherMode);
  37005. } else
  37006. #elif defined(MA_SUPPORT_NEON)
  37007. if (ma_has_neon()) {
  37008. ma_pcm_s32_to_s16__neon(dst, src, count, ditherMode);
  37009. } else
  37010. #endif
  37011. {
  37012. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  37013. }
  37014. #endif
  37015. }
  37016. static MA_INLINE void ma_pcm_s32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37017. {
  37018. ma_uint8* dst_s24 = (ma_uint8*)dst;
  37019. const ma_int32* src_s32 = (const ma_int32*)src;
  37020. ma_uint64 i;
  37021. for (i = 0; i < count; i += 1) {
  37022. ma_uint32 x = (ma_uint32)src_s32[i];
  37023. dst_s24[i*3+0] = (ma_uint8)((x & 0x0000FF00) >> 8);
  37024. dst_s24[i*3+1] = (ma_uint8)((x & 0x00FF0000) >> 16);
  37025. dst_s24[i*3+2] = (ma_uint8)((x & 0xFF000000) >> 24);
  37026. }
  37027. (void)ditherMode; /* No dithering for s32 -> s24. */
  37028. }
  37029. static MA_INLINE void ma_pcm_s32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37030. {
  37031. ma_pcm_s32_to_s24__reference(dst, src, count, ditherMode);
  37032. }
  37033. #if defined(MA_SUPPORT_SSE2)
  37034. static MA_INLINE void ma_pcm_s32_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37035. {
  37036. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  37037. }
  37038. #endif
  37039. #if defined(MA_SUPPORT_NEON)
  37040. static MA_INLINE void ma_pcm_s32_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37041. {
  37042. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  37043. }
  37044. #endif
  37045. MA_API void ma_pcm_s32_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37046. {
  37047. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37048. ma_pcm_s32_to_s24__reference(dst, src, count, ditherMode);
  37049. #else
  37050. # if defined(MA_SUPPORT_SSE2)
  37051. if (ma_has_sse2()) {
  37052. ma_pcm_s32_to_s24__sse2(dst, src, count, ditherMode);
  37053. } else
  37054. #elif defined(MA_SUPPORT_NEON)
  37055. if (ma_has_neon()) {
  37056. ma_pcm_s32_to_s24__neon(dst, src, count, ditherMode);
  37057. } else
  37058. #endif
  37059. {
  37060. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  37061. }
  37062. #endif
  37063. }
  37064. MA_API void ma_pcm_s32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37065. {
  37066. (void)ditherMode;
  37067. ma_copy_memory_64(dst, src, count * sizeof(ma_int32));
  37068. }
  37069. static MA_INLINE void ma_pcm_s32_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37070. {
  37071. float* dst_f32 = (float*)dst;
  37072. const ma_int32* src_s32 = (const ma_int32*)src;
  37073. ma_uint64 i;
  37074. for (i = 0; i < count; i += 1) {
  37075. double x = src_s32[i];
  37076. #if 0
  37077. x = x + 2147483648.0;
  37078. x = x * 0.0000000004656612873077392578125;
  37079. x = x - 1;
  37080. #else
  37081. x = x / 2147483648.0;
  37082. #endif
  37083. dst_f32[i] = (float)x;
  37084. }
  37085. (void)ditherMode; /* No dithering for s32 -> f32. */
  37086. }
  37087. static MA_INLINE void ma_pcm_s32_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37088. {
  37089. ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode);
  37090. }
  37091. #if defined(MA_SUPPORT_SSE2)
  37092. static MA_INLINE void ma_pcm_s32_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37093. {
  37094. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  37095. }
  37096. #endif
  37097. #if defined(MA_SUPPORT_NEON)
  37098. static MA_INLINE void ma_pcm_s32_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37099. {
  37100. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  37101. }
  37102. #endif
  37103. MA_API void ma_pcm_s32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37104. {
  37105. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37106. ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode);
  37107. #else
  37108. # if defined(MA_SUPPORT_SSE2)
  37109. if (ma_has_sse2()) {
  37110. ma_pcm_s32_to_f32__sse2(dst, src, count, ditherMode);
  37111. } else
  37112. #elif defined(MA_SUPPORT_NEON)
  37113. if (ma_has_neon()) {
  37114. ma_pcm_s32_to_f32__neon(dst, src, count, ditherMode);
  37115. } else
  37116. #endif
  37117. {
  37118. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  37119. }
  37120. #endif
  37121. }
  37122. static MA_INLINE void ma_pcm_interleave_s32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37123. {
  37124. ma_int32* dst_s32 = (ma_int32*)dst;
  37125. const ma_int32** src_s32 = (const ma_int32**)src;
  37126. ma_uint64 iFrame;
  37127. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37128. ma_uint32 iChannel;
  37129. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  37130. dst_s32[iFrame*channels + iChannel] = src_s32[iChannel][iFrame];
  37131. }
  37132. }
  37133. }
  37134. static MA_INLINE void ma_pcm_interleave_s32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37135. {
  37136. ma_pcm_interleave_s32__reference(dst, src, frameCount, channels);
  37137. }
  37138. MA_API void ma_pcm_interleave_s32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37139. {
  37140. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37141. ma_pcm_interleave_s32__reference(dst, src, frameCount, channels);
  37142. #else
  37143. ma_pcm_interleave_s32__optimized(dst, src, frameCount, channels);
  37144. #endif
  37145. }
  37146. static MA_INLINE void ma_pcm_deinterleave_s32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37147. {
  37148. ma_int32** dst_s32 = (ma_int32**)dst;
  37149. const ma_int32* src_s32 = (const ma_int32*)src;
  37150. ma_uint64 iFrame;
  37151. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37152. ma_uint32 iChannel;
  37153. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  37154. dst_s32[iChannel][iFrame] = src_s32[iFrame*channels + iChannel];
  37155. }
  37156. }
  37157. }
  37158. static MA_INLINE void ma_pcm_deinterleave_s32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37159. {
  37160. ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels);
  37161. }
  37162. MA_API void ma_pcm_deinterleave_s32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37163. {
  37164. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37165. ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels);
  37166. #else
  37167. ma_pcm_deinterleave_s32__optimized(dst, src, frameCount, channels);
  37168. #endif
  37169. }
  37170. /* f32 */
  37171. static MA_INLINE void ma_pcm_f32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37172. {
  37173. ma_uint64 i;
  37174. ma_uint8* dst_u8 = (ma_uint8*)dst;
  37175. const float* src_f32 = (const float*)src;
  37176. float ditherMin = 0;
  37177. float ditherMax = 0;
  37178. if (ditherMode != ma_dither_mode_none) {
  37179. ditherMin = 1.0f / -128;
  37180. ditherMax = 1.0f / 127;
  37181. }
  37182. for (i = 0; i < count; i += 1) {
  37183. float x = src_f32[i];
  37184. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37185. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37186. x = x + 1; /* -1..1 to 0..2 */
  37187. x = x * 127.5f; /* 0..2 to 0..255 */
  37188. dst_u8[i] = (ma_uint8)x;
  37189. }
  37190. }
  37191. static MA_INLINE void ma_pcm_f32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37192. {
  37193. ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode);
  37194. }
  37195. #if defined(MA_SUPPORT_SSE2)
  37196. static MA_INLINE void ma_pcm_f32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37197. {
  37198. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  37199. }
  37200. #endif
  37201. #if defined(MA_SUPPORT_NEON)
  37202. static MA_INLINE void ma_pcm_f32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37203. {
  37204. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  37205. }
  37206. #endif
  37207. MA_API void ma_pcm_f32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37208. {
  37209. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37210. ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode);
  37211. #else
  37212. # if defined(MA_SUPPORT_SSE2)
  37213. if (ma_has_sse2()) {
  37214. ma_pcm_f32_to_u8__sse2(dst, src, count, ditherMode);
  37215. } else
  37216. #elif defined(MA_SUPPORT_NEON)
  37217. if (ma_has_neon()) {
  37218. ma_pcm_f32_to_u8__neon(dst, src, count, ditherMode);
  37219. } else
  37220. #endif
  37221. {
  37222. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  37223. }
  37224. #endif
  37225. }
  37226. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37227. static MA_INLINE void ma_pcm_f32_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37228. {
  37229. ma_uint64 i;
  37230. ma_int16* dst_s16 = (ma_int16*)dst;
  37231. const float* src_f32 = (const float*)src;
  37232. float ditherMin = 0;
  37233. float ditherMax = 0;
  37234. if (ditherMode != ma_dither_mode_none) {
  37235. ditherMin = 1.0f / -32768;
  37236. ditherMax = 1.0f / 32767;
  37237. }
  37238. for (i = 0; i < count; i += 1) {
  37239. float x = src_f32[i];
  37240. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37241. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37242. #if 0
  37243. /* The accurate way. */
  37244. x = x + 1; /* -1..1 to 0..2 */
  37245. x = x * 32767.5f; /* 0..2 to 0..65535 */
  37246. x = x - 32768.0f; /* 0...65535 to -32768..32767 */
  37247. #else
  37248. /* The fast way. */
  37249. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  37250. #endif
  37251. dst_s16[i] = (ma_int16)x;
  37252. }
  37253. }
  37254. #else
  37255. static MA_INLINE void ma_pcm_f32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37256. {
  37257. ma_uint64 i;
  37258. ma_uint64 i4;
  37259. ma_uint64 count4;
  37260. ma_int16* dst_s16 = (ma_int16*)dst;
  37261. const float* src_f32 = (const float*)src;
  37262. float ditherMin = 0;
  37263. float ditherMax = 0;
  37264. if (ditherMode != ma_dither_mode_none) {
  37265. ditherMin = 1.0f / -32768;
  37266. ditherMax = 1.0f / 32767;
  37267. }
  37268. /* Unrolled. */
  37269. i = 0;
  37270. count4 = count >> 2;
  37271. for (i4 = 0; i4 < count4; i4 += 1) {
  37272. float d0 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37273. float d1 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37274. float d2 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37275. float d3 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37276. float x0 = src_f32[i+0];
  37277. float x1 = src_f32[i+1];
  37278. float x2 = src_f32[i+2];
  37279. float x3 = src_f32[i+3];
  37280. x0 = x0 + d0;
  37281. x1 = x1 + d1;
  37282. x2 = x2 + d2;
  37283. x3 = x3 + d3;
  37284. x0 = ((x0 < -1) ? -1 : ((x0 > 1) ? 1 : x0));
  37285. x1 = ((x1 < -1) ? -1 : ((x1 > 1) ? 1 : x1));
  37286. x2 = ((x2 < -1) ? -1 : ((x2 > 1) ? 1 : x2));
  37287. x3 = ((x3 < -1) ? -1 : ((x3 > 1) ? 1 : x3));
  37288. x0 = x0 * 32767.0f;
  37289. x1 = x1 * 32767.0f;
  37290. x2 = x2 * 32767.0f;
  37291. x3 = x3 * 32767.0f;
  37292. dst_s16[i+0] = (ma_int16)x0;
  37293. dst_s16[i+1] = (ma_int16)x1;
  37294. dst_s16[i+2] = (ma_int16)x2;
  37295. dst_s16[i+3] = (ma_int16)x3;
  37296. i += 4;
  37297. }
  37298. /* Leftover. */
  37299. for (; i < count; i += 1) {
  37300. float x = src_f32[i];
  37301. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37302. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37303. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  37304. dst_s16[i] = (ma_int16)x;
  37305. }
  37306. }
  37307. #if defined(MA_SUPPORT_SSE2)
  37308. static MA_INLINE void ma_pcm_f32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37309. {
  37310. ma_uint64 i;
  37311. ma_uint64 i8;
  37312. ma_uint64 count8;
  37313. ma_int16* dst_s16;
  37314. const float* src_f32;
  37315. float ditherMin;
  37316. float ditherMax;
  37317. /* Both the input and output buffers need to be aligned to 16 bytes. */
  37318. if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) {
  37319. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  37320. return;
  37321. }
  37322. dst_s16 = (ma_int16*)dst;
  37323. src_f32 = (const float*)src;
  37324. ditherMin = 0;
  37325. ditherMax = 0;
  37326. if (ditherMode != ma_dither_mode_none) {
  37327. ditherMin = 1.0f / -32768;
  37328. ditherMax = 1.0f / 32767;
  37329. }
  37330. i = 0;
  37331. /* SSE2. SSE allows us to output 8 s16's at a time which means our loop is unrolled 8 times. */
  37332. count8 = count >> 3;
  37333. for (i8 = 0; i8 < count8; i8 += 1) {
  37334. __m128 d0;
  37335. __m128 d1;
  37336. __m128 x0;
  37337. __m128 x1;
  37338. if (ditherMode == ma_dither_mode_none) {
  37339. d0 = _mm_set1_ps(0);
  37340. d1 = _mm_set1_ps(0);
  37341. } else if (ditherMode == ma_dither_mode_rectangle) {
  37342. d0 = _mm_set_ps(
  37343. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37344. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37345. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37346. ma_dither_f32_rectangle(ditherMin, ditherMax)
  37347. );
  37348. d1 = _mm_set_ps(
  37349. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37350. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37351. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37352. ma_dither_f32_rectangle(ditherMin, ditherMax)
  37353. );
  37354. } else {
  37355. d0 = _mm_set_ps(
  37356. ma_dither_f32_triangle(ditherMin, ditherMax),
  37357. ma_dither_f32_triangle(ditherMin, ditherMax),
  37358. ma_dither_f32_triangle(ditherMin, ditherMax),
  37359. ma_dither_f32_triangle(ditherMin, ditherMax)
  37360. );
  37361. d1 = _mm_set_ps(
  37362. ma_dither_f32_triangle(ditherMin, ditherMax),
  37363. ma_dither_f32_triangle(ditherMin, ditherMax),
  37364. ma_dither_f32_triangle(ditherMin, ditherMax),
  37365. ma_dither_f32_triangle(ditherMin, ditherMax)
  37366. );
  37367. }
  37368. x0 = *((__m128*)(src_f32 + i) + 0);
  37369. x1 = *((__m128*)(src_f32 + i) + 1);
  37370. x0 = _mm_add_ps(x0, d0);
  37371. x1 = _mm_add_ps(x1, d1);
  37372. x0 = _mm_mul_ps(x0, _mm_set1_ps(32767.0f));
  37373. x1 = _mm_mul_ps(x1, _mm_set1_ps(32767.0f));
  37374. _mm_stream_si128(((__m128i*)(dst_s16 + i)), _mm_packs_epi32(_mm_cvttps_epi32(x0), _mm_cvttps_epi32(x1)));
  37375. i += 8;
  37376. }
  37377. /* Leftover. */
  37378. for (; i < count; i += 1) {
  37379. float x = src_f32[i];
  37380. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37381. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37382. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  37383. dst_s16[i] = (ma_int16)x;
  37384. }
  37385. }
  37386. #endif /* SSE2 */
  37387. #if defined(MA_SUPPORT_NEON)
  37388. static MA_INLINE void ma_pcm_f32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37389. {
  37390. ma_uint64 i;
  37391. ma_uint64 i8;
  37392. ma_uint64 count8;
  37393. ma_int16* dst_s16;
  37394. const float* src_f32;
  37395. float ditherMin;
  37396. float ditherMax;
  37397. if (!ma_has_neon()) {
  37398. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  37399. return;
  37400. }
  37401. /* Both the input and output buffers need to be aligned to 16 bytes. */
  37402. if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) {
  37403. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  37404. return;
  37405. }
  37406. dst_s16 = (ma_int16*)dst;
  37407. src_f32 = (const float*)src;
  37408. ditherMin = 0;
  37409. ditherMax = 0;
  37410. if (ditherMode != ma_dither_mode_none) {
  37411. ditherMin = 1.0f / -32768;
  37412. ditherMax = 1.0f / 32767;
  37413. }
  37414. i = 0;
  37415. /* NEON. NEON allows us to output 8 s16's at a time which means our loop is unrolled 8 times. */
  37416. count8 = count >> 3;
  37417. for (i8 = 0; i8 < count8; i8 += 1) {
  37418. float32x4_t d0;
  37419. float32x4_t d1;
  37420. float32x4_t x0;
  37421. float32x4_t x1;
  37422. int32x4_t i0;
  37423. int32x4_t i1;
  37424. if (ditherMode == ma_dither_mode_none) {
  37425. d0 = vmovq_n_f32(0);
  37426. d1 = vmovq_n_f32(0);
  37427. } else if (ditherMode == ma_dither_mode_rectangle) {
  37428. float d0v[4];
  37429. d0v[0] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37430. d0v[1] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37431. d0v[2] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37432. d0v[3] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37433. d0 = vld1q_f32(d0v);
  37434. float d1v[4];
  37435. d1v[0] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37436. d1v[1] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37437. d1v[2] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37438. d1v[3] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37439. d1 = vld1q_f32(d1v);
  37440. } else {
  37441. float d0v[4];
  37442. d0v[0] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37443. d0v[1] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37444. d0v[2] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37445. d0v[3] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37446. d0 = vld1q_f32(d0v);
  37447. float d1v[4];
  37448. d1v[0] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37449. d1v[1] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37450. d1v[2] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37451. d1v[3] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37452. d1 = vld1q_f32(d1v);
  37453. }
  37454. x0 = *((float32x4_t*)(src_f32 + i) + 0);
  37455. x1 = *((float32x4_t*)(src_f32 + i) + 1);
  37456. x0 = vaddq_f32(x0, d0);
  37457. x1 = vaddq_f32(x1, d1);
  37458. x0 = vmulq_n_f32(x0, 32767.0f);
  37459. x1 = vmulq_n_f32(x1, 32767.0f);
  37460. i0 = vcvtq_s32_f32(x0);
  37461. i1 = vcvtq_s32_f32(x1);
  37462. *((int16x8_t*)(dst_s16 + i)) = vcombine_s16(vqmovn_s32(i0), vqmovn_s32(i1));
  37463. i += 8;
  37464. }
  37465. /* Leftover. */
  37466. for (; i < count; i += 1) {
  37467. float x = src_f32[i];
  37468. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37469. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37470. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  37471. dst_s16[i] = (ma_int16)x;
  37472. }
  37473. }
  37474. #endif /* Neon */
  37475. #endif /* MA_USE_REFERENCE_CONVERSION_APIS */
  37476. MA_API void ma_pcm_f32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37477. {
  37478. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37479. ma_pcm_f32_to_s16__reference(dst, src, count, ditherMode);
  37480. #else
  37481. # if defined(MA_SUPPORT_SSE2)
  37482. if (ma_has_sse2()) {
  37483. ma_pcm_f32_to_s16__sse2(dst, src, count, ditherMode);
  37484. } else
  37485. #elif defined(MA_SUPPORT_NEON)
  37486. if (ma_has_neon()) {
  37487. ma_pcm_f32_to_s16__neon(dst, src, count, ditherMode);
  37488. } else
  37489. #endif
  37490. {
  37491. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  37492. }
  37493. #endif
  37494. }
  37495. static MA_INLINE void ma_pcm_f32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37496. {
  37497. ma_uint8* dst_s24 = (ma_uint8*)dst;
  37498. const float* src_f32 = (const float*)src;
  37499. ma_uint64 i;
  37500. for (i = 0; i < count; i += 1) {
  37501. ma_int32 r;
  37502. float x = src_f32[i];
  37503. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37504. #if 0
  37505. /* The accurate way. */
  37506. x = x + 1; /* -1..1 to 0..2 */
  37507. x = x * 8388607.5f; /* 0..2 to 0..16777215 */
  37508. x = x - 8388608.0f; /* 0..16777215 to -8388608..8388607 */
  37509. #else
  37510. /* The fast way. */
  37511. x = x * 8388607.0f; /* -1..1 to -8388607..8388607 */
  37512. #endif
  37513. r = (ma_int32)x;
  37514. dst_s24[(i*3)+0] = (ma_uint8)((r & 0x0000FF) >> 0);
  37515. dst_s24[(i*3)+1] = (ma_uint8)((r & 0x00FF00) >> 8);
  37516. dst_s24[(i*3)+2] = (ma_uint8)((r & 0xFF0000) >> 16);
  37517. }
  37518. (void)ditherMode; /* No dithering for f32 -> s24. */
  37519. }
  37520. static MA_INLINE void ma_pcm_f32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37521. {
  37522. ma_pcm_f32_to_s24__reference(dst, src, count, ditherMode);
  37523. }
  37524. #if defined(MA_SUPPORT_SSE2)
  37525. static MA_INLINE void ma_pcm_f32_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37526. {
  37527. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  37528. }
  37529. #endif
  37530. #if defined(MA_SUPPORT_NEON)
  37531. static MA_INLINE void ma_pcm_f32_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37532. {
  37533. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  37534. }
  37535. #endif
  37536. MA_API void ma_pcm_f32_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37537. {
  37538. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37539. ma_pcm_f32_to_s24__reference(dst, src, count, ditherMode);
  37540. #else
  37541. # if defined(MA_SUPPORT_SSE2)
  37542. if (ma_has_sse2()) {
  37543. ma_pcm_f32_to_s24__sse2(dst, src, count, ditherMode);
  37544. } else
  37545. #elif defined(MA_SUPPORT_NEON)
  37546. if (ma_has_neon()) {
  37547. ma_pcm_f32_to_s24__neon(dst, src, count, ditherMode);
  37548. } else
  37549. #endif
  37550. {
  37551. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  37552. }
  37553. #endif
  37554. }
  37555. static MA_INLINE void ma_pcm_f32_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37556. {
  37557. ma_int32* dst_s32 = (ma_int32*)dst;
  37558. const float* src_f32 = (const float*)src;
  37559. ma_uint32 i;
  37560. for (i = 0; i < count; i += 1) {
  37561. double x = src_f32[i];
  37562. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37563. #if 0
  37564. /* The accurate way. */
  37565. x = x + 1; /* -1..1 to 0..2 */
  37566. x = x * 2147483647.5; /* 0..2 to 0..4294967295 */
  37567. x = x - 2147483648.0; /* 0...4294967295 to -2147483648..2147483647 */
  37568. #else
  37569. /* The fast way. */
  37570. x = x * 2147483647.0; /* -1..1 to -2147483647..2147483647 */
  37571. #endif
  37572. dst_s32[i] = (ma_int32)x;
  37573. }
  37574. (void)ditherMode; /* No dithering for f32 -> s32. */
  37575. }
  37576. static MA_INLINE void ma_pcm_f32_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37577. {
  37578. ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode);
  37579. }
  37580. #if defined(MA_SUPPORT_SSE2)
  37581. static MA_INLINE void ma_pcm_f32_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37582. {
  37583. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  37584. }
  37585. #endif
  37586. #if defined(MA_SUPPORT_NEON)
  37587. static MA_INLINE void ma_pcm_f32_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37588. {
  37589. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  37590. }
  37591. #endif
  37592. MA_API void ma_pcm_f32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37593. {
  37594. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37595. ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode);
  37596. #else
  37597. # if defined(MA_SUPPORT_SSE2)
  37598. if (ma_has_sse2()) {
  37599. ma_pcm_f32_to_s32__sse2(dst, src, count, ditherMode);
  37600. } else
  37601. #elif defined(MA_SUPPORT_NEON)
  37602. if (ma_has_neon()) {
  37603. ma_pcm_f32_to_s32__neon(dst, src, count, ditherMode);
  37604. } else
  37605. #endif
  37606. {
  37607. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  37608. }
  37609. #endif
  37610. }
  37611. MA_API void ma_pcm_f32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37612. {
  37613. (void)ditherMode;
  37614. ma_copy_memory_64(dst, src, count * sizeof(float));
  37615. }
  37616. static void ma_pcm_interleave_f32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37617. {
  37618. float* dst_f32 = (float*)dst;
  37619. const float** src_f32 = (const float**)src;
  37620. ma_uint64 iFrame;
  37621. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37622. ma_uint32 iChannel;
  37623. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  37624. dst_f32[iFrame*channels + iChannel] = src_f32[iChannel][iFrame];
  37625. }
  37626. }
  37627. }
  37628. static void ma_pcm_interleave_f32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37629. {
  37630. ma_pcm_interleave_f32__reference(dst, src, frameCount, channels);
  37631. }
  37632. MA_API void ma_pcm_interleave_f32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37633. {
  37634. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37635. ma_pcm_interleave_f32__reference(dst, src, frameCount, channels);
  37636. #else
  37637. ma_pcm_interleave_f32__optimized(dst, src, frameCount, channels);
  37638. #endif
  37639. }
  37640. static void ma_pcm_deinterleave_f32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37641. {
  37642. float** dst_f32 = (float**)dst;
  37643. const float* src_f32 = (const float*)src;
  37644. ma_uint64 iFrame;
  37645. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37646. ma_uint32 iChannel;
  37647. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  37648. dst_f32[iChannel][iFrame] = src_f32[iFrame*channels + iChannel];
  37649. }
  37650. }
  37651. }
  37652. static void ma_pcm_deinterleave_f32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37653. {
  37654. ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels);
  37655. }
  37656. MA_API void ma_pcm_deinterleave_f32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37657. {
  37658. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37659. ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels);
  37660. #else
  37661. ma_pcm_deinterleave_f32__optimized(dst, src, frameCount, channels);
  37662. #endif
  37663. }
  37664. MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode)
  37665. {
  37666. if (formatOut == formatIn) {
  37667. ma_copy_memory_64(pOut, pIn, sampleCount * ma_get_bytes_per_sample(formatOut));
  37668. return;
  37669. }
  37670. switch (formatIn)
  37671. {
  37672. case ma_format_u8:
  37673. {
  37674. switch (formatOut)
  37675. {
  37676. case ma_format_s16: ma_pcm_u8_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  37677. case ma_format_s24: ma_pcm_u8_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  37678. case ma_format_s32: ma_pcm_u8_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  37679. case ma_format_f32: ma_pcm_u8_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  37680. default: break;
  37681. }
  37682. } break;
  37683. case ma_format_s16:
  37684. {
  37685. switch (formatOut)
  37686. {
  37687. case ma_format_u8: ma_pcm_s16_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  37688. case ma_format_s24: ma_pcm_s16_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  37689. case ma_format_s32: ma_pcm_s16_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  37690. case ma_format_f32: ma_pcm_s16_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  37691. default: break;
  37692. }
  37693. } break;
  37694. case ma_format_s24:
  37695. {
  37696. switch (formatOut)
  37697. {
  37698. case ma_format_u8: ma_pcm_s24_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  37699. case ma_format_s16: ma_pcm_s24_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  37700. case ma_format_s32: ma_pcm_s24_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  37701. case ma_format_f32: ma_pcm_s24_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  37702. default: break;
  37703. }
  37704. } break;
  37705. case ma_format_s32:
  37706. {
  37707. switch (formatOut)
  37708. {
  37709. case ma_format_u8: ma_pcm_s32_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  37710. case ma_format_s16: ma_pcm_s32_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  37711. case ma_format_s24: ma_pcm_s32_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  37712. case ma_format_f32: ma_pcm_s32_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  37713. default: break;
  37714. }
  37715. } break;
  37716. case ma_format_f32:
  37717. {
  37718. switch (formatOut)
  37719. {
  37720. case ma_format_u8: ma_pcm_f32_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  37721. case ma_format_s16: ma_pcm_f32_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  37722. case ma_format_s24: ma_pcm_f32_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  37723. case ma_format_s32: ma_pcm_f32_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  37724. default: break;
  37725. }
  37726. } break;
  37727. default: break;
  37728. }
  37729. }
  37730. MA_API void ma_convert_pcm_frames_format(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 frameCount, ma_uint32 channels, ma_dither_mode ditherMode)
  37731. {
  37732. ma_pcm_convert(pOut, formatOut, pIn, formatIn, frameCount * channels, ditherMode);
  37733. }
  37734. MA_API void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames)
  37735. {
  37736. if (pInterleavedPCMFrames == NULL || ppDeinterleavedPCMFrames == NULL) {
  37737. return; /* Invalid args. */
  37738. }
  37739. /* For efficiency we do this per format. */
  37740. switch (format) {
  37741. case ma_format_s16:
  37742. {
  37743. const ma_int16* pSrcS16 = (const ma_int16*)pInterleavedPCMFrames;
  37744. ma_uint64 iPCMFrame;
  37745. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37746. ma_uint32 iChannel;
  37747. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37748. ma_int16* pDstS16 = (ma_int16*)ppDeinterleavedPCMFrames[iChannel];
  37749. pDstS16[iPCMFrame] = pSrcS16[iPCMFrame*channels+iChannel];
  37750. }
  37751. }
  37752. } break;
  37753. case ma_format_f32:
  37754. {
  37755. const float* pSrcF32 = (const float*)pInterleavedPCMFrames;
  37756. ma_uint64 iPCMFrame;
  37757. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37758. ma_uint32 iChannel;
  37759. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37760. float* pDstF32 = (float*)ppDeinterleavedPCMFrames[iChannel];
  37761. pDstF32[iPCMFrame] = pSrcF32[iPCMFrame*channels+iChannel];
  37762. }
  37763. }
  37764. } break;
  37765. default:
  37766. {
  37767. ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format);
  37768. ma_uint64 iPCMFrame;
  37769. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37770. ma_uint32 iChannel;
  37771. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37772. void* pDst = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes);
  37773. const void* pSrc = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes);
  37774. memcpy(pDst, pSrc, sampleSizeInBytes);
  37775. }
  37776. }
  37777. } break;
  37778. }
  37779. }
  37780. MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames)
  37781. {
  37782. switch (format)
  37783. {
  37784. case ma_format_s16:
  37785. {
  37786. ma_int16* pDstS16 = (ma_int16*)pInterleavedPCMFrames;
  37787. ma_uint64 iPCMFrame;
  37788. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37789. ma_uint32 iChannel;
  37790. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37791. const ma_int16* pSrcS16 = (const ma_int16*)ppDeinterleavedPCMFrames[iChannel];
  37792. pDstS16[iPCMFrame*channels+iChannel] = pSrcS16[iPCMFrame];
  37793. }
  37794. }
  37795. } break;
  37796. case ma_format_f32:
  37797. {
  37798. float* pDstF32 = (float*)pInterleavedPCMFrames;
  37799. ma_uint64 iPCMFrame;
  37800. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37801. ma_uint32 iChannel;
  37802. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37803. const float* pSrcF32 = (const float*)ppDeinterleavedPCMFrames[iChannel];
  37804. pDstF32[iPCMFrame*channels+iChannel] = pSrcF32[iPCMFrame];
  37805. }
  37806. }
  37807. } break;
  37808. default:
  37809. {
  37810. ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format);
  37811. ma_uint64 iPCMFrame;
  37812. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37813. ma_uint32 iChannel;
  37814. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37815. void* pDst = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes);
  37816. const void* pSrc = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes);
  37817. memcpy(pDst, pSrc, sampleSizeInBytes);
  37818. }
  37819. }
  37820. } break;
  37821. }
  37822. }
  37823. /**************************************************************************************************************************************************************
  37824. Biquad Filter
  37825. **************************************************************************************************************************************************************/
  37826. #ifndef MA_BIQUAD_FIXED_POINT_SHIFT
  37827. #define MA_BIQUAD_FIXED_POINT_SHIFT 14
  37828. #endif
  37829. static ma_int32 ma_biquad_float_to_fp(double x)
  37830. {
  37831. return (ma_int32)(x * (1 << MA_BIQUAD_FIXED_POINT_SHIFT));
  37832. }
  37833. MA_API ma_biquad_config ma_biquad_config_init(ma_format format, ma_uint32 channels, double b0, double b1, double b2, double a0, double a1, double a2)
  37834. {
  37835. ma_biquad_config config;
  37836. MA_ZERO_OBJECT(&config);
  37837. config.format = format;
  37838. config.channels = channels;
  37839. config.b0 = b0;
  37840. config.b1 = b1;
  37841. config.b2 = b2;
  37842. config.a0 = a0;
  37843. config.a1 = a1;
  37844. config.a2 = a2;
  37845. return config;
  37846. }
  37847. typedef struct
  37848. {
  37849. size_t sizeInBytes;
  37850. size_t r1Offset;
  37851. size_t r2Offset;
  37852. } ma_biquad_heap_layout;
  37853. static ma_result ma_biquad_get_heap_layout(const ma_biquad_config* pConfig, ma_biquad_heap_layout* pHeapLayout)
  37854. {
  37855. MA_ASSERT(pHeapLayout != NULL);
  37856. MA_ZERO_OBJECT(pHeapLayout);
  37857. if (pConfig == NULL) {
  37858. return MA_INVALID_ARGS;
  37859. }
  37860. if (pConfig->channels == 0) {
  37861. return MA_INVALID_ARGS;
  37862. }
  37863. pHeapLayout->sizeInBytes = 0;
  37864. /* R0 */
  37865. pHeapLayout->r1Offset = pHeapLayout->sizeInBytes;
  37866. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  37867. /* R1 */
  37868. pHeapLayout->r2Offset = pHeapLayout->sizeInBytes;
  37869. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  37870. /* Make sure allocation size is aligned. */
  37871. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  37872. return MA_SUCCESS;
  37873. }
  37874. MA_API ma_result ma_biquad_get_heap_size(const ma_biquad_config* pConfig, size_t* pHeapSizeInBytes)
  37875. {
  37876. ma_result result;
  37877. ma_biquad_heap_layout heapLayout;
  37878. if (pHeapSizeInBytes == NULL) {
  37879. return MA_INVALID_ARGS;
  37880. }
  37881. *pHeapSizeInBytes = 0;
  37882. result = ma_biquad_get_heap_layout(pConfig, &heapLayout);
  37883. if (result != MA_SUCCESS) {
  37884. return result;
  37885. }
  37886. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  37887. return MA_SUCCESS;
  37888. }
  37889. MA_API ma_result ma_biquad_init_preallocated(const ma_biquad_config* pConfig, void* pHeap, ma_biquad* pBQ)
  37890. {
  37891. ma_result result;
  37892. ma_biquad_heap_layout heapLayout;
  37893. if (pBQ == NULL) {
  37894. return MA_INVALID_ARGS;
  37895. }
  37896. MA_ZERO_OBJECT(pBQ);
  37897. result = ma_biquad_get_heap_layout(pConfig, &heapLayout);
  37898. if (result != MA_SUCCESS) {
  37899. return result;
  37900. }
  37901. pBQ->_pHeap = pHeap;
  37902. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  37903. pBQ->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset);
  37904. pBQ->pR2 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r2Offset);
  37905. return ma_biquad_reinit(pConfig, pBQ);
  37906. }
  37907. MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad* pBQ)
  37908. {
  37909. ma_result result;
  37910. size_t heapSizeInBytes;
  37911. void* pHeap;
  37912. result = ma_biquad_get_heap_size(pConfig, &heapSizeInBytes);
  37913. if (result != MA_SUCCESS) {
  37914. return result;
  37915. }
  37916. if (heapSizeInBytes > 0) {
  37917. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  37918. if (pHeap == NULL) {
  37919. return MA_OUT_OF_MEMORY;
  37920. }
  37921. } else {
  37922. pHeap = NULL;
  37923. }
  37924. result = ma_biquad_init_preallocated(pConfig, pHeap, pBQ);
  37925. if (result != MA_SUCCESS) {
  37926. ma_free(pHeap, pAllocationCallbacks);
  37927. return result;
  37928. }
  37929. pBQ->_ownsHeap = MA_TRUE;
  37930. return MA_SUCCESS;
  37931. }
  37932. MA_API void ma_biquad_uninit(ma_biquad* pBQ, const ma_allocation_callbacks* pAllocationCallbacks)
  37933. {
  37934. if (pBQ == NULL) {
  37935. return;
  37936. }
  37937. if (pBQ->_ownsHeap) {
  37938. ma_free(pBQ->_pHeap, pAllocationCallbacks);
  37939. }
  37940. }
  37941. MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ)
  37942. {
  37943. if (pBQ == NULL || pConfig == NULL) {
  37944. return MA_INVALID_ARGS;
  37945. }
  37946. if (pConfig->a0 == 0) {
  37947. return MA_INVALID_ARGS; /* Division by zero. */
  37948. }
  37949. /* Only supporting f32 and s16. */
  37950. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  37951. return MA_INVALID_ARGS;
  37952. }
  37953. /* The format cannot be changed after initialization. */
  37954. if (pBQ->format != ma_format_unknown && pBQ->format != pConfig->format) {
  37955. return MA_INVALID_OPERATION;
  37956. }
  37957. /* The channel count cannot be changed after initialization. */
  37958. if (pBQ->channels != 0 && pBQ->channels != pConfig->channels) {
  37959. return MA_INVALID_OPERATION;
  37960. }
  37961. pBQ->format = pConfig->format;
  37962. pBQ->channels = pConfig->channels;
  37963. /* Normalize. */
  37964. if (pConfig->format == ma_format_f32) {
  37965. pBQ->b0.f32 = (float)(pConfig->b0 / pConfig->a0);
  37966. pBQ->b1.f32 = (float)(pConfig->b1 / pConfig->a0);
  37967. pBQ->b2.f32 = (float)(pConfig->b2 / pConfig->a0);
  37968. pBQ->a1.f32 = (float)(pConfig->a1 / pConfig->a0);
  37969. pBQ->a2.f32 = (float)(pConfig->a2 / pConfig->a0);
  37970. } else {
  37971. pBQ->b0.s32 = ma_biquad_float_to_fp(pConfig->b0 / pConfig->a0);
  37972. pBQ->b1.s32 = ma_biquad_float_to_fp(pConfig->b1 / pConfig->a0);
  37973. pBQ->b2.s32 = ma_biquad_float_to_fp(pConfig->b2 / pConfig->a0);
  37974. pBQ->a1.s32 = ma_biquad_float_to_fp(pConfig->a1 / pConfig->a0);
  37975. pBQ->a2.s32 = ma_biquad_float_to_fp(pConfig->a2 / pConfig->a0);
  37976. }
  37977. return MA_SUCCESS;
  37978. }
  37979. MA_API ma_result ma_biquad_clear_cache(ma_biquad* pBQ)
  37980. {
  37981. if (pBQ == NULL) {
  37982. return MA_INVALID_ARGS;
  37983. }
  37984. if (pBQ->format == ma_format_f32) {
  37985. pBQ->pR1->f32 = 0;
  37986. pBQ->pR2->f32 = 0;
  37987. } else {
  37988. pBQ->pR1->s32 = 0;
  37989. pBQ->pR2->s32 = 0;
  37990. }
  37991. return MA_SUCCESS;
  37992. }
  37993. static MA_INLINE void ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(ma_biquad* pBQ, float* pY, const float* pX)
  37994. {
  37995. ma_uint32 c;
  37996. const ma_uint32 channels = pBQ->channels;
  37997. const float b0 = pBQ->b0.f32;
  37998. const float b1 = pBQ->b1.f32;
  37999. const float b2 = pBQ->b2.f32;
  38000. const float a1 = pBQ->a1.f32;
  38001. const float a2 = pBQ->a2.f32;
  38002. MA_ASSUME(channels > 0);
  38003. for (c = 0; c < channels; c += 1) {
  38004. float r1 = pBQ->pR1[c].f32;
  38005. float r2 = pBQ->pR2[c].f32;
  38006. float x = pX[c];
  38007. float y;
  38008. y = b0*x + r1;
  38009. r1 = b1*x - a1*y + r2;
  38010. r2 = b2*x - a2*y;
  38011. pY[c] = y;
  38012. pBQ->pR1[c].f32 = r1;
  38013. pBQ->pR2[c].f32 = r2;
  38014. }
  38015. }
  38016. static MA_INLINE void ma_biquad_process_pcm_frame_f32(ma_biquad* pBQ, float* pY, const float* pX)
  38017. {
  38018. ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX);
  38019. }
  38020. static MA_INLINE void ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX)
  38021. {
  38022. ma_uint32 c;
  38023. const ma_uint32 channels = pBQ->channels;
  38024. const ma_int32 b0 = pBQ->b0.s32;
  38025. const ma_int32 b1 = pBQ->b1.s32;
  38026. const ma_int32 b2 = pBQ->b2.s32;
  38027. const ma_int32 a1 = pBQ->a1.s32;
  38028. const ma_int32 a2 = pBQ->a2.s32;
  38029. MA_ASSUME(channels > 0);
  38030. for (c = 0; c < channels; c += 1) {
  38031. ma_int32 r1 = pBQ->pR1[c].s32;
  38032. ma_int32 r2 = pBQ->pR2[c].s32;
  38033. ma_int32 x = pX[c];
  38034. ma_int32 y;
  38035. y = (b0*x + r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
  38036. r1 = (b1*x - a1*y + r2);
  38037. r2 = (b2*x - a2*y);
  38038. pY[c] = (ma_int16)ma_clamp(y, -32768, 32767);
  38039. pBQ->pR1[c].s32 = r1;
  38040. pBQ->pR2[c].s32 = r2;
  38041. }
  38042. }
  38043. static MA_INLINE void ma_biquad_process_pcm_frame_s16(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX)
  38044. {
  38045. ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX);
  38046. }
  38047. MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38048. {
  38049. ma_uint32 n;
  38050. if (pBQ == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  38051. return MA_INVALID_ARGS;
  38052. }
  38053. /* Note that the logic below needs to support in-place filtering. That is, it must support the case where pFramesOut and pFramesIn are the same. */
  38054. if (pBQ->format == ma_format_f32) {
  38055. /* */ float* pY = ( float*)pFramesOut;
  38056. const float* pX = (const float*)pFramesIn;
  38057. for (n = 0; n < frameCount; n += 1) {
  38058. ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX);
  38059. pY += pBQ->channels;
  38060. pX += pBQ->channels;
  38061. }
  38062. } else if (pBQ->format == ma_format_s16) {
  38063. /* */ ma_int16* pY = ( ma_int16*)pFramesOut;
  38064. const ma_int16* pX = (const ma_int16*)pFramesIn;
  38065. for (n = 0; n < frameCount; n += 1) {
  38066. ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX);
  38067. pY += pBQ->channels;
  38068. pX += pBQ->channels;
  38069. }
  38070. } else {
  38071. MA_ASSERT(MA_FALSE);
  38072. return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
  38073. }
  38074. return MA_SUCCESS;
  38075. }
  38076. MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ)
  38077. {
  38078. if (pBQ == NULL) {
  38079. return 0;
  38080. }
  38081. return 2;
  38082. }
  38083. /**************************************************************************************************************************************************************
  38084. Low-Pass Filter
  38085. **************************************************************************************************************************************************************/
  38086. MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency)
  38087. {
  38088. ma_lpf1_config config;
  38089. MA_ZERO_OBJECT(&config);
  38090. config.format = format;
  38091. config.channels = channels;
  38092. config.sampleRate = sampleRate;
  38093. config.cutoffFrequency = cutoffFrequency;
  38094. config.q = 0.5;
  38095. return config;
  38096. }
  38097. MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
  38098. {
  38099. ma_lpf2_config config;
  38100. MA_ZERO_OBJECT(&config);
  38101. config.format = format;
  38102. config.channels = channels;
  38103. config.sampleRate = sampleRate;
  38104. config.cutoffFrequency = cutoffFrequency;
  38105. config.q = q;
  38106. /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
  38107. if (config.q == 0) {
  38108. config.q = 0.707107;
  38109. }
  38110. return config;
  38111. }
  38112. typedef struct
  38113. {
  38114. size_t sizeInBytes;
  38115. size_t r1Offset;
  38116. } ma_lpf1_heap_layout;
  38117. static ma_result ma_lpf1_get_heap_layout(const ma_lpf1_config* pConfig, ma_lpf1_heap_layout* pHeapLayout)
  38118. {
  38119. MA_ASSERT(pHeapLayout != NULL);
  38120. MA_ZERO_OBJECT(pHeapLayout);
  38121. if (pConfig == NULL) {
  38122. return MA_INVALID_ARGS;
  38123. }
  38124. if (pConfig->channels == 0) {
  38125. return MA_INVALID_ARGS;
  38126. }
  38127. pHeapLayout->sizeInBytes = 0;
  38128. /* R1 */
  38129. pHeapLayout->r1Offset = pHeapLayout->sizeInBytes;
  38130. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  38131. /* Make sure allocation size is aligned. */
  38132. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  38133. return MA_SUCCESS;
  38134. }
  38135. MA_API ma_result ma_lpf1_get_heap_size(const ma_lpf1_config* pConfig, size_t* pHeapSizeInBytes)
  38136. {
  38137. ma_result result;
  38138. ma_lpf1_heap_layout heapLayout;
  38139. if (pHeapSizeInBytes == NULL) {
  38140. return MA_INVALID_ARGS;
  38141. }
  38142. result = ma_lpf1_get_heap_layout(pConfig, &heapLayout);
  38143. if (result != MA_SUCCESS) {
  38144. return result;
  38145. }
  38146. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  38147. return MA_SUCCESS;
  38148. }
  38149. MA_API ma_result ma_lpf1_init_preallocated(const ma_lpf1_config* pConfig, void* pHeap, ma_lpf1* pLPF)
  38150. {
  38151. ma_result result;
  38152. ma_lpf1_heap_layout heapLayout;
  38153. if (pLPF == NULL) {
  38154. return MA_INVALID_ARGS;
  38155. }
  38156. MA_ZERO_OBJECT(pLPF);
  38157. result = ma_lpf1_get_heap_layout(pConfig, &heapLayout);
  38158. if (result != MA_SUCCESS) {
  38159. return result;
  38160. }
  38161. pLPF->_pHeap = pHeap;
  38162. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  38163. pLPF->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset);
  38164. return ma_lpf1_reinit(pConfig, pLPF);
  38165. }
  38166. MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf1* pLPF)
  38167. {
  38168. ma_result result;
  38169. size_t heapSizeInBytes;
  38170. void* pHeap;
  38171. result = ma_lpf1_get_heap_size(pConfig, &heapSizeInBytes);
  38172. if (result != MA_SUCCESS) {
  38173. return result;
  38174. }
  38175. if (heapSizeInBytes > 0) {
  38176. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38177. if (pHeap == NULL) {
  38178. return MA_OUT_OF_MEMORY;
  38179. }
  38180. } else {
  38181. pHeap = NULL;
  38182. }
  38183. result = ma_lpf1_init_preallocated(pConfig, pHeap, pLPF);
  38184. if (result != MA_SUCCESS) {
  38185. ma_free(pHeap, pAllocationCallbacks);
  38186. return result;
  38187. }
  38188. pLPF->_ownsHeap = MA_TRUE;
  38189. return MA_SUCCESS;
  38190. }
  38191. MA_API void ma_lpf1_uninit(ma_lpf1* pLPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38192. {
  38193. if (pLPF == NULL) {
  38194. return;
  38195. }
  38196. if (pLPF->_ownsHeap) {
  38197. ma_free(pLPF->_pHeap, pAllocationCallbacks);
  38198. }
  38199. }
  38200. MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF)
  38201. {
  38202. double a;
  38203. if (pLPF == NULL || pConfig == NULL) {
  38204. return MA_INVALID_ARGS;
  38205. }
  38206. /* Only supporting f32 and s16. */
  38207. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  38208. return MA_INVALID_ARGS;
  38209. }
  38210. /* The format cannot be changed after initialization. */
  38211. if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) {
  38212. return MA_INVALID_OPERATION;
  38213. }
  38214. /* The channel count cannot be changed after initialization. */
  38215. if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) {
  38216. return MA_INVALID_OPERATION;
  38217. }
  38218. pLPF->format = pConfig->format;
  38219. pLPF->channels = pConfig->channels;
  38220. a = ma_expd(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate);
  38221. if (pConfig->format == ma_format_f32) {
  38222. pLPF->a.f32 = (float)a;
  38223. } else {
  38224. pLPF->a.s32 = ma_biquad_float_to_fp(a);
  38225. }
  38226. return MA_SUCCESS;
  38227. }
  38228. MA_API ma_result ma_lpf1_clear_cache(ma_lpf1* pLPF)
  38229. {
  38230. if (pLPF == NULL) {
  38231. return MA_INVALID_ARGS;
  38232. }
  38233. if (pLPF->format == ma_format_f32) {
  38234. pLPF->a.f32 = 0;
  38235. } else {
  38236. pLPF->a.s32 = 0;
  38237. }
  38238. return MA_SUCCESS;
  38239. }
  38240. static MA_INLINE void ma_lpf1_process_pcm_frame_f32(ma_lpf1* pLPF, float* pY, const float* pX)
  38241. {
  38242. ma_uint32 c;
  38243. const ma_uint32 channels = pLPF->channels;
  38244. const float a = pLPF->a.f32;
  38245. const float b = 1 - a;
  38246. MA_ASSUME(channels > 0);
  38247. for (c = 0; c < channels; c += 1) {
  38248. float r1 = pLPF->pR1[c].f32;
  38249. float x = pX[c];
  38250. float y;
  38251. y = b*x + a*r1;
  38252. pY[c] = y;
  38253. pLPF->pR1[c].f32 = y;
  38254. }
  38255. }
  38256. static MA_INLINE void ma_lpf1_process_pcm_frame_s16(ma_lpf1* pLPF, ma_int16* pY, const ma_int16* pX)
  38257. {
  38258. ma_uint32 c;
  38259. const ma_uint32 channels = pLPF->channels;
  38260. const ma_int32 a = pLPF->a.s32;
  38261. const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a);
  38262. MA_ASSUME(channels > 0);
  38263. for (c = 0; c < channels; c += 1) {
  38264. ma_int32 r1 = pLPF->pR1[c].s32;
  38265. ma_int32 x = pX[c];
  38266. ma_int32 y;
  38267. y = (b*x + a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
  38268. pY[c] = (ma_int16)y;
  38269. pLPF->pR1[c].s32 = (ma_int32)y;
  38270. }
  38271. }
  38272. MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38273. {
  38274. ma_uint32 n;
  38275. if (pLPF == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  38276. return MA_INVALID_ARGS;
  38277. }
  38278. /* Note that the logic below needs to support in-place filtering. That is, it must support the case where pFramesOut and pFramesIn are the same. */
  38279. if (pLPF->format == ma_format_f32) {
  38280. /* */ float* pY = ( float*)pFramesOut;
  38281. const float* pX = (const float*)pFramesIn;
  38282. for (n = 0; n < frameCount; n += 1) {
  38283. ma_lpf1_process_pcm_frame_f32(pLPF, pY, pX);
  38284. pY += pLPF->channels;
  38285. pX += pLPF->channels;
  38286. }
  38287. } else if (pLPF->format == ma_format_s16) {
  38288. /* */ ma_int16* pY = ( ma_int16*)pFramesOut;
  38289. const ma_int16* pX = (const ma_int16*)pFramesIn;
  38290. for (n = 0; n < frameCount; n += 1) {
  38291. ma_lpf1_process_pcm_frame_s16(pLPF, pY, pX);
  38292. pY += pLPF->channels;
  38293. pX += pLPF->channels;
  38294. }
  38295. } else {
  38296. MA_ASSERT(MA_FALSE);
  38297. return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
  38298. }
  38299. return MA_SUCCESS;
  38300. }
  38301. MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF)
  38302. {
  38303. if (pLPF == NULL) {
  38304. return 0;
  38305. }
  38306. return 1;
  38307. }
  38308. static MA_INLINE ma_biquad_config ma_lpf2__get_biquad_config(const ma_lpf2_config* pConfig)
  38309. {
  38310. ma_biquad_config bqConfig;
  38311. double q;
  38312. double w;
  38313. double s;
  38314. double c;
  38315. double a;
  38316. MA_ASSERT(pConfig != NULL);
  38317. q = pConfig->q;
  38318. w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
  38319. s = ma_sind(w);
  38320. c = ma_cosd(w);
  38321. a = s / (2*q);
  38322. bqConfig.b0 = (1 - c) / 2;
  38323. bqConfig.b1 = 1 - c;
  38324. bqConfig.b2 = (1 - c) / 2;
  38325. bqConfig.a0 = 1 + a;
  38326. bqConfig.a1 = -2 * c;
  38327. bqConfig.a2 = 1 - a;
  38328. bqConfig.format = pConfig->format;
  38329. bqConfig.channels = pConfig->channels;
  38330. return bqConfig;
  38331. }
  38332. MA_API ma_result ma_lpf2_get_heap_size(const ma_lpf2_config* pConfig, size_t* pHeapSizeInBytes)
  38333. {
  38334. ma_biquad_config bqConfig;
  38335. bqConfig = ma_lpf2__get_biquad_config(pConfig);
  38336. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  38337. }
  38338. MA_API ma_result ma_lpf2_init_preallocated(const ma_lpf2_config* pConfig, void* pHeap, ma_lpf2* pLPF)
  38339. {
  38340. ma_result result;
  38341. ma_biquad_config bqConfig;
  38342. if (pLPF == NULL) {
  38343. return MA_INVALID_ARGS;
  38344. }
  38345. MA_ZERO_OBJECT(pLPF);
  38346. if (pConfig == NULL) {
  38347. return MA_INVALID_ARGS;
  38348. }
  38349. bqConfig = ma_lpf2__get_biquad_config(pConfig);
  38350. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pLPF->bq);
  38351. if (result != MA_SUCCESS) {
  38352. return result;
  38353. }
  38354. return MA_SUCCESS;
  38355. }
  38356. MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf2* pLPF)
  38357. {
  38358. ma_result result;
  38359. size_t heapSizeInBytes;
  38360. void* pHeap;
  38361. result = ma_lpf2_get_heap_size(pConfig, &heapSizeInBytes);
  38362. if (result != MA_SUCCESS) {
  38363. return result;
  38364. }
  38365. if (heapSizeInBytes > 0) {
  38366. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38367. if (pHeap == NULL) {
  38368. return MA_OUT_OF_MEMORY;
  38369. }
  38370. } else {
  38371. pHeap = NULL;
  38372. }
  38373. result = ma_lpf2_init_preallocated(pConfig, pHeap, pLPF);
  38374. if (result != MA_SUCCESS) {
  38375. ma_free(pHeap, pAllocationCallbacks);
  38376. return result;
  38377. }
  38378. pLPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  38379. return MA_SUCCESS;
  38380. }
  38381. MA_API void ma_lpf2_uninit(ma_lpf2* pLPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38382. {
  38383. if (pLPF == NULL) {
  38384. return;
  38385. }
  38386. ma_biquad_uninit(&pLPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  38387. }
  38388. MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF)
  38389. {
  38390. ma_result result;
  38391. ma_biquad_config bqConfig;
  38392. if (pLPF == NULL || pConfig == NULL) {
  38393. return MA_INVALID_ARGS;
  38394. }
  38395. bqConfig = ma_lpf2__get_biquad_config(pConfig);
  38396. result = ma_biquad_reinit(&bqConfig, &pLPF->bq);
  38397. if (result != MA_SUCCESS) {
  38398. return result;
  38399. }
  38400. return MA_SUCCESS;
  38401. }
  38402. MA_API ma_result ma_lpf2_clear_cache(ma_lpf2* pLPF)
  38403. {
  38404. if (pLPF == NULL) {
  38405. return MA_INVALID_ARGS;
  38406. }
  38407. ma_biquad_clear_cache(&pLPF->bq);
  38408. return MA_SUCCESS;
  38409. }
  38410. static MA_INLINE void ma_lpf2_process_pcm_frame_s16(ma_lpf2* pLPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  38411. {
  38412. ma_biquad_process_pcm_frame_s16(&pLPF->bq, pFrameOut, pFrameIn);
  38413. }
  38414. static MA_INLINE void ma_lpf2_process_pcm_frame_f32(ma_lpf2* pLPF, float* pFrameOut, const float* pFrameIn)
  38415. {
  38416. ma_biquad_process_pcm_frame_f32(&pLPF->bq, pFrameOut, pFrameIn);
  38417. }
  38418. MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38419. {
  38420. if (pLPF == NULL) {
  38421. return MA_INVALID_ARGS;
  38422. }
  38423. return ma_biquad_process_pcm_frames(&pLPF->bq, pFramesOut, pFramesIn, frameCount);
  38424. }
  38425. MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF)
  38426. {
  38427. if (pLPF == NULL) {
  38428. return 0;
  38429. }
  38430. return ma_biquad_get_latency(&pLPF->bq);
  38431. }
  38432. MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  38433. {
  38434. ma_lpf_config config;
  38435. MA_ZERO_OBJECT(&config);
  38436. config.format = format;
  38437. config.channels = channels;
  38438. config.sampleRate = sampleRate;
  38439. config.cutoffFrequency = cutoffFrequency;
  38440. config.order = ma_min(order, MA_MAX_FILTER_ORDER);
  38441. return config;
  38442. }
  38443. typedef struct
  38444. {
  38445. size_t sizeInBytes;
  38446. size_t lpf1Offset;
  38447. size_t lpf2Offset; /* Offset of the first second order filter. Subsequent filters will come straight after, and will each have the same heap size. */
  38448. } ma_lpf_heap_layout;
  38449. static void ma_lpf_calculate_sub_lpf_counts(ma_uint32 order, ma_uint32* pLPF1Count, ma_uint32* pLPF2Count)
  38450. {
  38451. MA_ASSERT(pLPF1Count != NULL);
  38452. MA_ASSERT(pLPF2Count != NULL);
  38453. *pLPF1Count = order % 2;
  38454. *pLPF2Count = order / 2;
  38455. }
  38456. static ma_result ma_lpf_get_heap_layout(const ma_lpf_config* pConfig, ma_lpf_heap_layout* pHeapLayout)
  38457. {
  38458. ma_result result;
  38459. ma_uint32 lpf1Count;
  38460. ma_uint32 lpf2Count;
  38461. ma_uint32 ilpf1;
  38462. ma_uint32 ilpf2;
  38463. MA_ASSERT(pHeapLayout != NULL);
  38464. MA_ZERO_OBJECT(pHeapLayout);
  38465. if (pConfig == NULL) {
  38466. return MA_INVALID_ARGS;
  38467. }
  38468. if (pConfig->channels == 0) {
  38469. return MA_INVALID_ARGS;
  38470. }
  38471. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  38472. return MA_INVALID_ARGS;
  38473. }
  38474. ma_lpf_calculate_sub_lpf_counts(pConfig->order, &lpf1Count, &lpf2Count);
  38475. pHeapLayout->sizeInBytes = 0;
  38476. /* LPF 1 */
  38477. pHeapLayout->lpf1Offset = pHeapLayout->sizeInBytes;
  38478. for (ilpf1 = 0; ilpf1 < lpf1Count; ilpf1 += 1) {
  38479. size_t lpf1HeapSizeInBytes;
  38480. ma_lpf1_config lpf1Config = ma_lpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  38481. result = ma_lpf1_get_heap_size(&lpf1Config, &lpf1HeapSizeInBytes);
  38482. if (result != MA_SUCCESS) {
  38483. return result;
  38484. }
  38485. pHeapLayout->sizeInBytes += sizeof(ma_lpf1) + lpf1HeapSizeInBytes;
  38486. }
  38487. /* LPF 2*/
  38488. pHeapLayout->lpf2Offset = pHeapLayout->sizeInBytes;
  38489. for (ilpf2 = 0; ilpf2 < lpf2Count; ilpf2 += 1) {
  38490. size_t lpf2HeapSizeInBytes;
  38491. ma_lpf2_config lpf2Config = ma_lpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, 0.707107); /* <-- The "q" parameter does not matter for the purpose of calculating the heap size. */
  38492. result = ma_lpf2_get_heap_size(&lpf2Config, &lpf2HeapSizeInBytes);
  38493. if (result != MA_SUCCESS) {
  38494. return result;
  38495. }
  38496. pHeapLayout->sizeInBytes += sizeof(ma_lpf2) + lpf2HeapSizeInBytes;
  38497. }
  38498. /* Make sure allocation size is aligned. */
  38499. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  38500. return MA_SUCCESS;
  38501. }
  38502. static ma_result ma_lpf_reinit__internal(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF, ma_bool32 isNew)
  38503. {
  38504. ma_result result;
  38505. ma_uint32 lpf1Count;
  38506. ma_uint32 lpf2Count;
  38507. ma_uint32 ilpf1;
  38508. ma_uint32 ilpf2;
  38509. ma_lpf_heap_layout heapLayout; /* Only used if isNew is true. */
  38510. if (pLPF == NULL || pConfig == NULL) {
  38511. return MA_INVALID_ARGS;
  38512. }
  38513. /* Only supporting f32 and s16. */
  38514. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  38515. return MA_INVALID_ARGS;
  38516. }
  38517. /* The format cannot be changed after initialization. */
  38518. if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) {
  38519. return MA_INVALID_OPERATION;
  38520. }
  38521. /* The channel count cannot be changed after initialization. */
  38522. if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) {
  38523. return MA_INVALID_OPERATION;
  38524. }
  38525. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  38526. return MA_INVALID_ARGS;
  38527. }
  38528. ma_lpf_calculate_sub_lpf_counts(pConfig->order, &lpf1Count, &lpf2Count);
  38529. /* The filter order can't change between reinits. */
  38530. if (!isNew) {
  38531. if (pLPF->lpf1Count != lpf1Count || pLPF->lpf2Count != lpf2Count) {
  38532. return MA_INVALID_OPERATION;
  38533. }
  38534. }
  38535. if (isNew) {
  38536. result = ma_lpf_get_heap_layout(pConfig, &heapLayout);
  38537. if (result != MA_SUCCESS) {
  38538. return result;
  38539. }
  38540. pLPF->_pHeap = pHeap;
  38541. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  38542. pLPF->pLPF1 = (ma_lpf1*)ma_offset_ptr(pHeap, heapLayout.lpf1Offset);
  38543. pLPF->pLPF2 = (ma_lpf2*)ma_offset_ptr(pHeap, heapLayout.lpf2Offset);
  38544. } else {
  38545. MA_ZERO_OBJECT(&heapLayout); /* To silence a compiler warning. */
  38546. }
  38547. for (ilpf1 = 0; ilpf1 < lpf1Count; ilpf1 += 1) {
  38548. ma_lpf1_config lpf1Config = ma_lpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  38549. if (isNew) {
  38550. size_t lpf1HeapSizeInBytes;
  38551. result = ma_lpf1_get_heap_size(&lpf1Config, &lpf1HeapSizeInBytes);
  38552. if (result == MA_SUCCESS) {
  38553. result = ma_lpf1_init_preallocated(&lpf1Config, ma_offset_ptr(pHeap, heapLayout.lpf1Offset + (sizeof(ma_lpf1) * lpf1Count) + (ilpf1 * lpf1HeapSizeInBytes)), &pLPF->pLPF1[ilpf1]);
  38554. }
  38555. } else {
  38556. result = ma_lpf1_reinit(&lpf1Config, &pLPF->pLPF1[ilpf1]);
  38557. }
  38558. if (result != MA_SUCCESS) {
  38559. ma_uint32 jlpf1;
  38560. for (jlpf1 = 0; jlpf1 < ilpf1; jlpf1 += 1) {
  38561. ma_lpf1_uninit(&pLPF->pLPF1[jlpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  38562. }
  38563. return result;
  38564. }
  38565. }
  38566. for (ilpf2 = 0; ilpf2 < lpf2Count; ilpf2 += 1) {
  38567. ma_lpf2_config lpf2Config;
  38568. double q;
  38569. double a;
  38570. /* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */
  38571. if (lpf1Count == 1) {
  38572. a = (1 + ilpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */
  38573. } else {
  38574. a = (1 + ilpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */
  38575. }
  38576. q = 1 / (2*ma_cosd(a));
  38577. lpf2Config = ma_lpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
  38578. if (isNew) {
  38579. size_t lpf2HeapSizeInBytes;
  38580. result = ma_lpf2_get_heap_size(&lpf2Config, &lpf2HeapSizeInBytes);
  38581. if (result == MA_SUCCESS) {
  38582. result = ma_lpf2_init_preallocated(&lpf2Config, ma_offset_ptr(pHeap, heapLayout.lpf2Offset + (sizeof(ma_lpf2) * lpf2Count) + (ilpf2 * lpf2HeapSizeInBytes)), &pLPF->pLPF2[ilpf2]);
  38583. }
  38584. } else {
  38585. result = ma_lpf2_reinit(&lpf2Config, &pLPF->pLPF2[ilpf2]);
  38586. }
  38587. if (result != MA_SUCCESS) {
  38588. ma_uint32 jlpf1;
  38589. ma_uint32 jlpf2;
  38590. for (jlpf1 = 0; jlpf1 < lpf1Count; jlpf1 += 1) {
  38591. ma_lpf1_uninit(&pLPF->pLPF1[jlpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  38592. }
  38593. for (jlpf2 = 0; jlpf2 < ilpf2; jlpf2 += 1) {
  38594. ma_lpf2_uninit(&pLPF->pLPF2[jlpf2], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  38595. }
  38596. return result;
  38597. }
  38598. }
  38599. pLPF->lpf1Count = lpf1Count;
  38600. pLPF->lpf2Count = lpf2Count;
  38601. pLPF->format = pConfig->format;
  38602. pLPF->channels = pConfig->channels;
  38603. pLPF->sampleRate = pConfig->sampleRate;
  38604. return MA_SUCCESS;
  38605. }
  38606. MA_API ma_result ma_lpf_get_heap_size(const ma_lpf_config* pConfig, size_t* pHeapSizeInBytes)
  38607. {
  38608. ma_result result;
  38609. ma_lpf_heap_layout heapLayout;
  38610. if (pHeapSizeInBytes == NULL) {
  38611. return MA_INVALID_ARGS;
  38612. }
  38613. *pHeapSizeInBytes = 0;
  38614. result = ma_lpf_get_heap_layout(pConfig, &heapLayout);
  38615. if (result != MA_SUCCESS) {
  38616. return result;
  38617. }
  38618. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  38619. return result;
  38620. }
  38621. MA_API ma_result ma_lpf_init_preallocated(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF)
  38622. {
  38623. if (pLPF == NULL) {
  38624. return MA_INVALID_ARGS;
  38625. }
  38626. MA_ZERO_OBJECT(pLPF);
  38627. return ma_lpf_reinit__internal(pConfig, pHeap, pLPF, /*isNew*/MA_TRUE);
  38628. }
  38629. MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf* pLPF)
  38630. {
  38631. ma_result result;
  38632. size_t heapSizeInBytes;
  38633. void* pHeap;
  38634. result = ma_lpf_get_heap_size(pConfig, &heapSizeInBytes);
  38635. if (result != MA_SUCCESS) {
  38636. return result;
  38637. }
  38638. if (heapSizeInBytes > 0) {
  38639. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38640. if (pHeap == NULL) {
  38641. return MA_OUT_OF_MEMORY;
  38642. }
  38643. } else {
  38644. pHeap = NULL;
  38645. }
  38646. result = ma_lpf_init_preallocated(pConfig, pHeap, pLPF);
  38647. if (result != MA_SUCCESS) {
  38648. ma_free(pHeap, pAllocationCallbacks);
  38649. return result;
  38650. }
  38651. pLPF->_ownsHeap = MA_TRUE;
  38652. return MA_SUCCESS;
  38653. }
  38654. MA_API void ma_lpf_uninit(ma_lpf* pLPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38655. {
  38656. ma_uint32 ilpf1;
  38657. ma_uint32 ilpf2;
  38658. if (pLPF == NULL) {
  38659. return;
  38660. }
  38661. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38662. ma_lpf1_uninit(&pLPF->pLPF1[ilpf1], pAllocationCallbacks);
  38663. }
  38664. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38665. ma_lpf2_uninit(&pLPF->pLPF2[ilpf2], pAllocationCallbacks);
  38666. }
  38667. if (pLPF->_ownsHeap) {
  38668. ma_free(pLPF->_pHeap, pAllocationCallbacks);
  38669. }
  38670. }
  38671. MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF)
  38672. {
  38673. return ma_lpf_reinit__internal(pConfig, NULL, pLPF, /*isNew*/MA_FALSE);
  38674. }
  38675. MA_API ma_result ma_lpf_clear_cache(ma_lpf* pLPF)
  38676. {
  38677. ma_uint32 ilpf1;
  38678. ma_uint32 ilpf2;
  38679. if (pLPF == NULL) {
  38680. return MA_INVALID_ARGS;
  38681. }
  38682. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38683. ma_lpf1_clear_cache(&pLPF->pLPF1[ilpf1]);
  38684. }
  38685. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38686. ma_lpf2_clear_cache(&pLPF->pLPF2[ilpf2]);
  38687. }
  38688. return MA_SUCCESS;
  38689. }
  38690. static MA_INLINE void ma_lpf_process_pcm_frame_f32(ma_lpf* pLPF, float* pY, const void* pX)
  38691. {
  38692. ma_uint32 ilpf1;
  38693. ma_uint32 ilpf2;
  38694. MA_ASSERT(pLPF->format == ma_format_f32);
  38695. MA_MOVE_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels));
  38696. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38697. ma_lpf1_process_pcm_frame_f32(&pLPF->pLPF1[ilpf1], pY, pY);
  38698. }
  38699. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38700. ma_lpf2_process_pcm_frame_f32(&pLPF->pLPF2[ilpf2], pY, pY);
  38701. }
  38702. }
  38703. static MA_INLINE void ma_lpf_process_pcm_frame_s16(ma_lpf* pLPF, ma_int16* pY, const ma_int16* pX)
  38704. {
  38705. ma_uint32 ilpf1;
  38706. ma_uint32 ilpf2;
  38707. MA_ASSERT(pLPF->format == ma_format_s16);
  38708. MA_MOVE_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels));
  38709. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38710. ma_lpf1_process_pcm_frame_s16(&pLPF->pLPF1[ilpf1], pY, pY);
  38711. }
  38712. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38713. ma_lpf2_process_pcm_frame_s16(&pLPF->pLPF2[ilpf2], pY, pY);
  38714. }
  38715. }
  38716. MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38717. {
  38718. ma_result result;
  38719. ma_uint32 ilpf1;
  38720. ma_uint32 ilpf2;
  38721. if (pLPF == NULL) {
  38722. return MA_INVALID_ARGS;
  38723. }
  38724. /* Faster path for in-place. */
  38725. if (pFramesOut == pFramesIn) {
  38726. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38727. result = ma_lpf1_process_pcm_frames(&pLPF->pLPF1[ilpf1], pFramesOut, pFramesOut, frameCount);
  38728. if (result != MA_SUCCESS) {
  38729. return result;
  38730. }
  38731. }
  38732. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38733. result = ma_lpf2_process_pcm_frames(&pLPF->pLPF2[ilpf2], pFramesOut, pFramesOut, frameCount);
  38734. if (result != MA_SUCCESS) {
  38735. return result;
  38736. }
  38737. }
  38738. }
  38739. /* Slightly slower path for copying. */
  38740. if (pFramesOut != pFramesIn) {
  38741. ma_uint32 iFrame;
  38742. /* */ if (pLPF->format == ma_format_f32) {
  38743. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  38744. const float* pFramesInF32 = (const float*)pFramesIn;
  38745. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  38746. ma_lpf_process_pcm_frame_f32(pLPF, pFramesOutF32, pFramesInF32);
  38747. pFramesOutF32 += pLPF->channels;
  38748. pFramesInF32 += pLPF->channels;
  38749. }
  38750. } else if (pLPF->format == ma_format_s16) {
  38751. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  38752. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  38753. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  38754. ma_lpf_process_pcm_frame_s16(pLPF, pFramesOutS16, pFramesInS16);
  38755. pFramesOutS16 += pLPF->channels;
  38756. pFramesInS16 += pLPF->channels;
  38757. }
  38758. } else {
  38759. MA_ASSERT(MA_FALSE);
  38760. return MA_INVALID_OPERATION; /* Should never hit this. */
  38761. }
  38762. }
  38763. return MA_SUCCESS;
  38764. }
  38765. MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF)
  38766. {
  38767. if (pLPF == NULL) {
  38768. return 0;
  38769. }
  38770. return pLPF->lpf2Count*2 + pLPF->lpf1Count;
  38771. }
  38772. /**************************************************************************************************************************************************************
  38773. High-Pass Filtering
  38774. **************************************************************************************************************************************************************/
  38775. MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency)
  38776. {
  38777. ma_hpf1_config config;
  38778. MA_ZERO_OBJECT(&config);
  38779. config.format = format;
  38780. config.channels = channels;
  38781. config.sampleRate = sampleRate;
  38782. config.cutoffFrequency = cutoffFrequency;
  38783. return config;
  38784. }
  38785. MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
  38786. {
  38787. ma_hpf2_config config;
  38788. MA_ZERO_OBJECT(&config);
  38789. config.format = format;
  38790. config.channels = channels;
  38791. config.sampleRate = sampleRate;
  38792. config.cutoffFrequency = cutoffFrequency;
  38793. config.q = q;
  38794. /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
  38795. if (config.q == 0) {
  38796. config.q = 0.707107;
  38797. }
  38798. return config;
  38799. }
  38800. typedef struct
  38801. {
  38802. size_t sizeInBytes;
  38803. size_t r1Offset;
  38804. } ma_hpf1_heap_layout;
  38805. static ma_result ma_hpf1_get_heap_layout(const ma_hpf1_config* pConfig, ma_hpf1_heap_layout* pHeapLayout)
  38806. {
  38807. MA_ASSERT(pHeapLayout != NULL);
  38808. MA_ZERO_OBJECT(pHeapLayout);
  38809. if (pConfig == NULL) {
  38810. return MA_INVALID_ARGS;
  38811. }
  38812. if (pConfig->channels == 0) {
  38813. return MA_INVALID_ARGS;
  38814. }
  38815. pHeapLayout->sizeInBytes = 0;
  38816. /* R1 */
  38817. pHeapLayout->r1Offset = pHeapLayout->sizeInBytes;
  38818. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  38819. /* Make sure allocation size is aligned. */
  38820. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  38821. return MA_SUCCESS;
  38822. }
  38823. MA_API ma_result ma_hpf1_get_heap_size(const ma_hpf1_config* pConfig, size_t* pHeapSizeInBytes)
  38824. {
  38825. ma_result result;
  38826. ma_hpf1_heap_layout heapLayout;
  38827. if (pHeapSizeInBytes == NULL) {
  38828. return MA_INVALID_ARGS;
  38829. }
  38830. result = ma_hpf1_get_heap_layout(pConfig, &heapLayout);
  38831. if (result != MA_SUCCESS) {
  38832. return result;
  38833. }
  38834. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  38835. return MA_SUCCESS;
  38836. }
  38837. MA_API ma_result ma_hpf1_init_preallocated(const ma_hpf1_config* pConfig, void* pHeap, ma_hpf1* pLPF)
  38838. {
  38839. ma_result result;
  38840. ma_hpf1_heap_layout heapLayout;
  38841. if (pLPF == NULL) {
  38842. return MA_INVALID_ARGS;
  38843. }
  38844. MA_ZERO_OBJECT(pLPF);
  38845. result = ma_hpf1_get_heap_layout(pConfig, &heapLayout);
  38846. if (result != MA_SUCCESS) {
  38847. return result;
  38848. }
  38849. pLPF->_pHeap = pHeap;
  38850. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  38851. pLPF->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset);
  38852. return ma_hpf1_reinit(pConfig, pLPF);
  38853. }
  38854. MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf1* pLPF)
  38855. {
  38856. ma_result result;
  38857. size_t heapSizeInBytes;
  38858. void* pHeap;
  38859. result = ma_hpf1_get_heap_size(pConfig, &heapSizeInBytes);
  38860. if (result != MA_SUCCESS) {
  38861. return result;
  38862. }
  38863. if (heapSizeInBytes > 0) {
  38864. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38865. if (pHeap == NULL) {
  38866. return MA_OUT_OF_MEMORY;
  38867. }
  38868. } else {
  38869. pHeap = NULL;
  38870. }
  38871. result = ma_hpf1_init_preallocated(pConfig, pHeap, pLPF);
  38872. if (result != MA_SUCCESS) {
  38873. ma_free(pHeap, pAllocationCallbacks);
  38874. return result;
  38875. }
  38876. pLPF->_ownsHeap = MA_TRUE;
  38877. return MA_SUCCESS;
  38878. }
  38879. MA_API void ma_hpf1_uninit(ma_hpf1* pHPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38880. {
  38881. if (pHPF == NULL) {
  38882. return;
  38883. }
  38884. if (pHPF->_ownsHeap) {
  38885. ma_free(pHPF->_pHeap, pAllocationCallbacks);
  38886. }
  38887. }
  38888. MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF)
  38889. {
  38890. double a;
  38891. if (pHPF == NULL || pConfig == NULL) {
  38892. return MA_INVALID_ARGS;
  38893. }
  38894. /* Only supporting f32 and s16. */
  38895. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  38896. return MA_INVALID_ARGS;
  38897. }
  38898. /* The format cannot be changed after initialization. */
  38899. if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) {
  38900. return MA_INVALID_OPERATION;
  38901. }
  38902. /* The channel count cannot be changed after initialization. */
  38903. if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) {
  38904. return MA_INVALID_OPERATION;
  38905. }
  38906. pHPF->format = pConfig->format;
  38907. pHPF->channels = pConfig->channels;
  38908. a = ma_expd(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate);
  38909. if (pConfig->format == ma_format_f32) {
  38910. pHPF->a.f32 = (float)a;
  38911. } else {
  38912. pHPF->a.s32 = ma_biquad_float_to_fp(a);
  38913. }
  38914. return MA_SUCCESS;
  38915. }
  38916. static MA_INLINE void ma_hpf1_process_pcm_frame_f32(ma_hpf1* pHPF, float* pY, const float* pX)
  38917. {
  38918. ma_uint32 c;
  38919. const ma_uint32 channels = pHPF->channels;
  38920. const float a = 1 - pHPF->a.f32;
  38921. const float b = 1 - a;
  38922. MA_ASSUME(channels > 0);
  38923. for (c = 0; c < channels; c += 1) {
  38924. float r1 = pHPF->pR1[c].f32;
  38925. float x = pX[c];
  38926. float y;
  38927. y = b*x - a*r1;
  38928. pY[c] = y;
  38929. pHPF->pR1[c].f32 = y;
  38930. }
  38931. }
  38932. static MA_INLINE void ma_hpf1_process_pcm_frame_s16(ma_hpf1* pHPF, ma_int16* pY, const ma_int16* pX)
  38933. {
  38934. ma_uint32 c;
  38935. const ma_uint32 channels = pHPF->channels;
  38936. const ma_int32 a = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - pHPF->a.s32);
  38937. const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a);
  38938. MA_ASSUME(channels > 0);
  38939. for (c = 0; c < channels; c += 1) {
  38940. ma_int32 r1 = pHPF->pR1[c].s32;
  38941. ma_int32 x = pX[c];
  38942. ma_int32 y;
  38943. y = (b*x - a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
  38944. pY[c] = (ma_int16)y;
  38945. pHPF->pR1[c].s32 = (ma_int32)y;
  38946. }
  38947. }
  38948. MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38949. {
  38950. ma_uint32 n;
  38951. if (pHPF == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  38952. return MA_INVALID_ARGS;
  38953. }
  38954. /* Note that the logic below needs to support in-place filtering. That is, it must support the case where pFramesOut and pFramesIn are the same. */
  38955. if (pHPF->format == ma_format_f32) {
  38956. /* */ float* pY = ( float*)pFramesOut;
  38957. const float* pX = (const float*)pFramesIn;
  38958. for (n = 0; n < frameCount; n += 1) {
  38959. ma_hpf1_process_pcm_frame_f32(pHPF, pY, pX);
  38960. pY += pHPF->channels;
  38961. pX += pHPF->channels;
  38962. }
  38963. } else if (pHPF->format == ma_format_s16) {
  38964. /* */ ma_int16* pY = ( ma_int16*)pFramesOut;
  38965. const ma_int16* pX = (const ma_int16*)pFramesIn;
  38966. for (n = 0; n < frameCount; n += 1) {
  38967. ma_hpf1_process_pcm_frame_s16(pHPF, pY, pX);
  38968. pY += pHPF->channels;
  38969. pX += pHPF->channels;
  38970. }
  38971. } else {
  38972. MA_ASSERT(MA_FALSE);
  38973. return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
  38974. }
  38975. return MA_SUCCESS;
  38976. }
  38977. MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF)
  38978. {
  38979. if (pHPF == NULL) {
  38980. return 0;
  38981. }
  38982. return 1;
  38983. }
  38984. static MA_INLINE ma_biquad_config ma_hpf2__get_biquad_config(const ma_hpf2_config* pConfig)
  38985. {
  38986. ma_biquad_config bqConfig;
  38987. double q;
  38988. double w;
  38989. double s;
  38990. double c;
  38991. double a;
  38992. MA_ASSERT(pConfig != NULL);
  38993. q = pConfig->q;
  38994. w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
  38995. s = ma_sind(w);
  38996. c = ma_cosd(w);
  38997. a = s / (2*q);
  38998. bqConfig.b0 = (1 + c) / 2;
  38999. bqConfig.b1 = -(1 + c);
  39000. bqConfig.b2 = (1 + c) / 2;
  39001. bqConfig.a0 = 1 + a;
  39002. bqConfig.a1 = -2 * c;
  39003. bqConfig.a2 = 1 - a;
  39004. bqConfig.format = pConfig->format;
  39005. bqConfig.channels = pConfig->channels;
  39006. return bqConfig;
  39007. }
  39008. MA_API ma_result ma_hpf2_get_heap_size(const ma_hpf2_config* pConfig, size_t* pHeapSizeInBytes)
  39009. {
  39010. ma_biquad_config bqConfig;
  39011. bqConfig = ma_hpf2__get_biquad_config(pConfig);
  39012. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39013. }
  39014. MA_API ma_result ma_hpf2_init_preallocated(const ma_hpf2_config* pConfig, void* pHeap, ma_hpf2* pHPF)
  39015. {
  39016. ma_result result;
  39017. ma_biquad_config bqConfig;
  39018. if (pHPF == NULL) {
  39019. return MA_INVALID_ARGS;
  39020. }
  39021. MA_ZERO_OBJECT(pHPF);
  39022. if (pConfig == NULL) {
  39023. return MA_INVALID_ARGS;
  39024. }
  39025. bqConfig = ma_hpf2__get_biquad_config(pConfig);
  39026. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pHPF->bq);
  39027. if (result != MA_SUCCESS) {
  39028. return result;
  39029. }
  39030. return MA_SUCCESS;
  39031. }
  39032. MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf2* pHPF)
  39033. {
  39034. ma_result result;
  39035. size_t heapSizeInBytes;
  39036. void* pHeap;
  39037. result = ma_hpf2_get_heap_size(pConfig, &heapSizeInBytes);
  39038. if (result != MA_SUCCESS) {
  39039. return result;
  39040. }
  39041. if (heapSizeInBytes > 0) {
  39042. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39043. if (pHeap == NULL) {
  39044. return MA_OUT_OF_MEMORY;
  39045. }
  39046. } else {
  39047. pHeap = NULL;
  39048. }
  39049. result = ma_hpf2_init_preallocated(pConfig, pHeap, pHPF);
  39050. if (result != MA_SUCCESS) {
  39051. ma_free(pHeap, pAllocationCallbacks);
  39052. return result;
  39053. }
  39054. pHPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39055. return MA_SUCCESS;
  39056. }
  39057. MA_API void ma_hpf2_uninit(ma_hpf2* pHPF, const ma_allocation_callbacks* pAllocationCallbacks)
  39058. {
  39059. if (pHPF == NULL) {
  39060. return;
  39061. }
  39062. ma_biquad_uninit(&pHPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  39063. }
  39064. MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF)
  39065. {
  39066. ma_result result;
  39067. ma_biquad_config bqConfig;
  39068. if (pHPF == NULL || pConfig == NULL) {
  39069. return MA_INVALID_ARGS;
  39070. }
  39071. bqConfig = ma_hpf2__get_biquad_config(pConfig);
  39072. result = ma_biquad_reinit(&bqConfig, &pHPF->bq);
  39073. if (result != MA_SUCCESS) {
  39074. return result;
  39075. }
  39076. return MA_SUCCESS;
  39077. }
  39078. static MA_INLINE void ma_hpf2_process_pcm_frame_s16(ma_hpf2* pHPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  39079. {
  39080. ma_biquad_process_pcm_frame_s16(&pHPF->bq, pFrameOut, pFrameIn);
  39081. }
  39082. static MA_INLINE void ma_hpf2_process_pcm_frame_f32(ma_hpf2* pHPF, float* pFrameOut, const float* pFrameIn)
  39083. {
  39084. ma_biquad_process_pcm_frame_f32(&pHPF->bq, pFrameOut, pFrameIn);
  39085. }
  39086. MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39087. {
  39088. if (pHPF == NULL) {
  39089. return MA_INVALID_ARGS;
  39090. }
  39091. return ma_biquad_process_pcm_frames(&pHPF->bq, pFramesOut, pFramesIn, frameCount);
  39092. }
  39093. MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF)
  39094. {
  39095. if (pHPF == NULL) {
  39096. return 0;
  39097. }
  39098. return ma_biquad_get_latency(&pHPF->bq);
  39099. }
  39100. MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  39101. {
  39102. ma_hpf_config config;
  39103. MA_ZERO_OBJECT(&config);
  39104. config.format = format;
  39105. config.channels = channels;
  39106. config.sampleRate = sampleRate;
  39107. config.cutoffFrequency = cutoffFrequency;
  39108. config.order = ma_min(order, MA_MAX_FILTER_ORDER);
  39109. return config;
  39110. }
  39111. typedef struct
  39112. {
  39113. size_t sizeInBytes;
  39114. size_t hpf1Offset;
  39115. size_t hpf2Offset; /* Offset of the first second order filter. Subsequent filters will come straight after, and will each have the same heap size. */
  39116. } ma_hpf_heap_layout;
  39117. static void ma_hpf_calculate_sub_hpf_counts(ma_uint32 order, ma_uint32* pHPF1Count, ma_uint32* pHPF2Count)
  39118. {
  39119. MA_ASSERT(pHPF1Count != NULL);
  39120. MA_ASSERT(pHPF2Count != NULL);
  39121. *pHPF1Count = order % 2;
  39122. *pHPF2Count = order / 2;
  39123. }
  39124. static ma_result ma_hpf_get_heap_layout(const ma_hpf_config* pConfig, ma_hpf_heap_layout* pHeapLayout)
  39125. {
  39126. ma_result result;
  39127. ma_uint32 hpf1Count;
  39128. ma_uint32 hpf2Count;
  39129. ma_uint32 ihpf1;
  39130. ma_uint32 ihpf2;
  39131. MA_ASSERT(pHeapLayout != NULL);
  39132. MA_ZERO_OBJECT(pHeapLayout);
  39133. if (pConfig == NULL) {
  39134. return MA_INVALID_ARGS;
  39135. }
  39136. if (pConfig->channels == 0) {
  39137. return MA_INVALID_ARGS;
  39138. }
  39139. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  39140. return MA_INVALID_ARGS;
  39141. }
  39142. ma_hpf_calculate_sub_hpf_counts(pConfig->order, &hpf1Count, &hpf2Count);
  39143. pHeapLayout->sizeInBytes = 0;
  39144. /* HPF 1 */
  39145. pHeapLayout->hpf1Offset = pHeapLayout->sizeInBytes;
  39146. for (ihpf1 = 0; ihpf1 < hpf1Count; ihpf1 += 1) {
  39147. size_t hpf1HeapSizeInBytes;
  39148. ma_hpf1_config hpf1Config = ma_hpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  39149. result = ma_hpf1_get_heap_size(&hpf1Config, &hpf1HeapSizeInBytes);
  39150. if (result != MA_SUCCESS) {
  39151. return result;
  39152. }
  39153. pHeapLayout->sizeInBytes += sizeof(ma_hpf1) + hpf1HeapSizeInBytes;
  39154. }
  39155. /* HPF 2*/
  39156. pHeapLayout->hpf2Offset = pHeapLayout->sizeInBytes;
  39157. for (ihpf2 = 0; ihpf2 < hpf2Count; ihpf2 += 1) {
  39158. size_t hpf2HeapSizeInBytes;
  39159. ma_hpf2_config hpf2Config = ma_hpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, 0.707107); /* <-- The "q" parameter does not matter for the purpose of calculating the heap size. */
  39160. result = ma_hpf2_get_heap_size(&hpf2Config, &hpf2HeapSizeInBytes);
  39161. if (result != MA_SUCCESS) {
  39162. return result;
  39163. }
  39164. pHeapLayout->sizeInBytes += sizeof(ma_hpf2) + hpf2HeapSizeInBytes;
  39165. }
  39166. /* Make sure allocation size is aligned. */
  39167. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  39168. return MA_SUCCESS;
  39169. }
  39170. static ma_result ma_hpf_reinit__internal(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pHPF, ma_bool32 isNew)
  39171. {
  39172. ma_result result;
  39173. ma_uint32 hpf1Count;
  39174. ma_uint32 hpf2Count;
  39175. ma_uint32 ihpf1;
  39176. ma_uint32 ihpf2;
  39177. ma_hpf_heap_layout heapLayout; /* Only used if isNew is true. */
  39178. if (pHPF == NULL || pConfig == NULL) {
  39179. return MA_INVALID_ARGS;
  39180. }
  39181. /* Only supporting f32 and s16. */
  39182. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  39183. return MA_INVALID_ARGS;
  39184. }
  39185. /* The format cannot be changed after initialization. */
  39186. if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) {
  39187. return MA_INVALID_OPERATION;
  39188. }
  39189. /* The channel count cannot be changed after initialization. */
  39190. if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) {
  39191. return MA_INVALID_OPERATION;
  39192. }
  39193. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  39194. return MA_INVALID_ARGS;
  39195. }
  39196. ma_hpf_calculate_sub_hpf_counts(pConfig->order, &hpf1Count, &hpf2Count);
  39197. /* The filter order can't change between reinits. */
  39198. if (!isNew) {
  39199. if (pHPF->hpf1Count != hpf1Count || pHPF->hpf2Count != hpf2Count) {
  39200. return MA_INVALID_OPERATION;
  39201. }
  39202. }
  39203. if (isNew) {
  39204. result = ma_hpf_get_heap_layout(pConfig, &heapLayout);
  39205. if (result != MA_SUCCESS) {
  39206. return result;
  39207. }
  39208. pHPF->_pHeap = pHeap;
  39209. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  39210. pHPF->pHPF1 = (ma_hpf1*)ma_offset_ptr(pHeap, heapLayout.hpf1Offset);
  39211. pHPF->pHPF2 = (ma_hpf2*)ma_offset_ptr(pHeap, heapLayout.hpf2Offset);
  39212. } else {
  39213. MA_ZERO_OBJECT(&heapLayout); /* To silence a compiler warning. */
  39214. }
  39215. for (ihpf1 = 0; ihpf1 < hpf1Count; ihpf1 += 1) {
  39216. ma_hpf1_config hpf1Config = ma_hpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  39217. if (isNew) {
  39218. size_t hpf1HeapSizeInBytes;
  39219. result = ma_hpf1_get_heap_size(&hpf1Config, &hpf1HeapSizeInBytes);
  39220. if (result == MA_SUCCESS) {
  39221. result = ma_hpf1_init_preallocated(&hpf1Config, ma_offset_ptr(pHeap, heapLayout.hpf1Offset + (sizeof(ma_hpf1) * hpf1Count) + (ihpf1 * hpf1HeapSizeInBytes)), &pHPF->pHPF1[ihpf1]);
  39222. }
  39223. } else {
  39224. result = ma_hpf1_reinit(&hpf1Config, &pHPF->pHPF1[ihpf1]);
  39225. }
  39226. if (result != MA_SUCCESS) {
  39227. ma_uint32 jhpf1;
  39228. for (jhpf1 = 0; jhpf1 < ihpf1; jhpf1 += 1) {
  39229. ma_hpf1_uninit(&pHPF->pHPF1[jhpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  39230. }
  39231. return result;
  39232. }
  39233. }
  39234. for (ihpf2 = 0; ihpf2 < hpf2Count; ihpf2 += 1) {
  39235. ma_hpf2_config hpf2Config;
  39236. double q;
  39237. double a;
  39238. /* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */
  39239. if (hpf1Count == 1) {
  39240. a = (1 + ihpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */
  39241. } else {
  39242. a = (1 + ihpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */
  39243. }
  39244. q = 1 / (2*ma_cosd(a));
  39245. hpf2Config = ma_hpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
  39246. if (isNew) {
  39247. size_t hpf2HeapSizeInBytes;
  39248. result = ma_hpf2_get_heap_size(&hpf2Config, &hpf2HeapSizeInBytes);
  39249. if (result == MA_SUCCESS) {
  39250. result = ma_hpf2_init_preallocated(&hpf2Config, ma_offset_ptr(pHeap, heapLayout.hpf2Offset + (sizeof(ma_hpf2) * hpf2Count) + (ihpf2 * hpf2HeapSizeInBytes)), &pHPF->pHPF2[ihpf2]);
  39251. }
  39252. } else {
  39253. result = ma_hpf2_reinit(&hpf2Config, &pHPF->pHPF2[ihpf2]);
  39254. }
  39255. if (result != MA_SUCCESS) {
  39256. ma_uint32 jhpf1;
  39257. ma_uint32 jhpf2;
  39258. for (jhpf1 = 0; jhpf1 < hpf1Count; jhpf1 += 1) {
  39259. ma_hpf1_uninit(&pHPF->pHPF1[jhpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  39260. }
  39261. for (jhpf2 = 0; jhpf2 < ihpf2; jhpf2 += 1) {
  39262. ma_hpf2_uninit(&pHPF->pHPF2[jhpf2], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  39263. }
  39264. return result;
  39265. }
  39266. }
  39267. pHPF->hpf1Count = hpf1Count;
  39268. pHPF->hpf2Count = hpf2Count;
  39269. pHPF->format = pConfig->format;
  39270. pHPF->channels = pConfig->channels;
  39271. pHPF->sampleRate = pConfig->sampleRate;
  39272. return MA_SUCCESS;
  39273. }
  39274. MA_API ma_result ma_hpf_get_heap_size(const ma_hpf_config* pConfig, size_t* pHeapSizeInBytes)
  39275. {
  39276. ma_result result;
  39277. ma_hpf_heap_layout heapLayout;
  39278. if (pHeapSizeInBytes == NULL) {
  39279. return MA_INVALID_ARGS;
  39280. }
  39281. *pHeapSizeInBytes = 0;
  39282. result = ma_hpf_get_heap_layout(pConfig, &heapLayout);
  39283. if (result != MA_SUCCESS) {
  39284. return result;
  39285. }
  39286. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  39287. return result;
  39288. }
  39289. MA_API ma_result ma_hpf_init_preallocated(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pLPF)
  39290. {
  39291. if (pLPF == NULL) {
  39292. return MA_INVALID_ARGS;
  39293. }
  39294. MA_ZERO_OBJECT(pLPF);
  39295. return ma_hpf_reinit__internal(pConfig, pHeap, pLPF, /*isNew*/MA_TRUE);
  39296. }
  39297. MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf* pHPF)
  39298. {
  39299. ma_result result;
  39300. size_t heapSizeInBytes;
  39301. void* pHeap;
  39302. result = ma_hpf_get_heap_size(pConfig, &heapSizeInBytes);
  39303. if (result != MA_SUCCESS) {
  39304. return result;
  39305. }
  39306. if (heapSizeInBytes > 0) {
  39307. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39308. if (pHeap == NULL) {
  39309. return MA_OUT_OF_MEMORY;
  39310. }
  39311. } else {
  39312. pHeap = NULL;
  39313. }
  39314. result = ma_hpf_init_preallocated(pConfig, pHeap, pHPF);
  39315. if (result != MA_SUCCESS) {
  39316. ma_free(pHeap, pAllocationCallbacks);
  39317. return result;
  39318. }
  39319. pHPF->_ownsHeap = MA_TRUE;
  39320. return MA_SUCCESS;
  39321. }
  39322. MA_API void ma_hpf_uninit(ma_hpf* pHPF, const ma_allocation_callbacks* pAllocationCallbacks)
  39323. {
  39324. ma_uint32 ihpf1;
  39325. ma_uint32 ihpf2;
  39326. if (pHPF == NULL) {
  39327. return;
  39328. }
  39329. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  39330. ma_hpf1_uninit(&pHPF->pHPF1[ihpf1], pAllocationCallbacks);
  39331. }
  39332. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  39333. ma_hpf2_uninit(&pHPF->pHPF2[ihpf2], pAllocationCallbacks);
  39334. }
  39335. if (pHPF->_ownsHeap) {
  39336. ma_free(pHPF->_pHeap, pAllocationCallbacks);
  39337. }
  39338. }
  39339. MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF)
  39340. {
  39341. return ma_hpf_reinit__internal(pConfig, NULL, pHPF, /*isNew*/MA_FALSE);
  39342. }
  39343. MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39344. {
  39345. ma_result result;
  39346. ma_uint32 ihpf1;
  39347. ma_uint32 ihpf2;
  39348. if (pHPF == NULL) {
  39349. return MA_INVALID_ARGS;
  39350. }
  39351. /* Faster path for in-place. */
  39352. if (pFramesOut == pFramesIn) {
  39353. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  39354. result = ma_hpf1_process_pcm_frames(&pHPF->pHPF1[ihpf1], pFramesOut, pFramesOut, frameCount);
  39355. if (result != MA_SUCCESS) {
  39356. return result;
  39357. }
  39358. }
  39359. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  39360. result = ma_hpf2_process_pcm_frames(&pHPF->pHPF2[ihpf2], pFramesOut, pFramesOut, frameCount);
  39361. if (result != MA_SUCCESS) {
  39362. return result;
  39363. }
  39364. }
  39365. }
  39366. /* Slightly slower path for copying. */
  39367. if (pFramesOut != pFramesIn) {
  39368. ma_uint32 iFrame;
  39369. /* */ if (pHPF->format == ma_format_f32) {
  39370. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  39371. const float* pFramesInF32 = (const float*)pFramesIn;
  39372. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39373. MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pHPF->format, pHPF->channels));
  39374. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  39375. ma_hpf1_process_pcm_frame_f32(&pHPF->pHPF1[ihpf1], pFramesOutF32, pFramesOutF32);
  39376. }
  39377. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  39378. ma_hpf2_process_pcm_frame_f32(&pHPF->pHPF2[ihpf2], pFramesOutF32, pFramesOutF32);
  39379. }
  39380. pFramesOutF32 += pHPF->channels;
  39381. pFramesInF32 += pHPF->channels;
  39382. }
  39383. } else if (pHPF->format == ma_format_s16) {
  39384. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  39385. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  39386. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39387. MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pHPF->format, pHPF->channels));
  39388. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  39389. ma_hpf1_process_pcm_frame_s16(&pHPF->pHPF1[ihpf1], pFramesOutS16, pFramesOutS16);
  39390. }
  39391. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  39392. ma_hpf2_process_pcm_frame_s16(&pHPF->pHPF2[ihpf2], pFramesOutS16, pFramesOutS16);
  39393. }
  39394. pFramesOutS16 += pHPF->channels;
  39395. pFramesInS16 += pHPF->channels;
  39396. }
  39397. } else {
  39398. MA_ASSERT(MA_FALSE);
  39399. return MA_INVALID_OPERATION; /* Should never hit this. */
  39400. }
  39401. }
  39402. return MA_SUCCESS;
  39403. }
  39404. MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF)
  39405. {
  39406. if (pHPF == NULL) {
  39407. return 0;
  39408. }
  39409. return pHPF->hpf2Count*2 + pHPF->hpf1Count;
  39410. }
  39411. /**************************************************************************************************************************************************************
  39412. Band-Pass Filtering
  39413. **************************************************************************************************************************************************************/
  39414. MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
  39415. {
  39416. ma_bpf2_config config;
  39417. MA_ZERO_OBJECT(&config);
  39418. config.format = format;
  39419. config.channels = channels;
  39420. config.sampleRate = sampleRate;
  39421. config.cutoffFrequency = cutoffFrequency;
  39422. config.q = q;
  39423. /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
  39424. if (config.q == 0) {
  39425. config.q = 0.707107;
  39426. }
  39427. return config;
  39428. }
  39429. static MA_INLINE ma_biquad_config ma_bpf2__get_biquad_config(const ma_bpf2_config* pConfig)
  39430. {
  39431. ma_biquad_config bqConfig;
  39432. double q;
  39433. double w;
  39434. double s;
  39435. double c;
  39436. double a;
  39437. MA_ASSERT(pConfig != NULL);
  39438. q = pConfig->q;
  39439. w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
  39440. s = ma_sind(w);
  39441. c = ma_cosd(w);
  39442. a = s / (2*q);
  39443. bqConfig.b0 = q * a;
  39444. bqConfig.b1 = 0;
  39445. bqConfig.b2 = -q * a;
  39446. bqConfig.a0 = 1 + a;
  39447. bqConfig.a1 = -2 * c;
  39448. bqConfig.a2 = 1 - a;
  39449. bqConfig.format = pConfig->format;
  39450. bqConfig.channels = pConfig->channels;
  39451. return bqConfig;
  39452. }
  39453. MA_API ma_result ma_bpf2_get_heap_size(const ma_bpf2_config* pConfig, size_t* pHeapSizeInBytes)
  39454. {
  39455. ma_biquad_config bqConfig;
  39456. bqConfig = ma_bpf2__get_biquad_config(pConfig);
  39457. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39458. }
  39459. MA_API ma_result ma_bpf2_init_preallocated(const ma_bpf2_config* pConfig, void* pHeap, ma_bpf2* pBPF)
  39460. {
  39461. ma_result result;
  39462. ma_biquad_config bqConfig;
  39463. if (pBPF == NULL) {
  39464. return MA_INVALID_ARGS;
  39465. }
  39466. MA_ZERO_OBJECT(pBPF);
  39467. if (pConfig == NULL) {
  39468. return MA_INVALID_ARGS;
  39469. }
  39470. bqConfig = ma_bpf2__get_biquad_config(pConfig);
  39471. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pBPF->bq);
  39472. if (result != MA_SUCCESS) {
  39473. return result;
  39474. }
  39475. return MA_SUCCESS;
  39476. }
  39477. MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf2* pBPF)
  39478. {
  39479. ma_result result;
  39480. size_t heapSizeInBytes;
  39481. void* pHeap;
  39482. result = ma_bpf2_get_heap_size(pConfig, &heapSizeInBytes);
  39483. if (result != MA_SUCCESS) {
  39484. return result;
  39485. }
  39486. if (heapSizeInBytes > 0) {
  39487. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39488. if (pHeap == NULL) {
  39489. return MA_OUT_OF_MEMORY;
  39490. }
  39491. } else {
  39492. pHeap = NULL;
  39493. }
  39494. result = ma_bpf2_init_preallocated(pConfig, pHeap, pBPF);
  39495. if (result != MA_SUCCESS) {
  39496. ma_free(pHeap, pAllocationCallbacks);
  39497. return result;
  39498. }
  39499. pBPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39500. return MA_SUCCESS;
  39501. }
  39502. MA_API void ma_bpf2_uninit(ma_bpf2* pBPF, const ma_allocation_callbacks* pAllocationCallbacks)
  39503. {
  39504. if (pBPF == NULL) {
  39505. return;
  39506. }
  39507. ma_biquad_uninit(&pBPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  39508. }
  39509. MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF)
  39510. {
  39511. ma_result result;
  39512. ma_biquad_config bqConfig;
  39513. if (pBPF == NULL || pConfig == NULL) {
  39514. return MA_INVALID_ARGS;
  39515. }
  39516. bqConfig = ma_bpf2__get_biquad_config(pConfig);
  39517. result = ma_biquad_reinit(&bqConfig, &pBPF->bq);
  39518. if (result != MA_SUCCESS) {
  39519. return result;
  39520. }
  39521. return MA_SUCCESS;
  39522. }
  39523. static MA_INLINE void ma_bpf2_process_pcm_frame_s16(ma_bpf2* pBPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  39524. {
  39525. ma_biquad_process_pcm_frame_s16(&pBPF->bq, pFrameOut, pFrameIn);
  39526. }
  39527. static MA_INLINE void ma_bpf2_process_pcm_frame_f32(ma_bpf2* pBPF, float* pFrameOut, const float* pFrameIn)
  39528. {
  39529. ma_biquad_process_pcm_frame_f32(&pBPF->bq, pFrameOut, pFrameIn);
  39530. }
  39531. MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39532. {
  39533. if (pBPF == NULL) {
  39534. return MA_INVALID_ARGS;
  39535. }
  39536. return ma_biquad_process_pcm_frames(&pBPF->bq, pFramesOut, pFramesIn, frameCount);
  39537. }
  39538. MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF)
  39539. {
  39540. if (pBPF == NULL) {
  39541. return 0;
  39542. }
  39543. return ma_biquad_get_latency(&pBPF->bq);
  39544. }
  39545. MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  39546. {
  39547. ma_bpf_config config;
  39548. MA_ZERO_OBJECT(&config);
  39549. config.format = format;
  39550. config.channels = channels;
  39551. config.sampleRate = sampleRate;
  39552. config.cutoffFrequency = cutoffFrequency;
  39553. config.order = ma_min(order, MA_MAX_FILTER_ORDER);
  39554. return config;
  39555. }
  39556. typedef struct
  39557. {
  39558. size_t sizeInBytes;
  39559. size_t bpf2Offset;
  39560. } ma_bpf_heap_layout;
  39561. static ma_result ma_bpf_get_heap_layout(const ma_bpf_config* pConfig, ma_bpf_heap_layout* pHeapLayout)
  39562. {
  39563. ma_result result;
  39564. ma_uint32 bpf2Count;
  39565. ma_uint32 ibpf2;
  39566. MA_ASSERT(pHeapLayout != NULL);
  39567. MA_ZERO_OBJECT(pHeapLayout);
  39568. if (pConfig == NULL) {
  39569. return MA_INVALID_ARGS;
  39570. }
  39571. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  39572. return MA_INVALID_ARGS;
  39573. }
  39574. /* We must have an even number of order. */
  39575. if ((pConfig->order & 0x1) != 0) {
  39576. return MA_INVALID_ARGS;
  39577. }
  39578. bpf2Count = pConfig->channels / 2;
  39579. pHeapLayout->sizeInBytes = 0;
  39580. /* BPF 2 */
  39581. pHeapLayout->bpf2Offset = pHeapLayout->sizeInBytes;
  39582. for (ibpf2 = 0; ibpf2 < bpf2Count; ibpf2 += 1) {
  39583. size_t bpf2HeapSizeInBytes;
  39584. ma_bpf2_config bpf2Config = ma_bpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, 0.707107); /* <-- The "q" parameter does not matter for the purpose of calculating the heap size. */
  39585. result = ma_bpf2_get_heap_size(&bpf2Config, &bpf2HeapSizeInBytes);
  39586. if (result != MA_SUCCESS) {
  39587. return result;
  39588. }
  39589. pHeapLayout->sizeInBytes += sizeof(ma_bpf2) + bpf2HeapSizeInBytes;
  39590. }
  39591. /* Make sure allocation size is aligned. */
  39592. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  39593. return MA_SUCCESS;
  39594. }
  39595. static ma_result ma_bpf_reinit__internal(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF, ma_bool32 isNew)
  39596. {
  39597. ma_result result;
  39598. ma_uint32 bpf2Count;
  39599. ma_uint32 ibpf2;
  39600. ma_bpf_heap_layout heapLayout; /* Only used if isNew is true. */
  39601. if (pBPF == NULL || pConfig == NULL) {
  39602. return MA_INVALID_ARGS;
  39603. }
  39604. /* Only supporting f32 and s16. */
  39605. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  39606. return MA_INVALID_ARGS;
  39607. }
  39608. /* The format cannot be changed after initialization. */
  39609. if (pBPF->format != ma_format_unknown && pBPF->format != pConfig->format) {
  39610. return MA_INVALID_OPERATION;
  39611. }
  39612. /* The channel count cannot be changed after initialization. */
  39613. if (pBPF->channels != 0 && pBPF->channels != pConfig->channels) {
  39614. return MA_INVALID_OPERATION;
  39615. }
  39616. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  39617. return MA_INVALID_ARGS;
  39618. }
  39619. /* We must have an even number of order. */
  39620. if ((pConfig->order & 0x1) != 0) {
  39621. return MA_INVALID_ARGS;
  39622. }
  39623. bpf2Count = pConfig->order / 2;
  39624. /* The filter order can't change between reinits. */
  39625. if (!isNew) {
  39626. if (pBPF->bpf2Count != bpf2Count) {
  39627. return MA_INVALID_OPERATION;
  39628. }
  39629. }
  39630. if (isNew) {
  39631. result = ma_bpf_get_heap_layout(pConfig, &heapLayout);
  39632. if (result != MA_SUCCESS) {
  39633. return result;
  39634. }
  39635. pBPF->_pHeap = pHeap;
  39636. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  39637. pBPF->pBPF2 = (ma_bpf2*)ma_offset_ptr(pHeap, heapLayout.bpf2Offset);
  39638. } else {
  39639. MA_ZERO_OBJECT(&heapLayout);
  39640. }
  39641. for (ibpf2 = 0; ibpf2 < bpf2Count; ibpf2 += 1) {
  39642. ma_bpf2_config bpf2Config;
  39643. double q;
  39644. /* TODO: Calculate Q to make this a proper Butterworth filter. */
  39645. q = 0.707107;
  39646. bpf2Config = ma_bpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
  39647. if (isNew) {
  39648. size_t bpf2HeapSizeInBytes;
  39649. result = ma_bpf2_get_heap_size(&bpf2Config, &bpf2HeapSizeInBytes);
  39650. if (result == MA_SUCCESS) {
  39651. result = ma_bpf2_init_preallocated(&bpf2Config, ma_offset_ptr(pHeap, heapLayout.bpf2Offset + (sizeof(ma_bpf2) * bpf2Count) + (ibpf2 * bpf2HeapSizeInBytes)), &pBPF->pBPF2[ibpf2]);
  39652. }
  39653. } else {
  39654. result = ma_bpf2_reinit(&bpf2Config, &pBPF->pBPF2[ibpf2]);
  39655. }
  39656. if (result != MA_SUCCESS) {
  39657. return result;
  39658. }
  39659. }
  39660. pBPF->bpf2Count = bpf2Count;
  39661. pBPF->format = pConfig->format;
  39662. pBPF->channels = pConfig->channels;
  39663. return MA_SUCCESS;
  39664. }
  39665. MA_API ma_result ma_bpf_get_heap_size(const ma_bpf_config* pConfig, size_t* pHeapSizeInBytes)
  39666. {
  39667. ma_result result;
  39668. ma_bpf_heap_layout heapLayout;
  39669. if (pHeapSizeInBytes == NULL) {
  39670. return MA_INVALID_ARGS;
  39671. }
  39672. *pHeapSizeInBytes = 0;
  39673. result = ma_bpf_get_heap_layout(pConfig, &heapLayout);
  39674. if (result != MA_SUCCESS) {
  39675. return result;
  39676. }
  39677. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  39678. return MA_SUCCESS;
  39679. }
  39680. MA_API ma_result ma_bpf_init_preallocated(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF)
  39681. {
  39682. if (pBPF == NULL) {
  39683. return MA_INVALID_ARGS;
  39684. }
  39685. MA_ZERO_OBJECT(pBPF);
  39686. return ma_bpf_reinit__internal(pConfig, pHeap, pBPF, /*isNew*/MA_TRUE);
  39687. }
  39688. MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf* pBPF)
  39689. {
  39690. ma_result result;
  39691. size_t heapSizeInBytes;
  39692. void* pHeap;
  39693. result = ma_bpf_get_heap_size(pConfig, &heapSizeInBytes);
  39694. if (result != MA_SUCCESS) {
  39695. return result;
  39696. }
  39697. if (heapSizeInBytes > 0) {
  39698. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39699. if (pHeap == NULL) {
  39700. return MA_OUT_OF_MEMORY;
  39701. }
  39702. } else {
  39703. pHeap = NULL;
  39704. }
  39705. result = ma_bpf_init_preallocated(pConfig, pHeap, pBPF);
  39706. if (result != MA_SUCCESS) {
  39707. ma_free(pHeap, pAllocationCallbacks);
  39708. return result;
  39709. }
  39710. pBPF->_ownsHeap = MA_TRUE;
  39711. return MA_SUCCESS;
  39712. }
  39713. MA_API void ma_bpf_uninit(ma_bpf* pBPF, const ma_allocation_callbacks* pAllocationCallbacks)
  39714. {
  39715. ma_uint32 ibpf2;
  39716. if (pBPF == NULL) {
  39717. return;
  39718. }
  39719. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  39720. ma_bpf2_uninit(&pBPF->pBPF2[ibpf2], pAllocationCallbacks);
  39721. }
  39722. if (pBPF->_ownsHeap) {
  39723. ma_free(pBPF->_pHeap, pAllocationCallbacks);
  39724. }
  39725. }
  39726. MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF)
  39727. {
  39728. return ma_bpf_reinit__internal(pConfig, NULL, pBPF, /*isNew*/MA_FALSE);
  39729. }
  39730. MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39731. {
  39732. ma_result result;
  39733. ma_uint32 ibpf2;
  39734. if (pBPF == NULL) {
  39735. return MA_INVALID_ARGS;
  39736. }
  39737. /* Faster path for in-place. */
  39738. if (pFramesOut == pFramesIn) {
  39739. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  39740. result = ma_bpf2_process_pcm_frames(&pBPF->pBPF2[ibpf2], pFramesOut, pFramesOut, frameCount);
  39741. if (result != MA_SUCCESS) {
  39742. return result;
  39743. }
  39744. }
  39745. }
  39746. /* Slightly slower path for copying. */
  39747. if (pFramesOut != pFramesIn) {
  39748. ma_uint32 iFrame;
  39749. /* */ if (pBPF->format == ma_format_f32) {
  39750. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  39751. const float* pFramesInF32 = (const float*)pFramesIn;
  39752. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39753. MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pBPF->format, pBPF->channels));
  39754. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  39755. ma_bpf2_process_pcm_frame_f32(&pBPF->pBPF2[ibpf2], pFramesOutF32, pFramesOutF32);
  39756. }
  39757. pFramesOutF32 += pBPF->channels;
  39758. pFramesInF32 += pBPF->channels;
  39759. }
  39760. } else if (pBPF->format == ma_format_s16) {
  39761. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  39762. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  39763. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39764. MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pBPF->format, pBPF->channels));
  39765. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  39766. ma_bpf2_process_pcm_frame_s16(&pBPF->pBPF2[ibpf2], pFramesOutS16, pFramesOutS16);
  39767. }
  39768. pFramesOutS16 += pBPF->channels;
  39769. pFramesInS16 += pBPF->channels;
  39770. }
  39771. } else {
  39772. MA_ASSERT(MA_FALSE);
  39773. return MA_INVALID_OPERATION; /* Should never hit this. */
  39774. }
  39775. }
  39776. return MA_SUCCESS;
  39777. }
  39778. MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF)
  39779. {
  39780. if (pBPF == NULL) {
  39781. return 0;
  39782. }
  39783. return pBPF->bpf2Count*2;
  39784. }
  39785. /**************************************************************************************************************************************************************
  39786. Notching Filter
  39787. **************************************************************************************************************************************************************/
  39788. MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency)
  39789. {
  39790. ma_notch2_config config;
  39791. MA_ZERO_OBJECT(&config);
  39792. config.format = format;
  39793. config.channels = channels;
  39794. config.sampleRate = sampleRate;
  39795. config.q = q;
  39796. config.frequency = frequency;
  39797. if (config.q == 0) {
  39798. config.q = 0.707107;
  39799. }
  39800. return config;
  39801. }
  39802. static MA_INLINE ma_biquad_config ma_notch2__get_biquad_config(const ma_notch2_config* pConfig)
  39803. {
  39804. ma_biquad_config bqConfig;
  39805. double q;
  39806. double w;
  39807. double s;
  39808. double c;
  39809. double a;
  39810. MA_ASSERT(pConfig != NULL);
  39811. q = pConfig->q;
  39812. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  39813. s = ma_sind(w);
  39814. c = ma_cosd(w);
  39815. a = s / (2*q);
  39816. bqConfig.b0 = 1;
  39817. bqConfig.b1 = -2 * c;
  39818. bqConfig.b2 = 1;
  39819. bqConfig.a0 = 1 + a;
  39820. bqConfig.a1 = -2 * c;
  39821. bqConfig.a2 = 1 - a;
  39822. bqConfig.format = pConfig->format;
  39823. bqConfig.channels = pConfig->channels;
  39824. return bqConfig;
  39825. }
  39826. MA_API ma_result ma_notch2_get_heap_size(const ma_notch2_config* pConfig, size_t* pHeapSizeInBytes)
  39827. {
  39828. ma_biquad_config bqConfig;
  39829. bqConfig = ma_notch2__get_biquad_config(pConfig);
  39830. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39831. }
  39832. MA_API ma_result ma_notch2_init_preallocated(const ma_notch2_config* pConfig, void* pHeap, ma_notch2* pFilter)
  39833. {
  39834. ma_result result;
  39835. ma_biquad_config bqConfig;
  39836. if (pFilter == NULL) {
  39837. return MA_INVALID_ARGS;
  39838. }
  39839. MA_ZERO_OBJECT(pFilter);
  39840. if (pConfig == NULL) {
  39841. return MA_INVALID_ARGS;
  39842. }
  39843. bqConfig = ma_notch2__get_biquad_config(pConfig);
  39844. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  39845. if (result != MA_SUCCESS) {
  39846. return result;
  39847. }
  39848. return MA_SUCCESS;
  39849. }
  39850. MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch2* pFilter)
  39851. {
  39852. ma_result result;
  39853. size_t heapSizeInBytes;
  39854. void* pHeap;
  39855. result = ma_notch2_get_heap_size(pConfig, &heapSizeInBytes);
  39856. if (result != MA_SUCCESS) {
  39857. return result;
  39858. }
  39859. if (heapSizeInBytes > 0) {
  39860. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39861. if (pHeap == NULL) {
  39862. return MA_OUT_OF_MEMORY;
  39863. }
  39864. } else {
  39865. pHeap = NULL;
  39866. }
  39867. result = ma_notch2_init_preallocated(pConfig, pHeap, pFilter);
  39868. if (result != MA_SUCCESS) {
  39869. ma_free(pHeap, pAllocationCallbacks);
  39870. return result;
  39871. }
  39872. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39873. return MA_SUCCESS;
  39874. }
  39875. MA_API void ma_notch2_uninit(ma_notch2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  39876. {
  39877. if (pFilter == NULL) {
  39878. return;
  39879. }
  39880. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  39881. }
  39882. MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter)
  39883. {
  39884. ma_result result;
  39885. ma_biquad_config bqConfig;
  39886. if (pFilter == NULL || pConfig == NULL) {
  39887. return MA_INVALID_ARGS;
  39888. }
  39889. bqConfig = ma_notch2__get_biquad_config(pConfig);
  39890. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  39891. if (result != MA_SUCCESS) {
  39892. return result;
  39893. }
  39894. return MA_SUCCESS;
  39895. }
  39896. static MA_INLINE void ma_notch2_process_pcm_frame_s16(ma_notch2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  39897. {
  39898. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  39899. }
  39900. static MA_INLINE void ma_notch2_process_pcm_frame_f32(ma_notch2* pFilter, float* pFrameOut, const float* pFrameIn)
  39901. {
  39902. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  39903. }
  39904. MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39905. {
  39906. if (pFilter == NULL) {
  39907. return MA_INVALID_ARGS;
  39908. }
  39909. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  39910. }
  39911. MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter)
  39912. {
  39913. if (pFilter == NULL) {
  39914. return 0;
  39915. }
  39916. return ma_biquad_get_latency(&pFilter->bq);
  39917. }
  39918. /**************************************************************************************************************************************************************
  39919. Peaking EQ Filter
  39920. **************************************************************************************************************************************************************/
  39921. MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  39922. {
  39923. ma_peak2_config config;
  39924. MA_ZERO_OBJECT(&config);
  39925. config.format = format;
  39926. config.channels = channels;
  39927. config.sampleRate = sampleRate;
  39928. config.gainDB = gainDB;
  39929. config.q = q;
  39930. config.frequency = frequency;
  39931. if (config.q == 0) {
  39932. config.q = 0.707107;
  39933. }
  39934. return config;
  39935. }
  39936. static MA_INLINE ma_biquad_config ma_peak2__get_biquad_config(const ma_peak2_config* pConfig)
  39937. {
  39938. ma_biquad_config bqConfig;
  39939. double q;
  39940. double w;
  39941. double s;
  39942. double c;
  39943. double a;
  39944. double A;
  39945. MA_ASSERT(pConfig != NULL);
  39946. q = pConfig->q;
  39947. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  39948. s = ma_sind(w);
  39949. c = ma_cosd(w);
  39950. a = s / (2*q);
  39951. A = ma_powd(10, (pConfig->gainDB / 40));
  39952. bqConfig.b0 = 1 + (a * A);
  39953. bqConfig.b1 = -2 * c;
  39954. bqConfig.b2 = 1 - (a * A);
  39955. bqConfig.a0 = 1 + (a / A);
  39956. bqConfig.a1 = -2 * c;
  39957. bqConfig.a2 = 1 - (a / A);
  39958. bqConfig.format = pConfig->format;
  39959. bqConfig.channels = pConfig->channels;
  39960. return bqConfig;
  39961. }
  39962. MA_API ma_result ma_peak2_get_heap_size(const ma_peak2_config* pConfig, size_t* pHeapSizeInBytes)
  39963. {
  39964. ma_biquad_config bqConfig;
  39965. bqConfig = ma_peak2__get_biquad_config(pConfig);
  39966. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39967. }
  39968. MA_API ma_result ma_peak2_init_preallocated(const ma_peak2_config* pConfig, void* pHeap, ma_peak2* pFilter)
  39969. {
  39970. ma_result result;
  39971. ma_biquad_config bqConfig;
  39972. if (pFilter == NULL) {
  39973. return MA_INVALID_ARGS;
  39974. }
  39975. MA_ZERO_OBJECT(pFilter);
  39976. if (pConfig == NULL) {
  39977. return MA_INVALID_ARGS;
  39978. }
  39979. bqConfig = ma_peak2__get_biquad_config(pConfig);
  39980. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  39981. if (result != MA_SUCCESS) {
  39982. return result;
  39983. }
  39984. return MA_SUCCESS;
  39985. }
  39986. MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak2* pFilter)
  39987. {
  39988. ma_result result;
  39989. size_t heapSizeInBytes;
  39990. void* pHeap;
  39991. result = ma_peak2_get_heap_size(pConfig, &heapSizeInBytes);
  39992. if (result != MA_SUCCESS) {
  39993. return result;
  39994. }
  39995. if (heapSizeInBytes > 0) {
  39996. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39997. if (pHeap == NULL) {
  39998. return MA_OUT_OF_MEMORY;
  39999. }
  40000. } else {
  40001. pHeap = NULL;
  40002. }
  40003. result = ma_peak2_init_preallocated(pConfig, pHeap, pFilter);
  40004. if (result != MA_SUCCESS) {
  40005. ma_free(pHeap, pAllocationCallbacks);
  40006. return result;
  40007. }
  40008. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  40009. return MA_SUCCESS;
  40010. }
  40011. MA_API void ma_peak2_uninit(ma_peak2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  40012. {
  40013. if (pFilter == NULL) {
  40014. return;
  40015. }
  40016. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  40017. }
  40018. MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter)
  40019. {
  40020. ma_result result;
  40021. ma_biquad_config bqConfig;
  40022. if (pFilter == NULL || pConfig == NULL) {
  40023. return MA_INVALID_ARGS;
  40024. }
  40025. bqConfig = ma_peak2__get_biquad_config(pConfig);
  40026. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  40027. if (result != MA_SUCCESS) {
  40028. return result;
  40029. }
  40030. return MA_SUCCESS;
  40031. }
  40032. static MA_INLINE void ma_peak2_process_pcm_frame_s16(ma_peak2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  40033. {
  40034. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  40035. }
  40036. static MA_INLINE void ma_peak2_process_pcm_frame_f32(ma_peak2* pFilter, float* pFrameOut, const float* pFrameIn)
  40037. {
  40038. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  40039. }
  40040. MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40041. {
  40042. if (pFilter == NULL) {
  40043. return MA_INVALID_ARGS;
  40044. }
  40045. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  40046. }
  40047. MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter)
  40048. {
  40049. if (pFilter == NULL) {
  40050. return 0;
  40051. }
  40052. return ma_biquad_get_latency(&pFilter->bq);
  40053. }
  40054. /**************************************************************************************************************************************************************
  40055. Low Shelf Filter
  40056. **************************************************************************************************************************************************************/
  40057. MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency)
  40058. {
  40059. ma_loshelf2_config config;
  40060. MA_ZERO_OBJECT(&config);
  40061. config.format = format;
  40062. config.channels = channels;
  40063. config.sampleRate = sampleRate;
  40064. config.gainDB = gainDB;
  40065. config.shelfSlope = shelfSlope;
  40066. config.frequency = frequency;
  40067. return config;
  40068. }
  40069. static MA_INLINE ma_biquad_config ma_loshelf2__get_biquad_config(const ma_loshelf2_config* pConfig)
  40070. {
  40071. ma_biquad_config bqConfig;
  40072. double w;
  40073. double s;
  40074. double c;
  40075. double A;
  40076. double S;
  40077. double a;
  40078. double sqrtA;
  40079. MA_ASSERT(pConfig != NULL);
  40080. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  40081. s = ma_sind(w);
  40082. c = ma_cosd(w);
  40083. A = ma_powd(10, (pConfig->gainDB / 40));
  40084. S = pConfig->shelfSlope;
  40085. a = s/2 * ma_sqrtd((A + 1/A) * (1/S - 1) + 2);
  40086. sqrtA = 2*ma_sqrtd(A)*a;
  40087. bqConfig.b0 = A * ((A + 1) - (A - 1)*c + sqrtA);
  40088. bqConfig.b1 = 2 * A * ((A - 1) - (A + 1)*c);
  40089. bqConfig.b2 = A * ((A + 1) - (A - 1)*c - sqrtA);
  40090. bqConfig.a0 = (A + 1) + (A - 1)*c + sqrtA;
  40091. bqConfig.a1 = -2 * ((A - 1) + (A + 1)*c);
  40092. bqConfig.a2 = (A + 1) + (A - 1)*c - sqrtA;
  40093. bqConfig.format = pConfig->format;
  40094. bqConfig.channels = pConfig->channels;
  40095. return bqConfig;
  40096. }
  40097. MA_API ma_result ma_loshelf2_get_heap_size(const ma_loshelf2_config* pConfig, size_t* pHeapSizeInBytes)
  40098. {
  40099. ma_biquad_config bqConfig;
  40100. bqConfig = ma_loshelf2__get_biquad_config(pConfig);
  40101. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  40102. }
  40103. MA_API ma_result ma_loshelf2_init_preallocated(const ma_loshelf2_config* pConfig, void* pHeap, ma_loshelf2* pFilter)
  40104. {
  40105. ma_result result;
  40106. ma_biquad_config bqConfig;
  40107. if (pFilter == NULL) {
  40108. return MA_INVALID_ARGS;
  40109. }
  40110. MA_ZERO_OBJECT(pFilter);
  40111. if (pConfig == NULL) {
  40112. return MA_INVALID_ARGS;
  40113. }
  40114. bqConfig = ma_loshelf2__get_biquad_config(pConfig);
  40115. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  40116. if (result != MA_SUCCESS) {
  40117. return result;
  40118. }
  40119. return MA_SUCCESS;
  40120. }
  40121. MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf2* pFilter)
  40122. {
  40123. ma_result result;
  40124. size_t heapSizeInBytes;
  40125. void* pHeap;
  40126. result = ma_loshelf2_get_heap_size(pConfig, &heapSizeInBytes);
  40127. if (result != MA_SUCCESS) {
  40128. return result;
  40129. }
  40130. if (heapSizeInBytes > 0) {
  40131. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  40132. if (pHeap == NULL) {
  40133. return MA_OUT_OF_MEMORY;
  40134. }
  40135. } else {
  40136. pHeap = NULL;
  40137. }
  40138. result = ma_loshelf2_init_preallocated(pConfig, pHeap, pFilter);
  40139. if (result != MA_SUCCESS) {
  40140. ma_free(pHeap, pAllocationCallbacks);
  40141. return result;
  40142. }
  40143. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  40144. return MA_SUCCESS;
  40145. }
  40146. MA_API void ma_loshelf2_uninit(ma_loshelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  40147. {
  40148. if (pFilter == NULL) {
  40149. return;
  40150. }
  40151. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  40152. }
  40153. MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter)
  40154. {
  40155. ma_result result;
  40156. ma_biquad_config bqConfig;
  40157. if (pFilter == NULL || pConfig == NULL) {
  40158. return MA_INVALID_ARGS;
  40159. }
  40160. bqConfig = ma_loshelf2__get_biquad_config(pConfig);
  40161. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  40162. if (result != MA_SUCCESS) {
  40163. return result;
  40164. }
  40165. return MA_SUCCESS;
  40166. }
  40167. static MA_INLINE void ma_loshelf2_process_pcm_frame_s16(ma_loshelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  40168. {
  40169. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  40170. }
  40171. static MA_INLINE void ma_loshelf2_process_pcm_frame_f32(ma_loshelf2* pFilter, float* pFrameOut, const float* pFrameIn)
  40172. {
  40173. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  40174. }
  40175. MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40176. {
  40177. if (pFilter == NULL) {
  40178. return MA_INVALID_ARGS;
  40179. }
  40180. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  40181. }
  40182. MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter)
  40183. {
  40184. if (pFilter == NULL) {
  40185. return 0;
  40186. }
  40187. return ma_biquad_get_latency(&pFilter->bq);
  40188. }
  40189. /**************************************************************************************************************************************************************
  40190. High Shelf Filter
  40191. **************************************************************************************************************************************************************/
  40192. MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency)
  40193. {
  40194. ma_hishelf2_config config;
  40195. MA_ZERO_OBJECT(&config);
  40196. config.format = format;
  40197. config.channels = channels;
  40198. config.sampleRate = sampleRate;
  40199. config.gainDB = gainDB;
  40200. config.shelfSlope = shelfSlope;
  40201. config.frequency = frequency;
  40202. return config;
  40203. }
  40204. static MA_INLINE ma_biquad_config ma_hishelf2__get_biquad_config(const ma_hishelf2_config* pConfig)
  40205. {
  40206. ma_biquad_config bqConfig;
  40207. double w;
  40208. double s;
  40209. double c;
  40210. double A;
  40211. double S;
  40212. double a;
  40213. double sqrtA;
  40214. MA_ASSERT(pConfig != NULL);
  40215. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  40216. s = ma_sind(w);
  40217. c = ma_cosd(w);
  40218. A = ma_powd(10, (pConfig->gainDB / 40));
  40219. S = pConfig->shelfSlope;
  40220. a = s/2 * ma_sqrtd((A + 1/A) * (1/S - 1) + 2);
  40221. sqrtA = 2*ma_sqrtd(A)*a;
  40222. bqConfig.b0 = A * ((A + 1) + (A - 1)*c + sqrtA);
  40223. bqConfig.b1 = -2 * A * ((A - 1) + (A + 1)*c);
  40224. bqConfig.b2 = A * ((A + 1) + (A - 1)*c - sqrtA);
  40225. bqConfig.a0 = (A + 1) - (A - 1)*c + sqrtA;
  40226. bqConfig.a1 = 2 * ((A - 1) - (A + 1)*c);
  40227. bqConfig.a2 = (A + 1) - (A - 1)*c - sqrtA;
  40228. bqConfig.format = pConfig->format;
  40229. bqConfig.channels = pConfig->channels;
  40230. return bqConfig;
  40231. }
  40232. MA_API ma_result ma_hishelf2_get_heap_size(const ma_hishelf2_config* pConfig, size_t* pHeapSizeInBytes)
  40233. {
  40234. ma_biquad_config bqConfig;
  40235. bqConfig = ma_hishelf2__get_biquad_config(pConfig);
  40236. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  40237. }
  40238. MA_API ma_result ma_hishelf2_init_preallocated(const ma_hishelf2_config* pConfig, void* pHeap, ma_hishelf2* pFilter)
  40239. {
  40240. ma_result result;
  40241. ma_biquad_config bqConfig;
  40242. if (pFilter == NULL) {
  40243. return MA_INVALID_ARGS;
  40244. }
  40245. MA_ZERO_OBJECT(pFilter);
  40246. if (pConfig == NULL) {
  40247. return MA_INVALID_ARGS;
  40248. }
  40249. bqConfig = ma_hishelf2__get_biquad_config(pConfig);
  40250. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  40251. if (result != MA_SUCCESS) {
  40252. return result;
  40253. }
  40254. return MA_SUCCESS;
  40255. }
  40256. MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf2* pFilter)
  40257. {
  40258. ma_result result;
  40259. size_t heapSizeInBytes;
  40260. void* pHeap;
  40261. result = ma_hishelf2_get_heap_size(pConfig, &heapSizeInBytes);
  40262. if (result != MA_SUCCESS) {
  40263. return result;
  40264. }
  40265. if (heapSizeInBytes > 0) {
  40266. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  40267. if (pHeap == NULL) {
  40268. return MA_OUT_OF_MEMORY;
  40269. }
  40270. } else {
  40271. pHeap = NULL;
  40272. }
  40273. result = ma_hishelf2_init_preallocated(pConfig, pHeap, pFilter);
  40274. if (result != MA_SUCCESS) {
  40275. ma_free(pHeap, pAllocationCallbacks);
  40276. return result;
  40277. }
  40278. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  40279. return MA_SUCCESS;
  40280. }
  40281. MA_API void ma_hishelf2_uninit(ma_hishelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  40282. {
  40283. if (pFilter == NULL) {
  40284. return;
  40285. }
  40286. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  40287. }
  40288. MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter)
  40289. {
  40290. ma_result result;
  40291. ma_biquad_config bqConfig;
  40292. if (pFilter == NULL || pConfig == NULL) {
  40293. return MA_INVALID_ARGS;
  40294. }
  40295. bqConfig = ma_hishelf2__get_biquad_config(pConfig);
  40296. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  40297. if (result != MA_SUCCESS) {
  40298. return result;
  40299. }
  40300. return MA_SUCCESS;
  40301. }
  40302. static MA_INLINE void ma_hishelf2_process_pcm_frame_s16(ma_hishelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  40303. {
  40304. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  40305. }
  40306. static MA_INLINE void ma_hishelf2_process_pcm_frame_f32(ma_hishelf2* pFilter, float* pFrameOut, const float* pFrameIn)
  40307. {
  40308. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  40309. }
  40310. MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40311. {
  40312. if (pFilter == NULL) {
  40313. return MA_INVALID_ARGS;
  40314. }
  40315. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  40316. }
  40317. MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter)
  40318. {
  40319. if (pFilter == NULL) {
  40320. return 0;
  40321. }
  40322. return ma_biquad_get_latency(&pFilter->bq);
  40323. }
  40324. /*
  40325. Delay
  40326. */
  40327. MA_API ma_delay_config ma_delay_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay)
  40328. {
  40329. ma_delay_config config;
  40330. MA_ZERO_OBJECT(&config);
  40331. config.channels = channels;
  40332. config.sampleRate = sampleRate;
  40333. config.delayInFrames = delayInFrames;
  40334. config.delayStart = (decay == 0) ? MA_TRUE : MA_FALSE; /* Delay the start if it looks like we're not configuring an echo. */
  40335. config.wet = 1;
  40336. config.dry = 1;
  40337. config.decay = decay;
  40338. return config;
  40339. }
  40340. MA_API ma_result ma_delay_init(const ma_delay_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay* pDelay)
  40341. {
  40342. if (pDelay == NULL) {
  40343. return MA_INVALID_ARGS;
  40344. }
  40345. MA_ZERO_OBJECT(pDelay);
  40346. if (pConfig == NULL) {
  40347. return MA_INVALID_ARGS;
  40348. }
  40349. if (pConfig->decay < 0 || pConfig->decay > 1) {
  40350. return MA_INVALID_ARGS;
  40351. }
  40352. pDelay->config = *pConfig;
  40353. pDelay->bufferSizeInFrames = pConfig->delayInFrames;
  40354. pDelay->cursor = 0;
  40355. pDelay->pBuffer = (float*)ma_malloc((size_t)(pDelay->bufferSizeInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->channels)), pAllocationCallbacks);
  40356. if (pDelay->pBuffer == NULL) {
  40357. return MA_OUT_OF_MEMORY;
  40358. }
  40359. ma_silence_pcm_frames(pDelay->pBuffer, pDelay->bufferSizeInFrames, ma_format_f32, pConfig->channels);
  40360. return MA_SUCCESS;
  40361. }
  40362. MA_API void ma_delay_uninit(ma_delay* pDelay, const ma_allocation_callbacks* pAllocationCallbacks)
  40363. {
  40364. if (pDelay == NULL) {
  40365. return;
  40366. }
  40367. ma_free(pDelay->pBuffer, pAllocationCallbacks);
  40368. }
  40369. MA_API ma_result ma_delay_process_pcm_frames(ma_delay* pDelay, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  40370. {
  40371. ma_uint32 iFrame;
  40372. ma_uint32 iChannel;
  40373. float* pFramesOutF32 = (float*)pFramesOut;
  40374. const float* pFramesInF32 = (const float*)pFramesIn;
  40375. if (pDelay == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  40376. return MA_INVALID_ARGS;
  40377. }
  40378. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40379. for (iChannel = 0; iChannel < pDelay->config.channels; iChannel += 1) {
  40380. ma_uint32 iBuffer = (pDelay->cursor * pDelay->config.channels) + iChannel;
  40381. if (pDelay->config.delayStart) {
  40382. /* Delayed start. */
  40383. /* Read */
  40384. pFramesOutF32[iChannel] = pDelay->pBuffer[iBuffer] * pDelay->config.wet;
  40385. /* Feedback */
  40386. pDelay->pBuffer[iBuffer] = (pDelay->pBuffer[iBuffer] * pDelay->config.decay) + (pFramesInF32[iChannel] * pDelay->config.dry);
  40387. } else {
  40388. /* Immediate start */
  40389. /* Feedback */
  40390. pDelay->pBuffer[iBuffer] = (pDelay->pBuffer[iBuffer] * pDelay->config.decay) + (pFramesInF32[iChannel] * pDelay->config.dry);
  40391. /* Read */
  40392. pFramesOutF32[iChannel] = pDelay->pBuffer[iBuffer] * pDelay->config.wet;
  40393. }
  40394. }
  40395. pDelay->cursor = (pDelay->cursor + 1) % pDelay->bufferSizeInFrames;
  40396. pFramesOutF32 += pDelay->config.channels;
  40397. pFramesInF32 += pDelay->config.channels;
  40398. }
  40399. return MA_SUCCESS;
  40400. }
  40401. MA_API void ma_delay_set_wet(ma_delay* pDelay, float value)
  40402. {
  40403. if (pDelay == NULL) {
  40404. return;
  40405. }
  40406. pDelay->config.wet = value;
  40407. }
  40408. MA_API float ma_delay_get_wet(const ma_delay* pDelay)
  40409. {
  40410. if (pDelay == NULL) {
  40411. return 0;
  40412. }
  40413. return pDelay->config.wet;
  40414. }
  40415. MA_API void ma_delay_set_dry(ma_delay* pDelay, float value)
  40416. {
  40417. if (pDelay == NULL) {
  40418. return;
  40419. }
  40420. pDelay->config.dry = value;
  40421. }
  40422. MA_API float ma_delay_get_dry(const ma_delay* pDelay)
  40423. {
  40424. if (pDelay == NULL) {
  40425. return 0;
  40426. }
  40427. return pDelay->config.dry;
  40428. }
  40429. MA_API void ma_delay_set_decay(ma_delay* pDelay, float value)
  40430. {
  40431. if (pDelay == NULL) {
  40432. return;
  40433. }
  40434. pDelay->config.decay = value;
  40435. }
  40436. MA_API float ma_delay_get_decay(const ma_delay* pDelay)
  40437. {
  40438. if (pDelay == NULL) {
  40439. return 0;
  40440. }
  40441. return pDelay->config.decay;
  40442. }
  40443. MA_API ma_gainer_config ma_gainer_config_init(ma_uint32 channels, ma_uint32 smoothTimeInFrames)
  40444. {
  40445. ma_gainer_config config;
  40446. MA_ZERO_OBJECT(&config);
  40447. config.channels = channels;
  40448. config.smoothTimeInFrames = smoothTimeInFrames;
  40449. return config;
  40450. }
  40451. typedef struct
  40452. {
  40453. size_t sizeInBytes;
  40454. size_t oldGainsOffset;
  40455. size_t newGainsOffset;
  40456. } ma_gainer_heap_layout;
  40457. static ma_result ma_gainer_get_heap_layout(const ma_gainer_config* pConfig, ma_gainer_heap_layout* pHeapLayout)
  40458. {
  40459. MA_ASSERT(pHeapLayout != NULL);
  40460. MA_ZERO_OBJECT(pHeapLayout);
  40461. if (pConfig == NULL) {
  40462. return MA_INVALID_ARGS;
  40463. }
  40464. if (pConfig->channels == 0) {
  40465. return MA_INVALID_ARGS;
  40466. }
  40467. pHeapLayout->sizeInBytes = 0;
  40468. /* Old gains. */
  40469. pHeapLayout->oldGainsOffset = pHeapLayout->sizeInBytes;
  40470. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  40471. /* New gains. */
  40472. pHeapLayout->newGainsOffset = pHeapLayout->sizeInBytes;
  40473. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  40474. /* Alignment. */
  40475. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  40476. return MA_SUCCESS;
  40477. }
  40478. MA_API ma_result ma_gainer_get_heap_size(const ma_gainer_config* pConfig, size_t* pHeapSizeInBytes)
  40479. {
  40480. ma_result result;
  40481. ma_gainer_heap_layout heapLayout;
  40482. if (pHeapSizeInBytes == NULL) {
  40483. return MA_INVALID_ARGS;
  40484. }
  40485. *pHeapSizeInBytes = 0;
  40486. result = ma_gainer_get_heap_layout(pConfig, &heapLayout);
  40487. if (result != MA_SUCCESS) {
  40488. return MA_INVALID_ARGS;
  40489. }
  40490. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  40491. return MA_SUCCESS;
  40492. }
  40493. MA_API ma_result ma_gainer_init_preallocated(const ma_gainer_config* pConfig, void* pHeap, ma_gainer* pGainer)
  40494. {
  40495. ma_result result;
  40496. ma_gainer_heap_layout heapLayout;
  40497. ma_uint32 iChannel;
  40498. if (pGainer == NULL) {
  40499. return MA_INVALID_ARGS;
  40500. }
  40501. MA_ZERO_OBJECT(pGainer);
  40502. if (pConfig == NULL || pHeap == NULL) {
  40503. return MA_INVALID_ARGS;
  40504. }
  40505. result = ma_gainer_get_heap_layout(pConfig, &heapLayout);
  40506. if (result != MA_SUCCESS) {
  40507. return result;
  40508. }
  40509. pGainer->_pHeap = pHeap;
  40510. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  40511. pGainer->pOldGains = (float*)ma_offset_ptr(pHeap, heapLayout.oldGainsOffset);
  40512. pGainer->pNewGains = (float*)ma_offset_ptr(pHeap, heapLayout.newGainsOffset);
  40513. pGainer->masterVolume = 1;
  40514. pGainer->config = *pConfig;
  40515. pGainer->t = (ma_uint32)-1; /* No interpolation by default. */
  40516. for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
  40517. pGainer->pOldGains[iChannel] = 1;
  40518. pGainer->pNewGains[iChannel] = 1;
  40519. }
  40520. return MA_SUCCESS;
  40521. }
  40522. MA_API ma_result ma_gainer_init(const ma_gainer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_gainer* pGainer)
  40523. {
  40524. ma_result result;
  40525. size_t heapSizeInBytes;
  40526. void* pHeap;
  40527. result = ma_gainer_get_heap_size(pConfig, &heapSizeInBytes);
  40528. if (result != MA_SUCCESS) {
  40529. return result; /* Failed to retrieve the size of the heap allocation. */
  40530. }
  40531. if (heapSizeInBytes > 0) {
  40532. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  40533. if (pHeap == NULL) {
  40534. return MA_OUT_OF_MEMORY;
  40535. }
  40536. } else {
  40537. pHeap = NULL;
  40538. }
  40539. result = ma_gainer_init_preallocated(pConfig, pHeap, pGainer);
  40540. if (result != MA_SUCCESS) {
  40541. ma_free(pHeap, pAllocationCallbacks);
  40542. return result;
  40543. }
  40544. pGainer->_ownsHeap = MA_TRUE;
  40545. return MA_SUCCESS;
  40546. }
  40547. MA_API void ma_gainer_uninit(ma_gainer* pGainer, const ma_allocation_callbacks* pAllocationCallbacks)
  40548. {
  40549. if (pGainer == NULL) {
  40550. return;
  40551. }
  40552. if (pGainer->_ownsHeap) {
  40553. ma_free(pGainer->_pHeap, pAllocationCallbacks);
  40554. }
  40555. }
  40556. static float ma_gainer_calculate_current_gain(const ma_gainer* pGainer, ma_uint32 channel)
  40557. {
  40558. float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames;
  40559. return ma_mix_f32_fast(pGainer->pOldGains[channel], pGainer->pNewGains[channel], a);
  40560. }
  40561. static /*__attribute__((noinline))*/ ma_result ma_gainer_process_pcm_frames_internal(ma_gainer * pGainer, void* MA_RESTRICT pFramesOut, const void* MA_RESTRICT pFramesIn, ma_uint64 frameCount)
  40562. {
  40563. ma_uint64 iFrame;
  40564. ma_uint32 iChannel;
  40565. ma_uint64 interpolatedFrameCount;
  40566. MA_ASSERT(pGainer != NULL);
  40567. /*
  40568. We don't necessarily need to apply a linear interpolation for the entire frameCount frames. When
  40569. linear interpolation is not needed we can do a simple volume adjustment which will be more
  40570. efficient than a lerp with an alpha value of 1.
  40571. To do this, all we need to do is determine how many frames need to have a lerp applied. Then we
  40572. just process that number of frames with linear interpolation. After that we run on an optimized
  40573. path which just applies the new gains without a lerp.
  40574. */
  40575. if (pGainer->t >= pGainer->config.smoothTimeInFrames) {
  40576. interpolatedFrameCount = 0;
  40577. } else {
  40578. interpolatedFrameCount = pGainer->t - pGainer->config.smoothTimeInFrames;
  40579. if (interpolatedFrameCount > frameCount) {
  40580. interpolatedFrameCount = frameCount;
  40581. }
  40582. }
  40583. /*
  40584. Start off with our interpolated frames. When we do this, we'll adjust frameCount and our pointers
  40585. so that the fast path can work naturally without consideration of the interpolated path.
  40586. */
  40587. if (interpolatedFrameCount > 0) {
  40588. /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */
  40589. if (pFramesOut != NULL && pFramesIn != NULL) {
  40590. /*
  40591. All we're really doing here is moving the old gains towards the new gains. We don't want to
  40592. be modifying the gains inside the ma_gainer object because that will break things. Instead
  40593. we can make a copy here on the stack. For extreme channel counts we can fall back to a slower
  40594. implementation which just uses a standard lerp.
  40595. */
  40596. float* pFramesOutF32 = (float*)pFramesOut;
  40597. const float* pFramesInF32 = (const float*)pFramesIn;
  40598. float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames;
  40599. float d = 1.0f / pGainer->config.smoothTimeInFrames;
  40600. if (pGainer->config.channels <= 32) {
  40601. float pRunningGain[32];
  40602. float pRunningGainDelta[32]; /* Could this be heap-allocated as part of the ma_gainer object? */
  40603. /* Initialize the running gain. */
  40604. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40605. float t = (pGainer->pNewGains[iChannel] - pGainer->pOldGains[iChannel]) * pGainer->masterVolume;
  40606. pRunningGainDelta[iChannel] = t * d;
  40607. pRunningGain[iChannel] = (pGainer->pOldGains[iChannel] * pGainer->masterVolume) + (t * a);
  40608. }
  40609. iFrame = 0;
  40610. /* Optimized paths for common channel counts. This is mostly just experimenting with some SIMD ideas. It's not necessarily final. */
  40611. if (pGainer->config.channels == 2) {
  40612. #if defined(MA_SUPPORT_SSE2)
  40613. if (ma_has_sse2()) {
  40614. ma_uint64 unrolledLoopCount = interpolatedFrameCount >> 1;
  40615. /* Expand some arrays so we can have a clean SIMD loop below. */
  40616. __m128 runningGainDelta0 = _mm_set_ps(pRunningGainDelta[1], pRunningGainDelta[0], pRunningGainDelta[1], pRunningGainDelta[0]);
  40617. __m128 runningGain0 = _mm_set_ps(pRunningGain[1] + pRunningGainDelta[1], pRunningGain[0] + pRunningGainDelta[0], pRunningGain[1], pRunningGain[0]);
  40618. for (; iFrame < unrolledLoopCount; iFrame += 1) {
  40619. _mm_storeu_ps(&pFramesOutF32[iFrame*4 + 0], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*4 + 0]), runningGain0));
  40620. runningGain0 = _mm_add_ps(runningGain0, runningGainDelta0);
  40621. }
  40622. iFrame = unrolledLoopCount << 1;
  40623. } else
  40624. #endif
  40625. {
  40626. /*
  40627. Two different scalar implementations here. Clang (and I assume GCC) will vectorize
  40628. both of these, but the bottom version results in a nicer vectorization with less
  40629. instructions emitted. The problem, however, is that the bottom version runs slower
  40630. when compiled with MSVC. The top version will be partially vectorized by MSVC.
  40631. */
  40632. #if defined(_MSC_VER) && !defined(__clang__)
  40633. ma_uint64 unrolledLoopCount = interpolatedFrameCount >> 1;
  40634. /* Expand some arrays so we can have a clean 4x SIMD operation in the loop. */
  40635. pRunningGainDelta[2] = pRunningGainDelta[0];
  40636. pRunningGainDelta[3] = pRunningGainDelta[1];
  40637. pRunningGain[2] = pRunningGain[0] + pRunningGainDelta[0];
  40638. pRunningGain[3] = pRunningGain[1] + pRunningGainDelta[1];
  40639. for (; iFrame < unrolledLoopCount; iFrame += 1) {
  40640. pFramesOutF32[iFrame*4 + 0] = pFramesInF32[iFrame*4 + 0] * pRunningGain[0];
  40641. pFramesOutF32[iFrame*4 + 1] = pFramesInF32[iFrame*4 + 1] * pRunningGain[1];
  40642. pFramesOutF32[iFrame*4 + 2] = pFramesInF32[iFrame*4 + 2] * pRunningGain[2];
  40643. pFramesOutF32[iFrame*4 + 3] = pFramesInF32[iFrame*4 + 3] * pRunningGain[3];
  40644. /* Move the running gain forward towards the new gain. */
  40645. pRunningGain[0] += pRunningGainDelta[0];
  40646. pRunningGain[1] += pRunningGainDelta[1];
  40647. pRunningGain[2] += pRunningGainDelta[2];
  40648. pRunningGain[3] += pRunningGainDelta[3];
  40649. }
  40650. iFrame = unrolledLoopCount << 1;
  40651. #else
  40652. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40653. for (iChannel = 0; iChannel < 2; iChannel += 1) {
  40654. pFramesOutF32[iFrame*2 + iChannel] = pFramesInF32[iFrame*2 + iChannel] * pRunningGain[iChannel];
  40655. }
  40656. for (iChannel = 0; iChannel < 2; iChannel += 1) {
  40657. pRunningGain[iChannel] += pRunningGainDelta[iChannel];
  40658. }
  40659. }
  40660. #endif
  40661. }
  40662. } else if (pGainer->config.channels == 6) {
  40663. #if defined(MA_SUPPORT_SSE2)
  40664. if (ma_has_sse2()) {
  40665. /*
  40666. For 6 channels things are a bit more complicated because 6 isn't cleanly divisible by 4. We need to do 2 frames
  40667. at a time, meaning we'll be doing 12 samples in a group. Like the stereo case we'll need to expand some arrays
  40668. so we can do clean 4x SIMD operations.
  40669. */
  40670. ma_uint64 unrolledLoopCount = interpolatedFrameCount >> 1;
  40671. /* Expand some arrays so we can have a clean SIMD loop below. */
  40672. __m128 runningGainDelta0 = _mm_set_ps(pRunningGainDelta[3], pRunningGainDelta[2], pRunningGainDelta[1], pRunningGainDelta[0]);
  40673. __m128 runningGainDelta1 = _mm_set_ps(pRunningGainDelta[1], pRunningGainDelta[0], pRunningGainDelta[5], pRunningGainDelta[4]);
  40674. __m128 runningGainDelta2 = _mm_set_ps(pRunningGainDelta[5], pRunningGainDelta[4], pRunningGainDelta[3], pRunningGainDelta[2]);
  40675. __m128 runningGain0 = _mm_set_ps(pRunningGain[3], pRunningGain[2], pRunningGain[1], pRunningGain[0]);
  40676. __m128 runningGain1 = _mm_set_ps(pRunningGain[1] + pRunningGainDelta[1], pRunningGain[0] + pRunningGainDelta[0], pRunningGain[5], pRunningGain[4]);
  40677. __m128 runningGain2 = _mm_set_ps(pRunningGain[5] + pRunningGainDelta[5], pRunningGain[4] + pRunningGainDelta[4], pRunningGain[3] + pRunningGainDelta[3], pRunningGain[2] + pRunningGainDelta[2]);
  40678. for (; iFrame < unrolledLoopCount; iFrame += 1) {
  40679. _mm_storeu_ps(&pFramesOutF32[iFrame*12 + 0], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*12 + 0]), runningGain0));
  40680. _mm_storeu_ps(&pFramesOutF32[iFrame*12 + 4], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*12 + 4]), runningGain1));
  40681. _mm_storeu_ps(&pFramesOutF32[iFrame*12 + 8], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*12 + 8]), runningGain2));
  40682. runningGain0 = _mm_add_ps(runningGain0, runningGainDelta0);
  40683. runningGain1 = _mm_add_ps(runningGain1, runningGainDelta1);
  40684. runningGain2 = _mm_add_ps(runningGain2, runningGainDelta2);
  40685. }
  40686. iFrame = unrolledLoopCount << 1;
  40687. } else
  40688. #endif
  40689. {
  40690. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40691. for (iChannel = 0; iChannel < 6; iChannel += 1) {
  40692. pFramesOutF32[iFrame*6 + iChannel] = pFramesInF32[iFrame*6 + iChannel] * pRunningGain[iChannel];
  40693. }
  40694. /* Move the running gain forward towards the new gain. */
  40695. for (iChannel = 0; iChannel < 6; iChannel += 1) {
  40696. pRunningGain[iChannel] += pRunningGainDelta[iChannel];
  40697. }
  40698. }
  40699. }
  40700. } else if (pGainer->config.channels == 8) {
  40701. /* For 8 channels we can just go over frame by frame and do all eight channels as 2 separate 4x SIMD operations. */
  40702. #if defined(MA_SUPPORT_SSE2)
  40703. if (ma_has_sse2()) {
  40704. __m128 runningGainDelta0 = _mm_loadu_ps(&pRunningGainDelta[0]);
  40705. __m128 runningGainDelta1 = _mm_loadu_ps(&pRunningGainDelta[4]);
  40706. __m128 runningGain0 = _mm_loadu_ps(&pRunningGain[0]);
  40707. __m128 runningGain1 = _mm_loadu_ps(&pRunningGain[4]);
  40708. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40709. _mm_storeu_ps(&pFramesOutF32[iFrame*8 + 0], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*8 + 0]), runningGain0));
  40710. _mm_storeu_ps(&pFramesOutF32[iFrame*8 + 4], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*8 + 4]), runningGain1));
  40711. runningGain0 = _mm_add_ps(runningGain0, runningGainDelta0);
  40712. runningGain1 = _mm_add_ps(runningGain1, runningGainDelta1);
  40713. }
  40714. } else
  40715. #endif
  40716. {
  40717. /* This is crafted so that it auto-vectorizes when compiled with Clang. */
  40718. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40719. for (iChannel = 0; iChannel < 8; iChannel += 1) {
  40720. pFramesOutF32[iFrame*8 + iChannel] = pFramesInF32[iFrame*8 + iChannel] * pRunningGain[iChannel];
  40721. }
  40722. /* Move the running gain forward towards the new gain. */
  40723. for (iChannel = 0; iChannel < 8; iChannel += 1) {
  40724. pRunningGain[iChannel] += pRunningGainDelta[iChannel];
  40725. }
  40726. }
  40727. }
  40728. }
  40729. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40730. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40731. pFramesOutF32[iFrame*pGainer->config.channels + iChannel] = pFramesInF32[iFrame*pGainer->config.channels + iChannel] * pRunningGain[iChannel];
  40732. pRunningGain[iChannel] += pRunningGainDelta[iChannel];
  40733. }
  40734. }
  40735. } else {
  40736. /* Slower path for extreme channel counts where we can't fit enough on the stack. We could also move this to the heap as part of the ma_gainer object which might even be better since it'll only be updated when the gains actually change. */
  40737. for (iFrame = 0; iFrame < interpolatedFrameCount; iFrame += 1) {
  40738. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40739. pFramesOutF32[iFrame*pGainer->config.channels + iChannel] = pFramesInF32[iFrame*pGainer->config.channels + iChannel] * ma_mix_f32_fast(pGainer->pOldGains[iChannel], pGainer->pNewGains[iChannel], a) * pGainer->masterVolume;
  40740. }
  40741. a += d;
  40742. }
  40743. }
  40744. }
  40745. /* Make sure the timer is updated. */
  40746. pGainer->t = (ma_uint32)ma_min(pGainer->t + interpolatedFrameCount, pGainer->config.smoothTimeInFrames);
  40747. /* Adjust our arguments so the next part can work normally. */
  40748. frameCount -= interpolatedFrameCount;
  40749. pFramesOut = ma_offset_ptr(pFramesOut, interpolatedFrameCount * sizeof(float));
  40750. pFramesIn = ma_offset_ptr(pFramesIn, interpolatedFrameCount * sizeof(float));
  40751. }
  40752. /* All we need to do here is apply the new gains using an optimized path. */
  40753. if (pFramesOut != NULL && pFramesIn != NULL) {
  40754. if (pGainer->config.channels <= 32) {
  40755. float gains[32];
  40756. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40757. gains[iChannel] = pGainer->pNewGains[iChannel] * pGainer->masterVolume;
  40758. }
  40759. ma_copy_and_apply_volume_factor_per_channel_f32((float*)pFramesOut, (const float*)pFramesIn, frameCount, pGainer->config.channels, gains);
  40760. } else {
  40761. /* Slow path. Too many channels to fit on the stack. Need to apply a master volume as a separate path. */
  40762. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40763. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40764. ((float*)pFramesOut)[iFrame*pGainer->config.channels + iChannel] = ((const float*)pFramesIn)[iFrame*pGainer->config.channels + iChannel] * pGainer->pNewGains[iChannel] * pGainer->masterVolume;
  40765. }
  40766. }
  40767. }
  40768. }
  40769. /* Now that some frames have been processed we need to make sure future changes to the gain are interpolated. */
  40770. if (pGainer->t == (ma_uint32)-1) {
  40771. pGainer->t = (ma_uint32)ma_min(pGainer->config.smoothTimeInFrames, frameCount);
  40772. }
  40773. #if 0
  40774. if (pGainer->t >= pGainer->config.smoothTimeInFrames) {
  40775. /* Fast path. No gain calculation required. */
  40776. ma_copy_and_apply_volume_factor_per_channel_f32(pFramesOutF32, pFramesInF32, frameCount, pGainer->config.channels, pGainer->pNewGains);
  40777. ma_apply_volume_factor_f32(pFramesOutF32, frameCount * pGainer->config.channels, pGainer->masterVolume);
  40778. /* Now that some frames have been processed we need to make sure future changes to the gain are interpolated. */
  40779. if (pGainer->t == (ma_uint32)-1) {
  40780. pGainer->t = pGainer->config.smoothTimeInFrames;
  40781. }
  40782. } else {
  40783. /* Slow path. Need to interpolate the gain for each channel individually. */
  40784. /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */
  40785. if (pFramesOut != NULL && pFramesIn != NULL) {
  40786. float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames;
  40787. float d = 1.0f / pGainer->config.smoothTimeInFrames;
  40788. ma_uint32 channelCount = pGainer->config.channels;
  40789. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40790. for (iChannel = 0; iChannel < channelCount; iChannel += 1) {
  40791. pFramesOutF32[iChannel] = pFramesInF32[iChannel] * ma_mix_f32_fast(pGainer->pOldGains[iChannel], pGainer->pNewGains[iChannel], a) * pGainer->masterVolume;
  40792. }
  40793. pFramesOutF32 += channelCount;
  40794. pFramesInF32 += channelCount;
  40795. a += d;
  40796. if (a > 1) {
  40797. a = 1;
  40798. }
  40799. }
  40800. }
  40801. pGainer->t = (ma_uint32)ma_min(pGainer->t + frameCount, pGainer->config.smoothTimeInFrames);
  40802. #if 0 /* Reference implementation. */
  40803. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40804. /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */
  40805. if (pFramesOut != NULL && pFramesIn != NULL) {
  40806. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40807. pFramesOutF32[iFrame * pGainer->config.channels + iChannel] = pFramesInF32[iFrame * pGainer->config.channels + iChannel] * ma_gainer_calculate_current_gain(pGainer, iChannel) * pGainer->masterVolume;
  40808. }
  40809. }
  40810. /* Move interpolation time forward, but don't go beyond our smoothing time. */
  40811. pGainer->t = ma_min(pGainer->t + 1, pGainer->config.smoothTimeInFrames);
  40812. }
  40813. #endif
  40814. }
  40815. #endif
  40816. return MA_SUCCESS;
  40817. }
  40818. MA_API ma_result ma_gainer_process_pcm_frames(ma_gainer* pGainer, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40819. {
  40820. if (pGainer == NULL) {
  40821. return MA_INVALID_ARGS;
  40822. }
  40823. /*
  40824. ma_gainer_process_pcm_frames_internal() marks pFramesOut and pFramesIn with MA_RESTRICT which
  40825. helps with auto-vectorization.
  40826. */
  40827. return ma_gainer_process_pcm_frames_internal(pGainer, pFramesOut, pFramesIn, frameCount);
  40828. }
  40829. static void ma_gainer_set_gain_by_index(ma_gainer* pGainer, float newGain, ma_uint32 iChannel)
  40830. {
  40831. pGainer->pOldGains[iChannel] = ma_gainer_calculate_current_gain(pGainer, iChannel);
  40832. pGainer->pNewGains[iChannel] = newGain;
  40833. }
  40834. static void ma_gainer_reset_smoothing_time(ma_gainer* pGainer)
  40835. {
  40836. if (pGainer->t == (ma_uint32)-1) {
  40837. pGainer->t = pGainer->config.smoothTimeInFrames; /* No smoothing required for initial gains setting. */
  40838. } else {
  40839. pGainer->t = 0;
  40840. }
  40841. }
  40842. MA_API ma_result ma_gainer_set_gain(ma_gainer* pGainer, float newGain)
  40843. {
  40844. ma_uint32 iChannel;
  40845. if (pGainer == NULL) {
  40846. return MA_INVALID_ARGS;
  40847. }
  40848. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40849. ma_gainer_set_gain_by_index(pGainer, newGain, iChannel);
  40850. }
  40851. /* The smoothing time needs to be reset to ensure we always interpolate by the configured smoothing time, but only if it's not the first setting. */
  40852. ma_gainer_reset_smoothing_time(pGainer);
  40853. return MA_SUCCESS;
  40854. }
  40855. MA_API ma_result ma_gainer_set_gains(ma_gainer* pGainer, float* pNewGains)
  40856. {
  40857. ma_uint32 iChannel;
  40858. if (pGainer == NULL || pNewGains == NULL) {
  40859. return MA_INVALID_ARGS;
  40860. }
  40861. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40862. ma_gainer_set_gain_by_index(pGainer, pNewGains[iChannel], iChannel);
  40863. }
  40864. /* The smoothing time needs to be reset to ensure we always interpolate by the configured smoothing time, but only if it's not the first setting. */
  40865. ma_gainer_reset_smoothing_time(pGainer);
  40866. return MA_SUCCESS;
  40867. }
  40868. MA_API ma_result ma_gainer_set_master_volume(ma_gainer* pGainer, float volume)
  40869. {
  40870. if (pGainer == NULL) {
  40871. return MA_INVALID_ARGS;
  40872. }
  40873. pGainer->masterVolume = volume;
  40874. return MA_SUCCESS;
  40875. }
  40876. MA_API ma_result ma_gainer_get_master_volume(const ma_gainer* pGainer, float* pVolume)
  40877. {
  40878. if (pGainer == NULL || pVolume == NULL) {
  40879. return MA_INVALID_ARGS;
  40880. }
  40881. *pVolume = pGainer->masterVolume;
  40882. return MA_SUCCESS;
  40883. }
  40884. MA_API ma_panner_config ma_panner_config_init(ma_format format, ma_uint32 channels)
  40885. {
  40886. ma_panner_config config;
  40887. MA_ZERO_OBJECT(&config);
  40888. config.format = format;
  40889. config.channels = channels;
  40890. config.mode = ma_pan_mode_balance; /* Set to balancing mode by default because it's consistent with other audio engines and most likely what the caller is expecting. */
  40891. config.pan = 0;
  40892. return config;
  40893. }
  40894. MA_API ma_result ma_panner_init(const ma_panner_config* pConfig, ma_panner* pPanner)
  40895. {
  40896. if (pPanner == NULL) {
  40897. return MA_INVALID_ARGS;
  40898. }
  40899. MA_ZERO_OBJECT(pPanner);
  40900. if (pConfig == NULL) {
  40901. return MA_INVALID_ARGS;
  40902. }
  40903. pPanner->format = pConfig->format;
  40904. pPanner->channels = pConfig->channels;
  40905. pPanner->mode = pConfig->mode;
  40906. pPanner->pan = pConfig->pan;
  40907. return MA_SUCCESS;
  40908. }
  40909. static void ma_stereo_balance_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, float pan)
  40910. {
  40911. ma_uint64 iFrame;
  40912. if (pan > 0) {
  40913. float factor = 1.0f - pan;
  40914. if (pFramesOut == pFramesIn) {
  40915. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40916. pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0] * factor;
  40917. }
  40918. } else {
  40919. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40920. pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0] * factor;
  40921. pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1];
  40922. }
  40923. }
  40924. } else {
  40925. float factor = 1.0f + pan;
  40926. if (pFramesOut == pFramesIn) {
  40927. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40928. pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1] * factor;
  40929. }
  40930. } else {
  40931. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40932. pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0];
  40933. pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1] * factor;
  40934. }
  40935. }
  40936. }
  40937. }
  40938. static void ma_stereo_balance_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, float pan)
  40939. {
  40940. if (pan == 0) {
  40941. /* Fast path. No panning required. */
  40942. if (pFramesOut == pFramesIn) {
  40943. /* No-op */
  40944. } else {
  40945. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  40946. }
  40947. return;
  40948. }
  40949. switch (format) {
  40950. case ma_format_f32: ma_stereo_balance_pcm_frames_f32((float*)pFramesOut, (float*)pFramesIn, frameCount, pan); break;
  40951. /* Unknown format. Just copy. */
  40952. default:
  40953. {
  40954. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  40955. } break;
  40956. }
  40957. }
  40958. static void ma_stereo_pan_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, float pan)
  40959. {
  40960. ma_uint64 iFrame;
  40961. if (pan > 0) {
  40962. float factorL0 = 1.0f - pan;
  40963. float factorL1 = 0.0f + pan;
  40964. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40965. float sample0 = (pFramesIn[iFrame*2 + 0] * factorL0);
  40966. float sample1 = (pFramesIn[iFrame*2 + 0] * factorL1) + pFramesIn[iFrame*2 + 1];
  40967. pFramesOut[iFrame*2 + 0] = sample0;
  40968. pFramesOut[iFrame*2 + 1] = sample1;
  40969. }
  40970. } else {
  40971. float factorR0 = 0.0f - pan;
  40972. float factorR1 = 1.0f + pan;
  40973. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40974. float sample0 = pFramesIn[iFrame*2 + 0] + (pFramesIn[iFrame*2 + 1] * factorR0);
  40975. float sample1 = (pFramesIn[iFrame*2 + 1] * factorR1);
  40976. pFramesOut[iFrame*2 + 0] = sample0;
  40977. pFramesOut[iFrame*2 + 1] = sample1;
  40978. }
  40979. }
  40980. }
  40981. static void ma_stereo_pan_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, float pan)
  40982. {
  40983. if (pan == 0) {
  40984. /* Fast path. No panning required. */
  40985. if (pFramesOut == pFramesIn) {
  40986. /* No-op */
  40987. } else {
  40988. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  40989. }
  40990. return;
  40991. }
  40992. switch (format) {
  40993. case ma_format_f32: ma_stereo_pan_pcm_frames_f32((float*)pFramesOut, (float*)pFramesIn, frameCount, pan); break;
  40994. /* Unknown format. Just copy. */
  40995. default:
  40996. {
  40997. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  40998. } break;
  40999. }
  41000. }
  41001. MA_API ma_result ma_panner_process_pcm_frames(ma_panner* pPanner, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  41002. {
  41003. if (pPanner == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  41004. return MA_INVALID_ARGS;
  41005. }
  41006. if (pPanner->channels == 2) {
  41007. /* Stereo case. For now assume channel 0 is left and channel right is 1, but should probably add support for a channel map. */
  41008. if (pPanner->mode == ma_pan_mode_balance) {
  41009. ma_stereo_balance_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->pan);
  41010. } else {
  41011. ma_stereo_pan_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->pan);
  41012. }
  41013. } else {
  41014. if (pPanner->channels == 1) {
  41015. /* Panning has no effect on mono streams. */
  41016. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->channels);
  41017. } else {
  41018. /* For now we're not going to support non-stereo set ups. Not sure how I want to handle this case just yet. */
  41019. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->channels);
  41020. }
  41021. }
  41022. return MA_SUCCESS;
  41023. }
  41024. MA_API void ma_panner_set_mode(ma_panner* pPanner, ma_pan_mode mode)
  41025. {
  41026. if (pPanner == NULL) {
  41027. return;
  41028. }
  41029. pPanner->mode = mode;
  41030. }
  41031. MA_API ma_pan_mode ma_panner_get_mode(const ma_panner* pPanner)
  41032. {
  41033. if (pPanner == NULL) {
  41034. return ma_pan_mode_balance;
  41035. }
  41036. return pPanner->mode;
  41037. }
  41038. MA_API void ma_panner_set_pan(ma_panner* pPanner, float pan)
  41039. {
  41040. if (pPanner == NULL) {
  41041. return;
  41042. }
  41043. pPanner->pan = ma_clamp(pan, -1.0f, 1.0f);
  41044. }
  41045. MA_API float ma_panner_get_pan(const ma_panner* pPanner)
  41046. {
  41047. if (pPanner == NULL) {
  41048. return 0;
  41049. }
  41050. return pPanner->pan;
  41051. }
  41052. MA_API ma_fader_config ma_fader_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  41053. {
  41054. ma_fader_config config;
  41055. MA_ZERO_OBJECT(&config);
  41056. config.format = format;
  41057. config.channels = channels;
  41058. config.sampleRate = sampleRate;
  41059. return config;
  41060. }
  41061. MA_API ma_result ma_fader_init(const ma_fader_config* pConfig, ma_fader* pFader)
  41062. {
  41063. if (pFader == NULL) {
  41064. return MA_INVALID_ARGS;
  41065. }
  41066. MA_ZERO_OBJECT(pFader);
  41067. if (pConfig == NULL) {
  41068. return MA_INVALID_ARGS;
  41069. }
  41070. /* Only f32 is supported for now. */
  41071. if (pConfig->format != ma_format_f32) {
  41072. return MA_INVALID_ARGS;
  41073. }
  41074. pFader->config = *pConfig;
  41075. pFader->volumeBeg = 1;
  41076. pFader->volumeEnd = 1;
  41077. pFader->lengthInFrames = 0;
  41078. pFader->cursorInFrames = 0;
  41079. return MA_SUCCESS;
  41080. }
  41081. MA_API ma_result ma_fader_process_pcm_frames(ma_fader* pFader, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  41082. {
  41083. if (pFader == NULL) {
  41084. return MA_INVALID_ARGS;
  41085. }
  41086. /*
  41087. For now we need to clamp frameCount so that the cursor never overflows 32-bits. This is required for
  41088. the conversion to a float which we use for the linear interpolation. This might be changed later.
  41089. */
  41090. if (frameCount + pFader->cursorInFrames > UINT_MAX) {
  41091. frameCount = UINT_MAX - pFader->cursorInFrames;
  41092. }
  41093. /* Optimized path if volumeBeg and volumeEnd are equal. */
  41094. if (pFader->volumeBeg == pFader->volumeEnd) {
  41095. if (pFader->volumeBeg == 1) {
  41096. /* Straight copy. */
  41097. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels);
  41098. } else {
  41099. /* Copy with volume. */
  41100. ma_copy_and_apply_volume_and_clip_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels, pFader->volumeEnd);
  41101. }
  41102. } else {
  41103. /* Slower path. Volumes are different, so may need to do an interpolation. */
  41104. if (pFader->cursorInFrames >= pFader->lengthInFrames) {
  41105. /* Fast path. We've gone past the end of the fade period so just apply the end volume to all samples. */
  41106. ma_copy_and_apply_volume_and_clip_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels, pFader->volumeEnd);
  41107. } else {
  41108. /* Slow path. This is where we do the actual fading. */
  41109. ma_uint64 iFrame;
  41110. ma_uint32 iChannel;
  41111. /* For now we only support f32. Support for other formats will be added later. */
  41112. if (pFader->config.format == ma_format_f32) {
  41113. const float* pFramesInF32 = (const float*)pFramesIn;
  41114. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  41115. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  41116. float a = (ma_uint32)ma_min(pFader->cursorInFrames + iFrame, pFader->lengthInFrames) / (float)((ma_uint32)pFader->lengthInFrames); /* Safe cast due to the frameCount clamp at the top of this function. */
  41117. float volume = ma_mix_f32_fast(pFader->volumeBeg, pFader->volumeEnd, a);
  41118. for (iChannel = 0; iChannel < pFader->config.channels; iChannel += 1) {
  41119. pFramesOutF32[iFrame*pFader->config.channels + iChannel] = pFramesInF32[iFrame*pFader->config.channels + iChannel] * volume;
  41120. }
  41121. }
  41122. } else {
  41123. return MA_NOT_IMPLEMENTED;
  41124. }
  41125. }
  41126. }
  41127. pFader->cursorInFrames += frameCount;
  41128. return MA_SUCCESS;
  41129. }
  41130. MA_API void ma_fader_get_data_format(const ma_fader* pFader, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate)
  41131. {
  41132. if (pFader == NULL) {
  41133. return;
  41134. }
  41135. if (pFormat != NULL) {
  41136. *pFormat = pFader->config.format;
  41137. }
  41138. if (pChannels != NULL) {
  41139. *pChannels = pFader->config.channels;
  41140. }
  41141. if (pSampleRate != NULL) {
  41142. *pSampleRate = pFader->config.sampleRate;
  41143. }
  41144. }
  41145. MA_API void ma_fader_set_fade(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames)
  41146. {
  41147. if (pFader == NULL) {
  41148. return;
  41149. }
  41150. /* If the volume is negative, use current volume. */
  41151. if (volumeBeg < 0) {
  41152. volumeBeg = ma_fader_get_current_volume(pFader);
  41153. }
  41154. /*
  41155. The length needs to be clamped to 32-bits due to how we convert it to a float for linear
  41156. interpolation reasons. I might change this requirement later, but for now it's not important.
  41157. */
  41158. if (lengthInFrames > UINT_MAX) {
  41159. lengthInFrames = UINT_MAX;
  41160. }
  41161. pFader->volumeBeg = volumeBeg;
  41162. pFader->volumeEnd = volumeEnd;
  41163. pFader->lengthInFrames = lengthInFrames;
  41164. pFader->cursorInFrames = 0; /* Reset cursor. */
  41165. }
  41166. MA_API float ma_fader_get_current_volume(const ma_fader* pFader)
  41167. {
  41168. if (pFader == NULL) {
  41169. return 0.0f;
  41170. }
  41171. /* The current volume depends on the position of the cursor. */
  41172. if (pFader->cursorInFrames == 0) {
  41173. return pFader->volumeBeg;
  41174. } else if (pFader->cursorInFrames >= pFader->lengthInFrames) {
  41175. return pFader->volumeEnd;
  41176. } else {
  41177. /* The cursor is somewhere inside the fading period. We can figure this out with a simple linear interpoluation between volumeBeg and volumeEnd based on our cursor position. */
  41178. return ma_mix_f32_fast(pFader->volumeBeg, pFader->volumeEnd, (ma_uint32)pFader->cursorInFrames / (float)((ma_uint32)pFader->lengthInFrames)); /* Safe cast to uint32 because we clamp it in ma_fader_process_pcm_frames(). */
  41179. }
  41180. }
  41181. MA_API ma_vec3f ma_vec3f_init_3f(float x, float y, float z)
  41182. {
  41183. ma_vec3f v;
  41184. v.x = x;
  41185. v.y = y;
  41186. v.z = z;
  41187. return v;
  41188. }
  41189. MA_API ma_vec3f ma_vec3f_sub(ma_vec3f a, ma_vec3f b)
  41190. {
  41191. return ma_vec3f_init_3f(
  41192. a.x - b.x,
  41193. a.y - b.y,
  41194. a.z - b.z
  41195. );
  41196. }
  41197. MA_API ma_vec3f ma_vec3f_neg(ma_vec3f a)
  41198. {
  41199. return ma_vec3f_init_3f(
  41200. -a.x,
  41201. -a.y,
  41202. -a.z
  41203. );
  41204. }
  41205. MA_API float ma_vec3f_dot(ma_vec3f a, ma_vec3f b)
  41206. {
  41207. return a.x*b.x + a.y*b.y + a.z*b.z;
  41208. }
  41209. MA_API float ma_vec3f_len2(ma_vec3f v)
  41210. {
  41211. return ma_vec3f_dot(v, v);
  41212. }
  41213. MA_API float ma_vec3f_len(ma_vec3f v)
  41214. {
  41215. return (float)ma_sqrtd(ma_vec3f_len2(v));
  41216. }
  41217. MA_API float ma_vec3f_dist(ma_vec3f a, ma_vec3f b)
  41218. {
  41219. return ma_vec3f_len(ma_vec3f_sub(a, b));
  41220. }
  41221. MA_API ma_vec3f ma_vec3f_normalize(ma_vec3f v)
  41222. {
  41223. float invLen;
  41224. float len2 = ma_vec3f_len2(v);
  41225. if (len2 == 0) {
  41226. return ma_vec3f_init_3f(0, 0, 0);
  41227. }
  41228. invLen = ma_rsqrtf(len2);
  41229. v.x *= invLen;
  41230. v.y *= invLen;
  41231. v.z *= invLen;
  41232. return v;
  41233. }
  41234. MA_API ma_vec3f ma_vec3f_cross(ma_vec3f a, ma_vec3f b)
  41235. {
  41236. return ma_vec3f_init_3f(
  41237. a.y*b.z - a.z*b.y,
  41238. a.z*b.x - a.x*b.z,
  41239. a.x*b.y - a.y*b.x
  41240. );
  41241. }
  41242. MA_API void ma_atomic_vec3f_init(ma_atomic_vec3f* v, ma_vec3f value)
  41243. {
  41244. v->v = value;
  41245. v->lock = 0; /* Important this is initialized to 0. */
  41246. }
  41247. MA_API void ma_atomic_vec3f_set(ma_atomic_vec3f* v, ma_vec3f value)
  41248. {
  41249. ma_spinlock_lock(&v->lock);
  41250. {
  41251. v->v = value;
  41252. }
  41253. ma_spinlock_unlock(&v->lock);
  41254. }
  41255. MA_API ma_vec3f ma_atomic_vec3f_get(ma_atomic_vec3f* v)
  41256. {
  41257. ma_vec3f r;
  41258. ma_spinlock_lock(&v->lock);
  41259. {
  41260. r = v->v;
  41261. }
  41262. ma_spinlock_unlock(&v->lock);
  41263. return r;
  41264. }
  41265. static void ma_channel_map_apply_f32(float* pFramesOut, const ma_channel* pChannelMapOut, ma_uint32 channelsOut, const float* pFramesIn, const ma_channel* pChannelMapIn, ma_uint32 channelsIn, ma_uint64 frameCount, ma_channel_mix_mode mode, ma_mono_expansion_mode monoExpansionMode);
  41266. static ma_bool32 ma_is_spatial_channel_position(ma_channel channelPosition);
  41267. #ifndef MA_DEFAULT_SPEED_OF_SOUND
  41268. #define MA_DEFAULT_SPEED_OF_SOUND 343.3f
  41269. #endif
  41270. /*
  41271. These vectors represent the direction that speakers are facing from the center point. They're used
  41272. for panning in the spatializer. Must be normalized.
  41273. */
  41274. static ma_vec3f g_maChannelDirections[MA_CHANNEL_POSITION_COUNT] = {
  41275. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_NONE */
  41276. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_MONO */
  41277. {-0.7071f, 0.0f, -0.7071f }, /* MA_CHANNEL_FRONT_LEFT */
  41278. {+0.7071f, 0.0f, -0.7071f }, /* MA_CHANNEL_FRONT_RIGHT */
  41279. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_FRONT_CENTER */
  41280. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_LFE */
  41281. {-0.7071f, 0.0f, +0.7071f }, /* MA_CHANNEL_BACK_LEFT */
  41282. {+0.7071f, 0.0f, +0.7071f }, /* MA_CHANNEL_BACK_RIGHT */
  41283. {-0.3162f, 0.0f, -0.9487f }, /* MA_CHANNEL_FRONT_LEFT_CENTER */
  41284. {+0.3162f, 0.0f, -0.9487f }, /* MA_CHANNEL_FRONT_RIGHT_CENTER */
  41285. { 0.0f, 0.0f, +1.0f }, /* MA_CHANNEL_BACK_CENTER */
  41286. {-1.0f, 0.0f, 0.0f }, /* MA_CHANNEL_SIDE_LEFT */
  41287. {+1.0f, 0.0f, 0.0f }, /* MA_CHANNEL_SIDE_RIGHT */
  41288. { 0.0f, +1.0f, 0.0f }, /* MA_CHANNEL_TOP_CENTER */
  41289. {-0.5774f, +0.5774f, -0.5774f }, /* MA_CHANNEL_TOP_FRONT_LEFT */
  41290. { 0.0f, +0.7071f, -0.7071f }, /* MA_CHANNEL_TOP_FRONT_CENTER */
  41291. {+0.5774f, +0.5774f, -0.5774f }, /* MA_CHANNEL_TOP_FRONT_RIGHT */
  41292. {-0.5774f, +0.5774f, +0.5774f }, /* MA_CHANNEL_TOP_BACK_LEFT */
  41293. { 0.0f, +0.7071f, +0.7071f }, /* MA_CHANNEL_TOP_BACK_CENTER */
  41294. {+0.5774f, +0.5774f, +0.5774f }, /* MA_CHANNEL_TOP_BACK_RIGHT */
  41295. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_0 */
  41296. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_1 */
  41297. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_2 */
  41298. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_3 */
  41299. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_4 */
  41300. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_5 */
  41301. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_6 */
  41302. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_7 */
  41303. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_8 */
  41304. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_9 */
  41305. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_10 */
  41306. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_11 */
  41307. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_12 */
  41308. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_13 */
  41309. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_14 */
  41310. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_15 */
  41311. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_16 */
  41312. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_17 */
  41313. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_18 */
  41314. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_19 */
  41315. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_20 */
  41316. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_21 */
  41317. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_22 */
  41318. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_23 */
  41319. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_24 */
  41320. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_25 */
  41321. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_26 */
  41322. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_27 */
  41323. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_28 */
  41324. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_29 */
  41325. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_30 */
  41326. { 0.0f, 0.0f, -1.0f } /* MA_CHANNEL_AUX_31 */
  41327. };
  41328. static ma_vec3f ma_get_channel_direction(ma_channel channel)
  41329. {
  41330. if (channel >= MA_CHANNEL_POSITION_COUNT) {
  41331. return ma_vec3f_init_3f(0, 0, -1);
  41332. } else {
  41333. return g_maChannelDirections[channel];
  41334. }
  41335. }
  41336. static float ma_attenuation_inverse(float distance, float minDistance, float maxDistance, float rolloff)
  41337. {
  41338. if (minDistance >= maxDistance) {
  41339. return 1; /* To avoid division by zero. Do not attenuate. */
  41340. }
  41341. return minDistance / (minDistance + rolloff * (ma_clamp(distance, minDistance, maxDistance) - minDistance));
  41342. }
  41343. static float ma_attenuation_linear(float distance, float minDistance, float maxDistance, float rolloff)
  41344. {
  41345. if (minDistance >= maxDistance) {
  41346. return 1; /* To avoid division by zero. Do not attenuate. */
  41347. }
  41348. return 1 - rolloff * (ma_clamp(distance, minDistance, maxDistance) - minDistance) / (maxDistance - minDistance);
  41349. }
  41350. static float ma_attenuation_exponential(float distance, float minDistance, float maxDistance, float rolloff)
  41351. {
  41352. if (minDistance >= maxDistance) {
  41353. return 1; /* To avoid division by zero. Do not attenuate. */
  41354. }
  41355. return (float)ma_powd(ma_clamp(distance, minDistance, maxDistance) / minDistance, -rolloff);
  41356. }
  41357. /*
  41358. Dopper Effect calculation taken from the OpenAL spec, with two main differences:
  41359. 1) The source to listener vector will have already been calcualted at an earlier step so we can
  41360. just use that directly. We need only the position of the source relative to the origin.
  41361. 2) We don't scale by a frequency because we actually just want the ratio which we'll plug straight
  41362. into the resampler directly.
  41363. */
  41364. static float ma_doppler_pitch(ma_vec3f relativePosition, ma_vec3f sourceVelocity, ma_vec3f listenVelocity, float speedOfSound, float dopplerFactor)
  41365. {
  41366. float len;
  41367. float vls;
  41368. float vss;
  41369. len = ma_vec3f_len(relativePosition);
  41370. /*
  41371. There's a case where the position of the source will be right on top of the listener in which
  41372. case the length will be 0 and we'll end up with a division by zero. We can just return a ratio
  41373. of 1.0 in this case. This is not considered in the OpenAL spec, but is necessary.
  41374. */
  41375. if (len == 0) {
  41376. return 1.0;
  41377. }
  41378. vls = ma_vec3f_dot(relativePosition, listenVelocity) / len;
  41379. vss = ma_vec3f_dot(relativePosition, sourceVelocity) / len;
  41380. vls = ma_min(vls, speedOfSound / dopplerFactor);
  41381. vss = ma_min(vss, speedOfSound / dopplerFactor);
  41382. return (speedOfSound - dopplerFactor*vls) / (speedOfSound - dopplerFactor*vss);
  41383. }
  41384. static void ma_get_default_channel_map_for_spatializer(ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channelCount)
  41385. {
  41386. /*
  41387. Special case for stereo. Want to default the left and right speakers to side left and side
  41388. right so that they're facing directly down the X axis rather than slightly forward. Not
  41389. doing this will result in sounds being quieter when behind the listener. This might
  41390. actually be good for some scenerios, but I don't think it's an appropriate default because
  41391. it can be a bit unexpected.
  41392. */
  41393. if (channelCount == 2) {
  41394. pChannelMap[0] = MA_CHANNEL_SIDE_LEFT;
  41395. pChannelMap[1] = MA_CHANNEL_SIDE_RIGHT;
  41396. } else {
  41397. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount);
  41398. }
  41399. }
  41400. MA_API ma_spatializer_listener_config ma_spatializer_listener_config_init(ma_uint32 channelsOut)
  41401. {
  41402. ma_spatializer_listener_config config;
  41403. MA_ZERO_OBJECT(&config);
  41404. config.channelsOut = channelsOut;
  41405. config.pChannelMapOut = NULL;
  41406. config.handedness = ma_handedness_right;
  41407. config.worldUp = ma_vec3f_init_3f(0, 1, 0);
  41408. config.coneInnerAngleInRadians = 6.283185f; /* 360 degrees. */
  41409. config.coneOuterAngleInRadians = 6.283185f; /* 360 degrees. */
  41410. config.coneOuterGain = 0;
  41411. config.speedOfSound = 343.3f; /* Same as OpenAL. Used for doppler effect. */
  41412. return config;
  41413. }
  41414. typedef struct
  41415. {
  41416. size_t sizeInBytes;
  41417. size_t channelMapOutOffset;
  41418. } ma_spatializer_listener_heap_layout;
  41419. static ma_result ma_spatializer_listener_get_heap_layout(const ma_spatializer_listener_config* pConfig, ma_spatializer_listener_heap_layout* pHeapLayout)
  41420. {
  41421. MA_ASSERT(pHeapLayout != NULL);
  41422. MA_ZERO_OBJECT(pHeapLayout);
  41423. if (pConfig == NULL) {
  41424. return MA_INVALID_ARGS;
  41425. }
  41426. if (pConfig->channelsOut == 0) {
  41427. return MA_INVALID_ARGS;
  41428. }
  41429. pHeapLayout->sizeInBytes = 0;
  41430. /* Channel map. We always need this, even for passthroughs. */
  41431. pHeapLayout->channelMapOutOffset = pHeapLayout->sizeInBytes;
  41432. pHeapLayout->sizeInBytes += ma_align_64(sizeof(*pConfig->pChannelMapOut) * pConfig->channelsOut);
  41433. return MA_SUCCESS;
  41434. }
  41435. MA_API ma_result ma_spatializer_listener_get_heap_size(const ma_spatializer_listener_config* pConfig, size_t* pHeapSizeInBytes)
  41436. {
  41437. ma_result result;
  41438. ma_spatializer_listener_heap_layout heapLayout;
  41439. if (pHeapSizeInBytes == NULL) {
  41440. return MA_INVALID_ARGS;
  41441. }
  41442. *pHeapSizeInBytes = 0;
  41443. result = ma_spatializer_listener_get_heap_layout(pConfig, &heapLayout);
  41444. if (result != MA_SUCCESS) {
  41445. return result;
  41446. }
  41447. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  41448. return MA_SUCCESS;
  41449. }
  41450. MA_API ma_result ma_spatializer_listener_init_preallocated(const ma_spatializer_listener_config* pConfig, void* pHeap, ma_spatializer_listener* pListener)
  41451. {
  41452. ma_result result;
  41453. ma_spatializer_listener_heap_layout heapLayout;
  41454. if (pListener == NULL) {
  41455. return MA_INVALID_ARGS;
  41456. }
  41457. MA_ZERO_OBJECT(pListener);
  41458. result = ma_spatializer_listener_get_heap_layout(pConfig, &heapLayout);
  41459. if (result != MA_SUCCESS) {
  41460. return result;
  41461. }
  41462. pListener->_pHeap = pHeap;
  41463. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  41464. pListener->config = *pConfig;
  41465. ma_atomic_vec3f_init(&pListener->position, ma_vec3f_init_3f(0, 0, 0));
  41466. ma_atomic_vec3f_init(&pListener->direction, ma_vec3f_init_3f(0, 0, -1));
  41467. ma_atomic_vec3f_init(&pListener->velocity, ma_vec3f_init_3f(0, 0, 0));
  41468. pListener->isEnabled = MA_TRUE;
  41469. /* Swap the forward direction if we're left handed (it was initialized based on right handed). */
  41470. if (pListener->config.handedness == ma_handedness_left) {
  41471. ma_vec3f negDir = ma_vec3f_neg(ma_spatializer_listener_get_direction(pListener));
  41472. ma_spatializer_listener_set_direction(pListener, negDir.x, negDir.y, negDir.z);
  41473. }
  41474. /* We must always have a valid channel map. */
  41475. pListener->config.pChannelMapOut = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapOutOffset);
  41476. /* Use a slightly different default channel map for stereo. */
  41477. if (pConfig->pChannelMapOut == NULL) {
  41478. ma_get_default_channel_map_for_spatializer(pListener->config.pChannelMapOut, pConfig->channelsOut, pConfig->channelsOut);
  41479. } else {
  41480. ma_channel_map_copy_or_default(pListener->config.pChannelMapOut, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelsOut);
  41481. }
  41482. return MA_SUCCESS;
  41483. }
  41484. MA_API ma_result ma_spatializer_listener_init(const ma_spatializer_listener_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer_listener* pListener)
  41485. {
  41486. ma_result result;
  41487. size_t heapSizeInBytes;
  41488. void* pHeap;
  41489. result = ma_spatializer_listener_get_heap_size(pConfig, &heapSizeInBytes);
  41490. if (result != MA_SUCCESS) {
  41491. return result;
  41492. }
  41493. if (heapSizeInBytes > 0) {
  41494. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  41495. if (pHeap == NULL) {
  41496. return MA_OUT_OF_MEMORY;
  41497. }
  41498. } else {
  41499. pHeap = NULL;
  41500. }
  41501. result = ma_spatializer_listener_init_preallocated(pConfig, pHeap, pListener);
  41502. if (result != MA_SUCCESS) {
  41503. ma_free(pHeap, pAllocationCallbacks);
  41504. return result;
  41505. }
  41506. pListener->_ownsHeap = MA_TRUE;
  41507. return MA_SUCCESS;
  41508. }
  41509. MA_API void ma_spatializer_listener_uninit(ma_spatializer_listener* pListener, const ma_allocation_callbacks* pAllocationCallbacks)
  41510. {
  41511. if (pListener == NULL) {
  41512. return;
  41513. }
  41514. if (pListener->_ownsHeap) {
  41515. ma_free(pListener->_pHeap, pAllocationCallbacks);
  41516. }
  41517. }
  41518. MA_API ma_channel* ma_spatializer_listener_get_channel_map(ma_spatializer_listener* pListener)
  41519. {
  41520. if (pListener == NULL) {
  41521. return NULL;
  41522. }
  41523. return pListener->config.pChannelMapOut;
  41524. }
  41525. MA_API void ma_spatializer_listener_set_cone(ma_spatializer_listener* pListener, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  41526. {
  41527. if (pListener == NULL) {
  41528. return;
  41529. }
  41530. pListener->config.coneInnerAngleInRadians = innerAngleInRadians;
  41531. pListener->config.coneOuterAngleInRadians = outerAngleInRadians;
  41532. pListener->config.coneOuterGain = outerGain;
  41533. }
  41534. MA_API void ma_spatializer_listener_get_cone(const ma_spatializer_listener* pListener, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  41535. {
  41536. if (pListener == NULL) {
  41537. return;
  41538. }
  41539. if (pInnerAngleInRadians != NULL) {
  41540. *pInnerAngleInRadians = pListener->config.coneInnerAngleInRadians;
  41541. }
  41542. if (pOuterAngleInRadians != NULL) {
  41543. *pOuterAngleInRadians = pListener->config.coneOuterAngleInRadians;
  41544. }
  41545. if (pOuterGain != NULL) {
  41546. *pOuterGain = pListener->config.coneOuterGain;
  41547. }
  41548. }
  41549. MA_API void ma_spatializer_listener_set_position(ma_spatializer_listener* pListener, float x, float y, float z)
  41550. {
  41551. if (pListener == NULL) {
  41552. return;
  41553. }
  41554. ma_atomic_vec3f_set(&pListener->position, ma_vec3f_init_3f(x, y, z));
  41555. }
  41556. MA_API ma_vec3f ma_spatializer_listener_get_position(const ma_spatializer_listener* pListener)
  41557. {
  41558. if (pListener == NULL) {
  41559. return ma_vec3f_init_3f(0, 0, 0);
  41560. }
  41561. return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pListener->position); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */
  41562. }
  41563. MA_API void ma_spatializer_listener_set_direction(ma_spatializer_listener* pListener, float x, float y, float z)
  41564. {
  41565. if (pListener == NULL) {
  41566. return;
  41567. }
  41568. ma_atomic_vec3f_set(&pListener->direction, ma_vec3f_init_3f(x, y, z));
  41569. }
  41570. MA_API ma_vec3f ma_spatializer_listener_get_direction(const ma_spatializer_listener* pListener)
  41571. {
  41572. if (pListener == NULL) {
  41573. return ma_vec3f_init_3f(0, 0, -1);
  41574. }
  41575. return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pListener->direction); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */
  41576. }
  41577. MA_API void ma_spatializer_listener_set_velocity(ma_spatializer_listener* pListener, float x, float y, float z)
  41578. {
  41579. if (pListener == NULL) {
  41580. return;
  41581. }
  41582. ma_atomic_vec3f_set(&pListener->velocity, ma_vec3f_init_3f(x, y, z));
  41583. }
  41584. MA_API ma_vec3f ma_spatializer_listener_get_velocity(const ma_spatializer_listener* pListener)
  41585. {
  41586. if (pListener == NULL) {
  41587. return ma_vec3f_init_3f(0, 0, 0);
  41588. }
  41589. return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pListener->velocity); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */
  41590. }
  41591. MA_API void ma_spatializer_listener_set_speed_of_sound(ma_spatializer_listener* pListener, float speedOfSound)
  41592. {
  41593. if (pListener == NULL) {
  41594. return;
  41595. }
  41596. pListener->config.speedOfSound = speedOfSound;
  41597. }
  41598. MA_API float ma_spatializer_listener_get_speed_of_sound(const ma_spatializer_listener* pListener)
  41599. {
  41600. if (pListener == NULL) {
  41601. return 0;
  41602. }
  41603. return pListener->config.speedOfSound;
  41604. }
  41605. MA_API void ma_spatializer_listener_set_world_up(ma_spatializer_listener* pListener, float x, float y, float z)
  41606. {
  41607. if (pListener == NULL) {
  41608. return;
  41609. }
  41610. pListener->config.worldUp = ma_vec3f_init_3f(x, y, z);
  41611. }
  41612. MA_API ma_vec3f ma_spatializer_listener_get_world_up(const ma_spatializer_listener* pListener)
  41613. {
  41614. if (pListener == NULL) {
  41615. return ma_vec3f_init_3f(0, 1, 0);
  41616. }
  41617. return pListener->config.worldUp;
  41618. }
  41619. MA_API void ma_spatializer_listener_set_enabled(ma_spatializer_listener* pListener, ma_bool32 isEnabled)
  41620. {
  41621. if (pListener == NULL) {
  41622. return;
  41623. }
  41624. pListener->isEnabled = isEnabled;
  41625. }
  41626. MA_API ma_bool32 ma_spatializer_listener_is_enabled(const ma_spatializer_listener* pListener)
  41627. {
  41628. if (pListener == NULL) {
  41629. return MA_FALSE;
  41630. }
  41631. return pListener->isEnabled;
  41632. }
  41633. MA_API ma_spatializer_config ma_spatializer_config_init(ma_uint32 channelsIn, ma_uint32 channelsOut)
  41634. {
  41635. ma_spatializer_config config;
  41636. MA_ZERO_OBJECT(&config);
  41637. config.channelsIn = channelsIn;
  41638. config.channelsOut = channelsOut;
  41639. config.pChannelMapIn = NULL;
  41640. config.attenuationModel = ma_attenuation_model_inverse;
  41641. config.positioning = ma_positioning_absolute;
  41642. config.handedness = ma_handedness_right;
  41643. config.minGain = 0;
  41644. config.maxGain = 1;
  41645. config.minDistance = 1;
  41646. config.maxDistance = MA_FLT_MAX;
  41647. config.rolloff = 1;
  41648. config.coneInnerAngleInRadians = 6.283185f; /* 360 degrees. */
  41649. config.coneOuterAngleInRadians = 6.283185f; /* 360 degress. */
  41650. config.coneOuterGain = 0.0f;
  41651. config.dopplerFactor = 1;
  41652. config.directionalAttenuationFactor = 1;
  41653. config.minSpatializationChannelGain = 0.2f;
  41654. config.gainSmoothTimeInFrames = 360; /* 7.5ms @ 48K. */
  41655. return config;
  41656. }
  41657. static ma_gainer_config ma_spatializer_gainer_config_init(const ma_spatializer_config* pConfig)
  41658. {
  41659. MA_ASSERT(pConfig != NULL);
  41660. return ma_gainer_config_init(pConfig->channelsOut, pConfig->gainSmoothTimeInFrames);
  41661. }
  41662. static ma_result ma_spatializer_validate_config(const ma_spatializer_config* pConfig)
  41663. {
  41664. MA_ASSERT(pConfig != NULL);
  41665. if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) {
  41666. return MA_INVALID_ARGS;
  41667. }
  41668. return MA_SUCCESS;
  41669. }
  41670. typedef struct
  41671. {
  41672. size_t sizeInBytes;
  41673. size_t channelMapInOffset;
  41674. size_t newChannelGainsOffset;
  41675. size_t gainerOffset;
  41676. } ma_spatializer_heap_layout;
  41677. static ma_result ma_spatializer_get_heap_layout(const ma_spatializer_config* pConfig, ma_spatializer_heap_layout* pHeapLayout)
  41678. {
  41679. ma_result result;
  41680. MA_ASSERT(pHeapLayout != NULL);
  41681. MA_ZERO_OBJECT(pHeapLayout);
  41682. if (pConfig == NULL) {
  41683. return MA_INVALID_ARGS;
  41684. }
  41685. result = ma_spatializer_validate_config(pConfig);
  41686. if (result != MA_SUCCESS) {
  41687. return result;
  41688. }
  41689. pHeapLayout->sizeInBytes = 0;
  41690. /* Channel map. */
  41691. pHeapLayout->channelMapInOffset = MA_SIZE_MAX; /* <-- MA_SIZE_MAX indicates no allocation necessary. */
  41692. if (pConfig->pChannelMapIn != NULL) {
  41693. pHeapLayout->channelMapInOffset = pHeapLayout->sizeInBytes;
  41694. pHeapLayout->sizeInBytes += ma_align_64(sizeof(*pConfig->pChannelMapIn) * pConfig->channelsIn);
  41695. }
  41696. /* New channel gains for output. */
  41697. pHeapLayout->newChannelGainsOffset = pHeapLayout->sizeInBytes;
  41698. pHeapLayout->sizeInBytes += ma_align_64(sizeof(float) * pConfig->channelsOut);
  41699. /* Gainer. */
  41700. {
  41701. size_t gainerHeapSizeInBytes;
  41702. ma_gainer_config gainerConfig;
  41703. gainerConfig = ma_spatializer_gainer_config_init(pConfig);
  41704. result = ma_gainer_get_heap_size(&gainerConfig, &gainerHeapSizeInBytes);
  41705. if (result != MA_SUCCESS) {
  41706. return result;
  41707. }
  41708. pHeapLayout->gainerOffset = pHeapLayout->sizeInBytes;
  41709. pHeapLayout->sizeInBytes += ma_align_64(gainerHeapSizeInBytes);
  41710. }
  41711. return MA_SUCCESS;
  41712. }
  41713. MA_API ma_result ma_spatializer_get_heap_size(const ma_spatializer_config* pConfig, size_t* pHeapSizeInBytes)
  41714. {
  41715. ma_result result;
  41716. ma_spatializer_heap_layout heapLayout;
  41717. if (pHeapSizeInBytes == NULL) {
  41718. return MA_INVALID_ARGS;
  41719. }
  41720. *pHeapSizeInBytes = 0; /* Safety. */
  41721. result = ma_spatializer_get_heap_layout(pConfig, &heapLayout);
  41722. if (result != MA_SUCCESS) {
  41723. return result;
  41724. }
  41725. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  41726. return MA_SUCCESS;
  41727. }
  41728. MA_API ma_result ma_spatializer_init_preallocated(const ma_spatializer_config* pConfig, void* pHeap, ma_spatializer* pSpatializer)
  41729. {
  41730. ma_result result;
  41731. ma_spatializer_heap_layout heapLayout;
  41732. ma_gainer_config gainerConfig;
  41733. if (pSpatializer == NULL) {
  41734. return MA_INVALID_ARGS;
  41735. }
  41736. MA_ZERO_OBJECT(pSpatializer);
  41737. if (pConfig == NULL || pHeap == NULL) {
  41738. return MA_INVALID_ARGS;
  41739. }
  41740. result = ma_spatializer_get_heap_layout(pConfig, &heapLayout);
  41741. if (result != MA_SUCCESS) {
  41742. return result;
  41743. }
  41744. pSpatializer->_pHeap = pHeap;
  41745. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  41746. pSpatializer->channelsIn = pConfig->channelsIn;
  41747. pSpatializer->channelsOut = pConfig->channelsOut;
  41748. pSpatializer->attenuationModel = pConfig->attenuationModel;
  41749. pSpatializer->positioning = pConfig->positioning;
  41750. pSpatializer->handedness = pConfig->handedness;
  41751. pSpatializer->minGain = pConfig->minGain;
  41752. pSpatializer->maxGain = pConfig->maxGain;
  41753. pSpatializer->minDistance = pConfig->minDistance;
  41754. pSpatializer->maxDistance = pConfig->maxDistance;
  41755. pSpatializer->rolloff = pConfig->rolloff;
  41756. pSpatializer->coneInnerAngleInRadians = pConfig->coneInnerAngleInRadians;
  41757. pSpatializer->coneOuterAngleInRadians = pConfig->coneOuterAngleInRadians;
  41758. pSpatializer->coneOuterGain = pConfig->coneOuterGain;
  41759. pSpatializer->dopplerFactor = pConfig->dopplerFactor;
  41760. pSpatializer->minSpatializationChannelGain = pConfig->minSpatializationChannelGain;
  41761. pSpatializer->directionalAttenuationFactor = pConfig->directionalAttenuationFactor;
  41762. pSpatializer->gainSmoothTimeInFrames = pConfig->gainSmoothTimeInFrames;
  41763. ma_atomic_vec3f_init(&pSpatializer->position, ma_vec3f_init_3f(0, 0, 0));
  41764. ma_atomic_vec3f_init(&pSpatializer->direction, ma_vec3f_init_3f(0, 0, -1));
  41765. ma_atomic_vec3f_init(&pSpatializer->velocity, ma_vec3f_init_3f(0, 0, 0));
  41766. pSpatializer->dopplerPitch = 1;
  41767. /* Swap the forward direction if we're left handed (it was initialized based on right handed). */
  41768. if (pSpatializer->handedness == ma_handedness_left) {
  41769. ma_vec3f negDir = ma_vec3f_neg(ma_spatializer_get_direction(pSpatializer));
  41770. ma_spatializer_set_direction(pSpatializer, negDir.x, negDir.y, negDir.z);
  41771. }
  41772. /* Channel map. This will be on the heap. */
  41773. if (pConfig->pChannelMapIn != NULL) {
  41774. pSpatializer->pChannelMapIn = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapInOffset);
  41775. ma_channel_map_copy_or_default(pSpatializer->pChannelMapIn, pSpatializer->channelsIn, pConfig->pChannelMapIn, pSpatializer->channelsIn);
  41776. }
  41777. /* New channel gains for output channels. */
  41778. pSpatializer->pNewChannelGainsOut = (float*)ma_offset_ptr(pHeap, heapLayout.newChannelGainsOffset);
  41779. /* Gainer. */
  41780. gainerConfig = ma_spatializer_gainer_config_init(pConfig);
  41781. result = ma_gainer_init_preallocated(&gainerConfig, ma_offset_ptr(pHeap, heapLayout.gainerOffset), &pSpatializer->gainer);
  41782. if (result != MA_SUCCESS) {
  41783. return result; /* Failed to initialize the gainer. */
  41784. }
  41785. return MA_SUCCESS;
  41786. }
  41787. MA_API ma_result ma_spatializer_init(const ma_spatializer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer* pSpatializer)
  41788. {
  41789. ma_result result;
  41790. size_t heapSizeInBytes;
  41791. void* pHeap;
  41792. /* We'll need a heap allocation to retrieve the size. */
  41793. result = ma_spatializer_get_heap_size(pConfig, &heapSizeInBytes);
  41794. if (result != MA_SUCCESS) {
  41795. return result;
  41796. }
  41797. if (heapSizeInBytes > 0) {
  41798. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  41799. if (pHeap == NULL) {
  41800. return MA_OUT_OF_MEMORY;
  41801. }
  41802. } else {
  41803. pHeap = NULL;
  41804. }
  41805. result = ma_spatializer_init_preallocated(pConfig, pHeap, pSpatializer);
  41806. if (result != MA_SUCCESS) {
  41807. ma_free(pHeap, pAllocationCallbacks);
  41808. return result;
  41809. }
  41810. pSpatializer->_ownsHeap = MA_TRUE;
  41811. return MA_SUCCESS;
  41812. }
  41813. MA_API void ma_spatializer_uninit(ma_spatializer* pSpatializer, const ma_allocation_callbacks* pAllocationCallbacks)
  41814. {
  41815. if (pSpatializer == NULL) {
  41816. return;
  41817. }
  41818. ma_gainer_uninit(&pSpatializer->gainer, pAllocationCallbacks);
  41819. if (pSpatializer->_ownsHeap) {
  41820. ma_free(pSpatializer->_pHeap, pAllocationCallbacks);
  41821. }
  41822. }
  41823. static float ma_calculate_angular_gain(ma_vec3f dirA, ma_vec3f dirB, float coneInnerAngleInRadians, float coneOuterAngleInRadians, float coneOuterGain)
  41824. {
  41825. /*
  41826. Angular attenuation.
  41827. Unlike distance gain, the math for this is not specified by the OpenAL spec so we'll just go ahead and figure
  41828. this out for ourselves at the expense of possibly being inconsistent with other implementations.
  41829. To do cone attenuation, I'm just using the same math that we'd use to implement a basic spotlight in OpenGL. We
  41830. just need to get the direction from the source to the listener and then do a dot product against that and the
  41831. direction of the spotlight. Then we just compare that dot product against the cosine of the inner and outer
  41832. angles. If the dot product is greater than the the outer angle, we just use coneOuterGain. If it's less than
  41833. the inner angle, we just use a gain of 1. Otherwise we linearly interpolate between 1 and coneOuterGain.
  41834. */
  41835. if (coneInnerAngleInRadians < 6.283185f) {
  41836. float angularGain = 1;
  41837. float cutoffInner = (float)ma_cosd(coneInnerAngleInRadians*0.5f);
  41838. float cutoffOuter = (float)ma_cosd(coneOuterAngleInRadians*0.5f);
  41839. float d;
  41840. d = ma_vec3f_dot(dirA, dirB);
  41841. if (d > cutoffInner) {
  41842. /* It's inside the inner angle. */
  41843. angularGain = 1;
  41844. } else {
  41845. /* It's outside the inner angle. */
  41846. if (d > cutoffOuter) {
  41847. /* It's between the inner and outer angle. We need to linearly interpolate between 1 and coneOuterGain. */
  41848. angularGain = ma_mix_f32(coneOuterGain, 1, (d - cutoffOuter) / (cutoffInner - cutoffOuter));
  41849. } else {
  41850. /* It's outside the outer angle. */
  41851. angularGain = coneOuterGain;
  41852. }
  41853. }
  41854. /*printf("d = %f; cutoffInner = %f; cutoffOuter = %f; angularGain = %f\n", d, cutoffInner, cutoffOuter, angularGain);*/
  41855. return angularGain;
  41856. } else {
  41857. /* Inner angle is 360 degrees so no need to do any attenuation. */
  41858. return 1;
  41859. }
  41860. }
  41861. MA_API ma_result ma_spatializer_process_pcm_frames(ma_spatializer* pSpatializer, ma_spatializer_listener* pListener, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  41862. {
  41863. ma_channel* pChannelMapIn = pSpatializer->pChannelMapIn;
  41864. ma_channel* pChannelMapOut = pListener->config.pChannelMapOut;
  41865. if (pSpatializer == NULL) {
  41866. return MA_INVALID_ARGS;
  41867. }
  41868. /* If we're not spatializing we need to run an optimized path. */
  41869. if (c89atomic_load_i32(&pSpatializer->attenuationModel) == ma_attenuation_model_none) {
  41870. if (ma_spatializer_listener_is_enabled(pListener)) {
  41871. /* No attenuation is required, but we'll need to do some channel conversion. */
  41872. if (pSpatializer->channelsIn == pSpatializer->channelsOut) {
  41873. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, ma_format_f32, pSpatializer->channelsIn);
  41874. } else {
  41875. ma_channel_map_apply_f32((float*)pFramesOut, pChannelMapOut, pSpatializer->channelsOut, (const float*)pFramesIn, pChannelMapIn, pSpatializer->channelsIn, frameCount, ma_channel_mix_mode_rectangular, ma_mono_expansion_mode_default); /* Safe casts to float* because f32 is the only supported format. */
  41876. }
  41877. } else {
  41878. /* The listener is disabled. Output silence. */
  41879. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, pSpatializer->channelsOut);
  41880. }
  41881. /*
  41882. We're not doing attenuation so don't bother with doppler for now. I'm not sure if this is
  41883. the correct thinking so might need to review this later.
  41884. */
  41885. pSpatializer->dopplerPitch = 1;
  41886. } else {
  41887. /*
  41888. Let's first determine which listener the sound is closest to. Need to keep in mind that we
  41889. might not have a world or any listeners, in which case we just spatializer based on the
  41890. listener being positioned at the origin (0, 0, 0).
  41891. */
  41892. ma_vec3f relativePosNormalized;
  41893. ma_vec3f relativePos; /* The position relative to the listener. */
  41894. ma_vec3f relativeDir; /* The direction of the sound, relative to the listener. */
  41895. ma_vec3f listenerVel; /* The volocity of the listener. For doppler pitch calculation. */
  41896. float speedOfSound;
  41897. float distance = 0;
  41898. float gain = 1;
  41899. ma_uint32 iChannel;
  41900. const ma_uint32 channelsOut = pSpatializer->channelsOut;
  41901. const ma_uint32 channelsIn = pSpatializer->channelsIn;
  41902. float minDistance = ma_spatializer_get_min_distance(pSpatializer);
  41903. float maxDistance = ma_spatializer_get_max_distance(pSpatializer);
  41904. float rolloff = ma_spatializer_get_rolloff(pSpatializer);
  41905. float dopplerFactor = ma_spatializer_get_doppler_factor(pSpatializer);
  41906. /*
  41907. We'll need the listener velocity for doppler pitch calculations. The speed of sound is
  41908. defined by the listener, so we'll grab that here too.
  41909. */
  41910. if (pListener != NULL) {
  41911. listenerVel = ma_spatializer_listener_get_velocity(pListener);
  41912. speedOfSound = pListener->config.speedOfSound;
  41913. } else {
  41914. listenerVel = ma_vec3f_init_3f(0, 0, 0);
  41915. speedOfSound = MA_DEFAULT_SPEED_OF_SOUND;
  41916. }
  41917. if (pListener == NULL || ma_spatializer_get_positioning(pSpatializer) == ma_positioning_relative) {
  41918. /* There's no listener or we're using relative positioning. */
  41919. relativePos = ma_spatializer_get_position(pSpatializer);
  41920. relativeDir = ma_spatializer_get_direction(pSpatializer);
  41921. } else {
  41922. /*
  41923. We've found a listener and we're using absolute positioning. We need to transform the
  41924. sound's position and direction so that it's relative to listener. Later on we'll use
  41925. this for determining the factors to apply to each channel to apply the panning effect.
  41926. */
  41927. ma_spatializer_get_relative_position_and_direction(pSpatializer, pListener, &relativePos, &relativeDir);
  41928. }
  41929. distance = ma_vec3f_len(relativePos);
  41930. /* We've gathered the data, so now we can apply some spatialization. */
  41931. switch (ma_spatializer_get_attenuation_model(pSpatializer)) {
  41932. case ma_attenuation_model_inverse:
  41933. {
  41934. gain = ma_attenuation_inverse(distance, minDistance, maxDistance, rolloff);
  41935. } break;
  41936. case ma_attenuation_model_linear:
  41937. {
  41938. gain = ma_attenuation_linear(distance, minDistance, maxDistance, rolloff);
  41939. } break;
  41940. case ma_attenuation_model_exponential:
  41941. {
  41942. gain = ma_attenuation_exponential(distance, minDistance, maxDistance, rolloff);
  41943. } break;
  41944. case ma_attenuation_model_none:
  41945. default:
  41946. {
  41947. gain = 1;
  41948. } break;
  41949. }
  41950. /* Normalize the position. */
  41951. if (distance > 0.001f) {
  41952. float distanceInv = 1/distance;
  41953. relativePosNormalized = relativePos;
  41954. relativePosNormalized.x *= distanceInv;
  41955. relativePosNormalized.y *= distanceInv;
  41956. relativePosNormalized.z *= distanceInv;
  41957. } else {
  41958. distance = 0;
  41959. relativePosNormalized = ma_vec3f_init_3f(0, 0, 0);
  41960. }
  41961. /*
  41962. Angular attenuation.
  41963. Unlike distance gain, the math for this is not specified by the OpenAL spec so we'll just go ahead and figure
  41964. this out for ourselves at the expense of possibly being inconsistent with other implementations.
  41965. To do cone attenuation, I'm just using the same math that we'd use to implement a basic spotlight in OpenGL. We
  41966. just need to get the direction from the source to the listener and then do a dot product against that and the
  41967. direction of the spotlight. Then we just compare that dot product against the cosine of the inner and outer
  41968. angles. If the dot product is greater than the the outer angle, we just use coneOuterGain. If it's less than
  41969. the inner angle, we just use a gain of 1. Otherwise we linearly interpolate between 1 and coneOuterGain.
  41970. */
  41971. if (distance > 0) {
  41972. /* Source anglular gain. */
  41973. float spatializerConeInnerAngle;
  41974. float spatializerConeOuterAngle;
  41975. float spatializerConeOuterGain;
  41976. ma_spatializer_get_cone(pSpatializer, &spatializerConeInnerAngle, &spatializerConeOuterAngle, &spatializerConeOuterGain);
  41977. gain *= ma_calculate_angular_gain(relativeDir, ma_vec3f_neg(relativePosNormalized), spatializerConeInnerAngle, spatializerConeOuterAngle, spatializerConeOuterGain);
  41978. /*
  41979. We're supporting angular gain on the listener as well for those who want to reduce the volume of sounds that
  41980. are positioned behind the listener. On default settings, this will have no effect.
  41981. */
  41982. if (pListener != NULL && pListener->config.coneInnerAngleInRadians < 6.283185f) {
  41983. ma_vec3f listenerDirection;
  41984. float listenerInnerAngle;
  41985. float listenerOuterAngle;
  41986. float listenerOuterGain;
  41987. if (pListener->config.handedness == ma_handedness_right) {
  41988. listenerDirection = ma_vec3f_init_3f(0, 0, -1);
  41989. } else {
  41990. listenerDirection = ma_vec3f_init_3f(0, 0, +1);
  41991. }
  41992. listenerInnerAngle = pListener->config.coneInnerAngleInRadians;
  41993. listenerOuterAngle = pListener->config.coneOuterAngleInRadians;
  41994. listenerOuterGain = pListener->config.coneOuterGain;
  41995. gain *= ma_calculate_angular_gain(listenerDirection, relativePosNormalized, listenerInnerAngle, listenerOuterAngle, listenerOuterGain);
  41996. }
  41997. } else {
  41998. /* The sound is right on top of the listener. Don't do any angular attenuation. */
  41999. }
  42000. /* Clamp the gain. */
  42001. gain = ma_clamp(gain, ma_spatializer_get_min_gain(pSpatializer), ma_spatializer_get_max_gain(pSpatializer));
  42002. /*
  42003. The gain needs to be applied per-channel here. The spatialization code below will be changing the per-channel
  42004. gains which will then eventually be passed into the gainer which will deal with smoothing the gain transitions
  42005. to avoid harsh changes in gain.
  42006. */
  42007. for (iChannel = 0; iChannel < channelsOut; iChannel += 1) {
  42008. pSpatializer->pNewChannelGainsOut[iChannel] = gain;
  42009. }
  42010. /*
  42011. Convert to our output channel count. If the listener is disabled we just output silence here. We cannot ignore
  42012. the whole section of code here because we need to update some internal spatialization state.
  42013. */
  42014. if (ma_spatializer_listener_is_enabled(pListener)) {
  42015. ma_channel_map_apply_f32((float*)pFramesOut, pChannelMapOut, channelsOut, (const float*)pFramesIn, pChannelMapIn, channelsIn, frameCount, ma_channel_mix_mode_rectangular, ma_mono_expansion_mode_default);
  42016. } else {
  42017. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, pSpatializer->channelsOut);
  42018. }
  42019. /*
  42020. Panning. This is where we'll apply the gain and convert to the output channel count. We have an optimized path for
  42021. when we're converting to a mono stream. In that case we don't really need to do any panning - we just apply the
  42022. gain to the final output.
  42023. */
  42024. /*printf("distance=%f; gain=%f\n", distance, gain);*/
  42025. /* We must have a valid channel map here to ensure we spatialize properly. */
  42026. MA_ASSERT(pChannelMapOut != NULL);
  42027. /*
  42028. We're not converting to mono so we'll want to apply some panning. This is where the feeling of something being
  42029. to the left, right, infront or behind the listener is calculated. I'm just using a basic model here. Note that
  42030. the code below is not based on any specific algorithm. I'm just implementing this off the top of my head and
  42031. seeing how it goes. There might be better ways to do this.
  42032. To determine the direction of the sound relative to a speaker I'm using dot products. Each speaker is given a
  42033. direction. For example, the left channel in a stereo system will be -1 on the X axis and the right channel will
  42034. be +1 on the X axis. A dot product is performed against the direction vector of the channel and the normalized
  42035. position of the sound.
  42036. */
  42037. /*
  42038. Calculate our per-channel gains. We do this based on the normalized relative position of the sound and it's
  42039. relation to the direction of the channel.
  42040. */
  42041. if (distance > 0) {
  42042. ma_vec3f unitPos = relativePos;
  42043. float distanceInv = 1/distance;
  42044. unitPos.x *= distanceInv;
  42045. unitPos.y *= distanceInv;
  42046. unitPos.z *= distanceInv;
  42047. for (iChannel = 0; iChannel < channelsOut; iChannel += 1) {
  42048. ma_channel channelOut;
  42049. float d;
  42050. float dMin;
  42051. channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannel);
  42052. if (ma_is_spatial_channel_position(channelOut)) {
  42053. d = ma_mix_f32_fast(1, ma_vec3f_dot(unitPos, ma_get_channel_direction(channelOut)), ma_spatializer_get_directional_attenuation_factor(pSpatializer));
  42054. } else {
  42055. d = 1; /* It's not a spatial channel so there's no real notion of direction. */
  42056. }
  42057. /*
  42058. In my testing, if the panning effect is too aggressive it makes spatialization feel uncomfortable.
  42059. The "dMin" variable below is used to control the aggressiveness of the panning effect. When set to
  42060. 0, panning will be most extreme and any sounds that are positioned on the opposite side of the
  42061. speaker will be completely silent from that speaker. Not only does this feel uncomfortable, it
  42062. doesn't even remotely represent the real world at all because sounds that come from your right side
  42063. are still clearly audible from your left side. Setting "dMin" to 1 will result in no panning at
  42064. all, which is also not ideal. By setting it to something greater than 0, the spatialization effect
  42065. becomes much less dramatic and a lot more bearable.
  42066. Summary: 0 = more extreme panning; 1 = no panning.
  42067. */
  42068. dMin = pSpatializer->minSpatializationChannelGain;
  42069. /*
  42070. At this point, "d" will be positive if the sound is on the same side as the channel and negative if
  42071. it's on the opposite side. It will be in the range of -1..1. There's two ways I can think of to
  42072. calculate a panning value. The first is to simply convert it to 0..1, however this has a problem
  42073. which I'm not entirely happy with. Considering a stereo system, when a sound is positioned right
  42074. in front of the listener it'll result in each speaker getting a gain of 0.5. I don't know if I like
  42075. the idea of having a scaling factor of 0.5 being applied to a sound when it's sitting right in front
  42076. of the listener. I would intuitively expect that to be played at full volume, or close to it.
  42077. The second idea I think of is to only apply a reduction in gain when the sound is on the opposite
  42078. side of the speaker. That is, reduce the gain only when the dot product is negative. The problem
  42079. with this is that there will not be any attenuation as the sound sweeps around the 180 degrees
  42080. where the dot product is positive. The idea with this option is that you leave the gain at 1 when
  42081. the sound is being played on the same side as the speaker and then you just reduce the volume when
  42082. the sound is on the other side.
  42083. The summarize, I think the first option should give a better sense of spatialization, but the second
  42084. option is better for preserving the sound's power.
  42085. UPDATE: In my testing, I find the first option to sound better. You can feel the sense of space a
  42086. bit better, but you can also hear the reduction in volume when it's right in front.
  42087. */
  42088. #if 1
  42089. {
  42090. /*
  42091. Scale the dot product from -1..1 to 0..1. Will result in a sound directly in front losing power
  42092. by being played at 0.5 gain.
  42093. */
  42094. d = (d + 1) * 0.5f; /* -1..1 to 0..1 */
  42095. d = ma_max(d, dMin);
  42096. pSpatializer->pNewChannelGainsOut[iChannel] *= d;
  42097. }
  42098. #else
  42099. {
  42100. /*
  42101. Only reduce the volume of the sound if it's on the opposite side. This path keeps the volume more
  42102. consistent, but comes at the expense of a worse sense of space and positioning.
  42103. */
  42104. if (d < 0) {
  42105. d += 1; /* Move into the positive range. */
  42106. d = ma_max(d, dMin);
  42107. channelGainsOut[iChannel] *= d;
  42108. }
  42109. }
  42110. #endif
  42111. }
  42112. } else {
  42113. /* Assume the sound is right on top of us. Don't do any panning. */
  42114. }
  42115. /* Now we need to apply the volume to each channel. This needs to run through the gainer to ensure we get a smooth volume transition. */
  42116. ma_gainer_set_gains(&pSpatializer->gainer, pSpatializer->pNewChannelGainsOut);
  42117. ma_gainer_process_pcm_frames(&pSpatializer->gainer, pFramesOut, pFramesOut, frameCount);
  42118. /*
  42119. Before leaving we'll want to update our doppler pitch so that the caller can apply some
  42120. pitch shifting if they desire. Note that we need to negate the relative position here
  42121. because the doppler calculation needs to be source-to-listener, but ours is listener-to-
  42122. source.
  42123. */
  42124. if (dopplerFactor > 0) {
  42125. pSpatializer->dopplerPitch = ma_doppler_pitch(ma_vec3f_sub(ma_spatializer_listener_get_position(pListener), ma_spatializer_get_position(pSpatializer)), ma_spatializer_get_velocity(pSpatializer), listenerVel, speedOfSound, dopplerFactor);
  42126. } else {
  42127. pSpatializer->dopplerPitch = 1;
  42128. }
  42129. }
  42130. return MA_SUCCESS;
  42131. }
  42132. MA_API ma_result ma_spatializer_set_master_volume(ma_spatializer* pSpatializer, float volume)
  42133. {
  42134. if (pSpatializer == NULL) {
  42135. return MA_INVALID_ARGS;
  42136. }
  42137. return ma_gainer_set_master_volume(&pSpatializer->gainer, volume);
  42138. }
  42139. MA_API ma_result ma_spatializer_get_master_volume(const ma_spatializer* pSpatializer, float* pVolume)
  42140. {
  42141. if (pSpatializer == NULL) {
  42142. return MA_INVALID_ARGS;
  42143. }
  42144. return ma_gainer_get_master_volume(&pSpatializer->gainer, pVolume);
  42145. }
  42146. MA_API ma_uint32 ma_spatializer_get_input_channels(const ma_spatializer* pSpatializer)
  42147. {
  42148. if (pSpatializer == NULL) {
  42149. return 0;
  42150. }
  42151. return pSpatializer->channelsIn;
  42152. }
  42153. MA_API ma_uint32 ma_spatializer_get_output_channels(const ma_spatializer* pSpatializer)
  42154. {
  42155. if (pSpatializer == NULL) {
  42156. return 0;
  42157. }
  42158. return pSpatializer->channelsOut;
  42159. }
  42160. MA_API void ma_spatializer_set_attenuation_model(ma_spatializer* pSpatializer, ma_attenuation_model attenuationModel)
  42161. {
  42162. if (pSpatializer == NULL) {
  42163. return;
  42164. }
  42165. c89atomic_exchange_i32(&pSpatializer->attenuationModel, attenuationModel);
  42166. }
  42167. MA_API ma_attenuation_model ma_spatializer_get_attenuation_model(const ma_spatializer* pSpatializer)
  42168. {
  42169. if (pSpatializer == NULL) {
  42170. return ma_attenuation_model_none;
  42171. }
  42172. return (ma_attenuation_model)c89atomic_load_i32(&pSpatializer->attenuationModel);
  42173. }
  42174. MA_API void ma_spatializer_set_positioning(ma_spatializer* pSpatializer, ma_positioning positioning)
  42175. {
  42176. if (pSpatializer == NULL) {
  42177. return;
  42178. }
  42179. c89atomic_exchange_i32(&pSpatializer->positioning, positioning);
  42180. }
  42181. MA_API ma_positioning ma_spatializer_get_positioning(const ma_spatializer* pSpatializer)
  42182. {
  42183. if (pSpatializer == NULL) {
  42184. return ma_positioning_absolute;
  42185. }
  42186. return (ma_positioning)c89atomic_load_i32(&pSpatializer->positioning);
  42187. }
  42188. MA_API void ma_spatializer_set_rolloff(ma_spatializer* pSpatializer, float rolloff)
  42189. {
  42190. if (pSpatializer == NULL) {
  42191. return;
  42192. }
  42193. c89atomic_exchange_f32(&pSpatializer->rolloff, rolloff);
  42194. }
  42195. MA_API float ma_spatializer_get_rolloff(const ma_spatializer* pSpatializer)
  42196. {
  42197. if (pSpatializer == NULL) {
  42198. return 0;
  42199. }
  42200. return c89atomic_load_f32(&pSpatializer->rolloff);
  42201. }
  42202. MA_API void ma_spatializer_set_min_gain(ma_spatializer* pSpatializer, float minGain)
  42203. {
  42204. if (pSpatializer == NULL) {
  42205. return;
  42206. }
  42207. c89atomic_exchange_f32(&pSpatializer->minGain, minGain);
  42208. }
  42209. MA_API float ma_spatializer_get_min_gain(const ma_spatializer* pSpatializer)
  42210. {
  42211. if (pSpatializer == NULL) {
  42212. return 0;
  42213. }
  42214. return c89atomic_load_f32(&pSpatializer->minGain);
  42215. }
  42216. MA_API void ma_spatializer_set_max_gain(ma_spatializer* pSpatializer, float maxGain)
  42217. {
  42218. if (pSpatializer == NULL) {
  42219. return;
  42220. }
  42221. c89atomic_exchange_f32(&pSpatializer->maxGain, maxGain);
  42222. }
  42223. MA_API float ma_spatializer_get_max_gain(const ma_spatializer* pSpatializer)
  42224. {
  42225. if (pSpatializer == NULL) {
  42226. return 0;
  42227. }
  42228. return c89atomic_load_f32(&pSpatializer->maxGain);
  42229. }
  42230. MA_API void ma_spatializer_set_min_distance(ma_spatializer* pSpatializer, float minDistance)
  42231. {
  42232. if (pSpatializer == NULL) {
  42233. return;
  42234. }
  42235. c89atomic_exchange_f32(&pSpatializer->minDistance, minDistance);
  42236. }
  42237. MA_API float ma_spatializer_get_min_distance(const ma_spatializer* pSpatializer)
  42238. {
  42239. if (pSpatializer == NULL) {
  42240. return 0;
  42241. }
  42242. return c89atomic_load_f32(&pSpatializer->minDistance);
  42243. }
  42244. MA_API void ma_spatializer_set_max_distance(ma_spatializer* pSpatializer, float maxDistance)
  42245. {
  42246. if (pSpatializer == NULL) {
  42247. return;
  42248. }
  42249. c89atomic_exchange_f32(&pSpatializer->maxDistance, maxDistance);
  42250. }
  42251. MA_API float ma_spatializer_get_max_distance(const ma_spatializer* pSpatializer)
  42252. {
  42253. if (pSpatializer == NULL) {
  42254. return 0;
  42255. }
  42256. return c89atomic_load_f32(&pSpatializer->maxDistance);
  42257. }
  42258. MA_API void ma_spatializer_set_cone(ma_spatializer* pSpatializer, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  42259. {
  42260. if (pSpatializer == NULL) {
  42261. return;
  42262. }
  42263. c89atomic_exchange_f32(&pSpatializer->coneInnerAngleInRadians, innerAngleInRadians);
  42264. c89atomic_exchange_f32(&pSpatializer->coneOuterAngleInRadians, outerAngleInRadians);
  42265. c89atomic_exchange_f32(&pSpatializer->coneOuterGain, outerGain);
  42266. }
  42267. MA_API void ma_spatializer_get_cone(const ma_spatializer* pSpatializer, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  42268. {
  42269. if (pSpatializer == NULL) {
  42270. return;
  42271. }
  42272. if (pInnerAngleInRadians != NULL) {
  42273. *pInnerAngleInRadians = c89atomic_load_f32(&pSpatializer->coneInnerAngleInRadians);
  42274. }
  42275. if (pOuterAngleInRadians != NULL) {
  42276. *pOuterAngleInRadians = c89atomic_load_f32(&pSpatializer->coneOuterAngleInRadians);
  42277. }
  42278. if (pOuterGain != NULL) {
  42279. *pOuterGain = c89atomic_load_f32(&pSpatializer->coneOuterGain);
  42280. }
  42281. }
  42282. MA_API void ma_spatializer_set_doppler_factor(ma_spatializer* pSpatializer, float dopplerFactor)
  42283. {
  42284. if (pSpatializer == NULL) {
  42285. return;
  42286. }
  42287. c89atomic_exchange_f32(&pSpatializer->dopplerFactor, dopplerFactor);
  42288. }
  42289. MA_API float ma_spatializer_get_doppler_factor(const ma_spatializer* pSpatializer)
  42290. {
  42291. if (pSpatializer == NULL) {
  42292. return 1;
  42293. }
  42294. return c89atomic_load_f32(&pSpatializer->dopplerFactor);
  42295. }
  42296. MA_API void ma_spatializer_set_directional_attenuation_factor(ma_spatializer* pSpatializer, float directionalAttenuationFactor)
  42297. {
  42298. if (pSpatializer == NULL) {
  42299. return;
  42300. }
  42301. c89atomic_exchange_f32(&pSpatializer->directionalAttenuationFactor, directionalAttenuationFactor);
  42302. }
  42303. MA_API float ma_spatializer_get_directional_attenuation_factor(const ma_spatializer* pSpatializer)
  42304. {
  42305. if (pSpatializer == NULL) {
  42306. return 1;
  42307. }
  42308. return c89atomic_load_f32(&pSpatializer->directionalAttenuationFactor);
  42309. }
  42310. MA_API void ma_spatializer_set_position(ma_spatializer* pSpatializer, float x, float y, float z)
  42311. {
  42312. if (pSpatializer == NULL) {
  42313. return;
  42314. }
  42315. ma_atomic_vec3f_set(&pSpatializer->position, ma_vec3f_init_3f(x, y, z));
  42316. }
  42317. MA_API ma_vec3f ma_spatializer_get_position(const ma_spatializer* pSpatializer)
  42318. {
  42319. if (pSpatializer == NULL) {
  42320. return ma_vec3f_init_3f(0, 0, 0);
  42321. }
  42322. return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pSpatializer->position); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */
  42323. }
  42324. MA_API void ma_spatializer_set_direction(ma_spatializer* pSpatializer, float x, float y, float z)
  42325. {
  42326. if (pSpatializer == NULL) {
  42327. return;
  42328. }
  42329. ma_atomic_vec3f_set(&pSpatializer->direction, ma_vec3f_init_3f(x, y, z));
  42330. }
  42331. MA_API ma_vec3f ma_spatializer_get_direction(const ma_spatializer* pSpatializer)
  42332. {
  42333. if (pSpatializer == NULL) {
  42334. return ma_vec3f_init_3f(0, 0, -1);
  42335. }
  42336. return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pSpatializer->direction); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */
  42337. }
  42338. MA_API void ma_spatializer_set_velocity(ma_spatializer* pSpatializer, float x, float y, float z)
  42339. {
  42340. if (pSpatializer == NULL) {
  42341. return;
  42342. }
  42343. ma_atomic_vec3f_set(&pSpatializer->velocity, ma_vec3f_init_3f(x, y, z));
  42344. }
  42345. MA_API ma_vec3f ma_spatializer_get_velocity(const ma_spatializer* pSpatializer)
  42346. {
  42347. if (pSpatializer == NULL) {
  42348. return ma_vec3f_init_3f(0, 0, 0);
  42349. }
  42350. return ma_atomic_vec3f_get((ma_atomic_vec3f*)&pSpatializer->velocity); /* Naughty const-cast. It's just for atomically loading the vec3 which should be safe. */
  42351. }
  42352. MA_API void ma_spatializer_get_relative_position_and_direction(const ma_spatializer* pSpatializer, const ma_spatializer_listener* pListener, ma_vec3f* pRelativePos, ma_vec3f* pRelativeDir)
  42353. {
  42354. if (pRelativePos != NULL) {
  42355. pRelativePos->x = 0;
  42356. pRelativePos->y = 0;
  42357. pRelativePos->z = 0;
  42358. }
  42359. if (pRelativeDir != NULL) {
  42360. pRelativeDir->x = 0;
  42361. pRelativeDir->y = 0;
  42362. pRelativeDir->z = -1;
  42363. }
  42364. if (pSpatializer == NULL) {
  42365. return;
  42366. }
  42367. if (pListener == NULL || ma_spatializer_get_positioning(pSpatializer) == ma_positioning_relative) {
  42368. /* There's no listener or we're using relative positioning. */
  42369. if (pRelativePos != NULL) {
  42370. *pRelativePos = ma_spatializer_get_position(pSpatializer);
  42371. }
  42372. if (pRelativeDir != NULL) {
  42373. *pRelativeDir = ma_spatializer_get_direction(pSpatializer);
  42374. }
  42375. } else {
  42376. ma_vec3f spatializerPosition;
  42377. ma_vec3f spatializerDirection;
  42378. ma_vec3f listenerPosition;
  42379. ma_vec3f listenerDirection;
  42380. ma_vec3f v;
  42381. ma_vec3f axisX;
  42382. ma_vec3f axisY;
  42383. ma_vec3f axisZ;
  42384. float m[4][4];
  42385. spatializerPosition = ma_spatializer_get_position(pSpatializer);
  42386. spatializerDirection = ma_spatializer_get_direction(pSpatializer);
  42387. listenerPosition = ma_spatializer_listener_get_position(pListener);
  42388. listenerDirection = ma_spatializer_listener_get_direction(pListener);
  42389. /*
  42390. We need to calcualte the right vector from our forward and up vectors. This is done with
  42391. a cross product.
  42392. */
  42393. axisZ = ma_vec3f_normalize(listenerDirection); /* Normalization required here because we can't trust the caller. */
  42394. axisX = ma_vec3f_normalize(ma_vec3f_cross(axisZ, pListener->config.worldUp)); /* Normalization required here because the world up vector may not be perpendicular with the forward vector. */
  42395. /*
  42396. The calculation of axisX above can result in a zero-length vector if the listener is
  42397. looking straight up on the Y axis. We'll need to fall back to a +X in this case so that
  42398. the calculations below don't fall apart. This is where a quaternion based listener and
  42399. sound orientation would come in handy.
  42400. */
  42401. if (ma_vec3f_len2(axisX) == 0) {
  42402. axisX = ma_vec3f_init_3f(1, 0, 0);
  42403. }
  42404. axisY = ma_vec3f_cross(axisX, axisZ); /* No normalization is required here because axisX and axisZ are unit length and perpendicular. */
  42405. /*
  42406. We need to swap the X axis if we're left handed because otherwise the cross product above
  42407. will have resulted in it pointing in the wrong direction (right handed was assumed in the
  42408. cross products above).
  42409. */
  42410. if (pListener->config.handedness == ma_handedness_left) {
  42411. axisX = ma_vec3f_neg(axisX);
  42412. }
  42413. /* Lookat. */
  42414. m[0][0] = axisX.x; m[1][0] = axisX.y; m[2][0] = axisX.z; m[3][0] = -ma_vec3f_dot(axisX, listenerPosition);
  42415. m[0][1] = axisY.x; m[1][1] = axisY.y; m[2][1] = axisY.z; m[3][1] = -ma_vec3f_dot(axisY, listenerPosition);
  42416. m[0][2] = -axisZ.x; m[1][2] = -axisZ.y; m[2][2] = -axisZ.z; m[3][2] = -ma_vec3f_dot(ma_vec3f_neg(axisZ), listenerPosition);
  42417. m[0][3] = 0; m[1][3] = 0; m[2][3] = 0; m[3][3] = 1;
  42418. /*
  42419. Multiply the lookat matrix by the spatializer position to transform it to listener
  42420. space. This allows calculations to work based on the sound being relative to the
  42421. origin which makes things simpler.
  42422. */
  42423. if (pRelativePos != NULL) {
  42424. v = spatializerPosition;
  42425. pRelativePos->x = m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z + m[3][0] * 1;
  42426. pRelativePos->y = m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z + m[3][1] * 1;
  42427. pRelativePos->z = m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z + m[3][2] * 1;
  42428. }
  42429. /*
  42430. The direction of the sound needs to also be transformed so that it's relative to the
  42431. rotation of the listener.
  42432. */
  42433. if (pRelativeDir != NULL) {
  42434. v = spatializerDirection;
  42435. pRelativeDir->x = m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z;
  42436. pRelativeDir->y = m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z;
  42437. pRelativeDir->z = m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z;
  42438. }
  42439. }
  42440. }
  42441. /**************************************************************************************************************************************************************
  42442. Resampling
  42443. **************************************************************************************************************************************************************/
  42444. MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  42445. {
  42446. ma_linear_resampler_config config;
  42447. MA_ZERO_OBJECT(&config);
  42448. config.format = format;
  42449. config.channels = channels;
  42450. config.sampleRateIn = sampleRateIn;
  42451. config.sampleRateOut = sampleRateOut;
  42452. config.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
  42453. config.lpfNyquistFactor = 1;
  42454. return config;
  42455. }
  42456. typedef struct
  42457. {
  42458. size_t sizeInBytes;
  42459. size_t x0Offset;
  42460. size_t x1Offset;
  42461. size_t lpfOffset;
  42462. } ma_linear_resampler_heap_layout;
  42463. static void ma_linear_resampler_adjust_timer_for_new_rate(ma_linear_resampler* pResampler, ma_uint32 oldSampleRateOut, ma_uint32 newSampleRateOut)
  42464. {
  42465. /*
  42466. So what's happening here? Basically we need to adjust the fractional component of the time advance based on the new rate. The old time advance will
  42467. be based on the old sample rate, but we are needing to adjust it to that it's based on the new sample rate.
  42468. */
  42469. ma_uint32 oldRateTimeWhole = pResampler->inTimeFrac / oldSampleRateOut; /* <-- This should almost never be anything other than 0, but leaving it here to make this more general and robust just in case. */
  42470. ma_uint32 oldRateTimeFract = pResampler->inTimeFrac % oldSampleRateOut;
  42471. pResampler->inTimeFrac =
  42472. (oldRateTimeWhole * newSampleRateOut) +
  42473. ((oldRateTimeFract * newSampleRateOut) / oldSampleRateOut);
  42474. /* Make sure the fractional part is less than the output sample rate. */
  42475. pResampler->inTimeInt += pResampler->inTimeFrac / pResampler->config.sampleRateOut;
  42476. pResampler->inTimeFrac = pResampler->inTimeFrac % pResampler->config.sampleRateOut;
  42477. }
  42478. static ma_result ma_linear_resampler_set_rate_internal(ma_linear_resampler* pResampler, void* pHeap, ma_linear_resampler_heap_layout* pHeapLayout, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_bool32 isResamplerAlreadyInitialized)
  42479. {
  42480. ma_result result;
  42481. ma_uint32 gcf;
  42482. ma_uint32 lpfSampleRate;
  42483. double lpfCutoffFrequency;
  42484. ma_lpf_config lpfConfig;
  42485. ma_uint32 oldSampleRateOut; /* Required for adjusting time advance down the bottom. */
  42486. if (pResampler == NULL) {
  42487. return MA_INVALID_ARGS;
  42488. }
  42489. if (sampleRateIn == 0 || sampleRateOut == 0) {
  42490. return MA_INVALID_ARGS;
  42491. }
  42492. oldSampleRateOut = pResampler->config.sampleRateOut;
  42493. pResampler->config.sampleRateIn = sampleRateIn;
  42494. pResampler->config.sampleRateOut = sampleRateOut;
  42495. /* Simplify the sample rate. */
  42496. gcf = ma_gcf_u32(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut);
  42497. pResampler->config.sampleRateIn /= gcf;
  42498. pResampler->config.sampleRateOut /= gcf;
  42499. /* Always initialize the low-pass filter, even when the order is 0. */
  42500. if (pResampler->config.lpfOrder > MA_MAX_FILTER_ORDER) {
  42501. return MA_INVALID_ARGS;
  42502. }
  42503. lpfSampleRate = (ma_uint32)(ma_max(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut));
  42504. lpfCutoffFrequency = ( double)(ma_min(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut) * 0.5 * pResampler->config.lpfNyquistFactor);
  42505. lpfConfig = ma_lpf_config_init(pResampler->config.format, pResampler->config.channels, lpfSampleRate, lpfCutoffFrequency, pResampler->config.lpfOrder);
  42506. /*
  42507. If the resampler is alreay initialized we don't want to do a fresh initialization of the low-pass filter because it will result in the cached frames
  42508. getting cleared. Instead we re-initialize the filter which will maintain any cached frames.
  42509. */
  42510. if (isResamplerAlreadyInitialized) {
  42511. result = ma_lpf_reinit(&lpfConfig, &pResampler->lpf);
  42512. } else {
  42513. result = ma_lpf_init_preallocated(&lpfConfig, ma_offset_ptr(pHeap, pHeapLayout->lpfOffset), &pResampler->lpf);
  42514. }
  42515. if (result != MA_SUCCESS) {
  42516. return result;
  42517. }
  42518. pResampler->inAdvanceInt = pResampler->config.sampleRateIn / pResampler->config.sampleRateOut;
  42519. pResampler->inAdvanceFrac = pResampler->config.sampleRateIn % pResampler->config.sampleRateOut;
  42520. /* Our timer was based on the old rate. We need to adjust it so that it's based on the new rate. */
  42521. ma_linear_resampler_adjust_timer_for_new_rate(pResampler, oldSampleRateOut, pResampler->config.sampleRateOut);
  42522. return MA_SUCCESS;
  42523. }
  42524. static ma_result ma_linear_resampler_get_heap_layout(const ma_linear_resampler_config* pConfig, ma_linear_resampler_heap_layout* pHeapLayout)
  42525. {
  42526. MA_ASSERT(pHeapLayout != NULL);
  42527. MA_ZERO_OBJECT(pHeapLayout);
  42528. if (pConfig == NULL) {
  42529. return MA_INVALID_ARGS;
  42530. }
  42531. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  42532. return MA_INVALID_ARGS;
  42533. }
  42534. if (pConfig->channels == 0) {
  42535. return MA_INVALID_ARGS;
  42536. }
  42537. pHeapLayout->sizeInBytes = 0;
  42538. /* x0 */
  42539. pHeapLayout->x0Offset = pHeapLayout->sizeInBytes;
  42540. if (pConfig->format == ma_format_f32) {
  42541. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  42542. } else {
  42543. pHeapLayout->sizeInBytes += sizeof(ma_int16) * pConfig->channels;
  42544. }
  42545. /* x1 */
  42546. pHeapLayout->x1Offset = pHeapLayout->sizeInBytes;
  42547. if (pConfig->format == ma_format_f32) {
  42548. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  42549. } else {
  42550. pHeapLayout->sizeInBytes += sizeof(ma_int16) * pConfig->channels;
  42551. }
  42552. /* LPF */
  42553. pHeapLayout->lpfOffset = ma_align_64(pHeapLayout->sizeInBytes);
  42554. {
  42555. ma_result result;
  42556. size_t lpfHeapSizeInBytes;
  42557. ma_lpf_config lpfConfig = ma_lpf_config_init(pConfig->format, pConfig->channels, 1, 1, pConfig->lpfOrder); /* Sample rate and cutoff frequency do not matter. */
  42558. result = ma_lpf_get_heap_size(&lpfConfig, &lpfHeapSizeInBytes);
  42559. if (result != MA_SUCCESS) {
  42560. return result;
  42561. }
  42562. pHeapLayout->sizeInBytes += lpfHeapSizeInBytes;
  42563. }
  42564. /* Make sure allocation size is aligned. */
  42565. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  42566. return MA_SUCCESS;
  42567. }
  42568. MA_API ma_result ma_linear_resampler_get_heap_size(const ma_linear_resampler_config* pConfig, size_t* pHeapSizeInBytes)
  42569. {
  42570. ma_result result;
  42571. ma_linear_resampler_heap_layout heapLayout;
  42572. if (pHeapSizeInBytes == NULL) {
  42573. return MA_INVALID_ARGS;
  42574. }
  42575. *pHeapSizeInBytes = 0;
  42576. result = ma_linear_resampler_get_heap_layout(pConfig, &heapLayout);
  42577. if (result != MA_SUCCESS) {
  42578. return result;
  42579. }
  42580. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  42581. return MA_SUCCESS;
  42582. }
  42583. MA_API ma_result ma_linear_resampler_init_preallocated(const ma_linear_resampler_config* pConfig, void* pHeap, ma_linear_resampler* pResampler)
  42584. {
  42585. ma_result result;
  42586. ma_linear_resampler_heap_layout heapLayout;
  42587. if (pResampler == NULL) {
  42588. return MA_INVALID_ARGS;
  42589. }
  42590. MA_ZERO_OBJECT(pResampler);
  42591. result = ma_linear_resampler_get_heap_layout(pConfig, &heapLayout);
  42592. if (result != MA_SUCCESS) {
  42593. return result;
  42594. }
  42595. pResampler->config = *pConfig;
  42596. pResampler->_pHeap = pHeap;
  42597. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  42598. if (pConfig->format == ma_format_f32) {
  42599. pResampler->x0.f32 = (float*)ma_offset_ptr(pHeap, heapLayout.x0Offset);
  42600. pResampler->x1.f32 = (float*)ma_offset_ptr(pHeap, heapLayout.x1Offset);
  42601. } else {
  42602. pResampler->x0.s16 = (ma_int16*)ma_offset_ptr(pHeap, heapLayout.x0Offset);
  42603. pResampler->x1.s16 = (ma_int16*)ma_offset_ptr(pHeap, heapLayout.x1Offset);
  42604. }
  42605. /* Setting the rate will set up the filter and time advances for us. */
  42606. result = ma_linear_resampler_set_rate_internal(pResampler, pHeap, &heapLayout, pConfig->sampleRateIn, pConfig->sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_FALSE);
  42607. if (result != MA_SUCCESS) {
  42608. return result;
  42609. }
  42610. pResampler->inTimeInt = 1; /* Set this to one to force an input sample to always be loaded for the first output frame. */
  42611. pResampler->inTimeFrac = 0;
  42612. return MA_SUCCESS;
  42613. }
  42614. MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_linear_resampler* pResampler)
  42615. {
  42616. ma_result result;
  42617. size_t heapSizeInBytes;
  42618. void* pHeap;
  42619. result = ma_linear_resampler_get_heap_size(pConfig, &heapSizeInBytes);
  42620. if (result != MA_SUCCESS) {
  42621. return result;
  42622. }
  42623. if (heapSizeInBytes > 0) {
  42624. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  42625. if (pHeap == NULL) {
  42626. return MA_OUT_OF_MEMORY;
  42627. }
  42628. } else {
  42629. pHeap = NULL;
  42630. }
  42631. result = ma_linear_resampler_init_preallocated(pConfig, pHeap, pResampler);
  42632. if (result != MA_SUCCESS) {
  42633. ma_free(pHeap, pAllocationCallbacks);
  42634. return result;
  42635. }
  42636. pResampler->_ownsHeap = MA_TRUE;
  42637. return MA_SUCCESS;
  42638. }
  42639. MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks)
  42640. {
  42641. if (pResampler == NULL) {
  42642. return;
  42643. }
  42644. ma_lpf_uninit(&pResampler->lpf, pAllocationCallbacks);
  42645. if (pResampler->_ownsHeap) {
  42646. ma_free(pResampler->_pHeap, pAllocationCallbacks);
  42647. }
  42648. }
  42649. static MA_INLINE ma_int16 ma_linear_resampler_mix_s16(ma_int16 x, ma_int16 y, ma_int32 a, const ma_int32 shift)
  42650. {
  42651. ma_int32 b;
  42652. ma_int32 c;
  42653. ma_int32 r;
  42654. MA_ASSERT(a <= (1<<shift));
  42655. b = x * ((1<<shift) - a);
  42656. c = y * a;
  42657. r = b + c;
  42658. return (ma_int16)(r >> shift);
  42659. }
  42660. static void ma_linear_resampler_interpolate_frame_s16(ma_linear_resampler* pResampler, ma_int16* MA_RESTRICT pFrameOut)
  42661. {
  42662. ma_uint32 c;
  42663. ma_uint32 a;
  42664. const ma_uint32 channels = pResampler->config.channels;
  42665. const ma_uint32 shift = 12;
  42666. MA_ASSERT(pResampler != NULL);
  42667. MA_ASSERT(pFrameOut != NULL);
  42668. a = (pResampler->inTimeFrac << shift) / pResampler->config.sampleRateOut;
  42669. MA_ASSUME(channels > 0);
  42670. for (c = 0; c < channels; c += 1) {
  42671. ma_int16 s = ma_linear_resampler_mix_s16(pResampler->x0.s16[c], pResampler->x1.s16[c], a, shift);
  42672. pFrameOut[c] = s;
  42673. }
  42674. }
  42675. static void ma_linear_resampler_interpolate_frame_f32(ma_linear_resampler* pResampler, float* MA_RESTRICT pFrameOut)
  42676. {
  42677. ma_uint32 c;
  42678. float a;
  42679. const ma_uint32 channels = pResampler->config.channels;
  42680. MA_ASSERT(pResampler != NULL);
  42681. MA_ASSERT(pFrameOut != NULL);
  42682. a = (float)pResampler->inTimeFrac / pResampler->config.sampleRateOut;
  42683. MA_ASSUME(channels > 0);
  42684. for (c = 0; c < channels; c += 1) {
  42685. float s = ma_mix_f32_fast(pResampler->x0.f32[c], pResampler->x1.f32[c], a);
  42686. pFrameOut[c] = s;
  42687. }
  42688. }
  42689. static ma_result ma_linear_resampler_process_pcm_frames_s16_downsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  42690. {
  42691. const ma_int16* pFramesInS16;
  42692. /* */ ma_int16* pFramesOutS16;
  42693. ma_uint64 frameCountIn;
  42694. ma_uint64 frameCountOut;
  42695. ma_uint64 framesProcessedIn;
  42696. ma_uint64 framesProcessedOut;
  42697. MA_ASSERT(pResampler != NULL);
  42698. MA_ASSERT(pFrameCountIn != NULL);
  42699. MA_ASSERT(pFrameCountOut != NULL);
  42700. pFramesInS16 = (const ma_int16*)pFramesIn;
  42701. pFramesOutS16 = ( ma_int16*)pFramesOut;
  42702. frameCountIn = *pFrameCountIn;
  42703. frameCountOut = *pFrameCountOut;
  42704. framesProcessedIn = 0;
  42705. framesProcessedOut = 0;
  42706. while (framesProcessedOut < frameCountOut) {
  42707. /* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */
  42708. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  42709. ma_uint32 iChannel;
  42710. if (pFramesInS16 != NULL) {
  42711. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42712. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  42713. pResampler->x1.s16[iChannel] = pFramesInS16[iChannel];
  42714. }
  42715. pFramesInS16 += pResampler->config.channels;
  42716. } else {
  42717. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42718. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  42719. pResampler->x1.s16[iChannel] = 0;
  42720. }
  42721. }
  42722. /* Filter. */
  42723. ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pResampler->x1.s16, pResampler->x1.s16);
  42724. framesProcessedIn += 1;
  42725. pResampler->inTimeInt -= 1;
  42726. }
  42727. if (pResampler->inTimeInt > 0) {
  42728. break; /* Ran out of input data. */
  42729. }
  42730. /* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */
  42731. if (pFramesOutS16 != NULL) {
  42732. MA_ASSERT(pResampler->inTimeInt == 0);
  42733. ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16);
  42734. pFramesOutS16 += pResampler->config.channels;
  42735. }
  42736. framesProcessedOut += 1;
  42737. /* Advance time forward. */
  42738. pResampler->inTimeInt += pResampler->inAdvanceInt;
  42739. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  42740. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  42741. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  42742. pResampler->inTimeInt += 1;
  42743. }
  42744. }
  42745. *pFrameCountIn = framesProcessedIn;
  42746. *pFrameCountOut = framesProcessedOut;
  42747. return MA_SUCCESS;
  42748. }
  42749. static ma_result ma_linear_resampler_process_pcm_frames_s16_upsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  42750. {
  42751. const ma_int16* pFramesInS16;
  42752. /* */ ma_int16* pFramesOutS16;
  42753. ma_uint64 frameCountIn;
  42754. ma_uint64 frameCountOut;
  42755. ma_uint64 framesProcessedIn;
  42756. ma_uint64 framesProcessedOut;
  42757. MA_ASSERT(pResampler != NULL);
  42758. MA_ASSERT(pFrameCountIn != NULL);
  42759. MA_ASSERT(pFrameCountOut != NULL);
  42760. pFramesInS16 = (const ma_int16*)pFramesIn;
  42761. pFramesOutS16 = ( ma_int16*)pFramesOut;
  42762. frameCountIn = *pFrameCountIn;
  42763. frameCountOut = *pFrameCountOut;
  42764. framesProcessedIn = 0;
  42765. framesProcessedOut = 0;
  42766. while (framesProcessedOut < frameCountOut) {
  42767. /* Before interpolating we need to load the buffers. */
  42768. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  42769. ma_uint32 iChannel;
  42770. if (pFramesInS16 != NULL) {
  42771. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42772. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  42773. pResampler->x1.s16[iChannel] = pFramesInS16[iChannel];
  42774. }
  42775. pFramesInS16 += pResampler->config.channels;
  42776. } else {
  42777. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42778. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  42779. pResampler->x1.s16[iChannel] = 0;
  42780. }
  42781. }
  42782. framesProcessedIn += 1;
  42783. pResampler->inTimeInt -= 1;
  42784. }
  42785. if (pResampler->inTimeInt > 0) {
  42786. break; /* Ran out of input data. */
  42787. }
  42788. /* Getting here means the frames have been loaded and we can generate the next output frame. */
  42789. if (pFramesOutS16 != NULL) {
  42790. MA_ASSERT(pResampler->inTimeInt == 0);
  42791. ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16);
  42792. /* Filter. */
  42793. ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pFramesOutS16, pFramesOutS16);
  42794. pFramesOutS16 += pResampler->config.channels;
  42795. }
  42796. framesProcessedOut += 1;
  42797. /* Advance time forward. */
  42798. pResampler->inTimeInt += pResampler->inAdvanceInt;
  42799. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  42800. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  42801. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  42802. pResampler->inTimeInt += 1;
  42803. }
  42804. }
  42805. *pFrameCountIn = framesProcessedIn;
  42806. *pFrameCountOut = framesProcessedOut;
  42807. return MA_SUCCESS;
  42808. }
  42809. static ma_result ma_linear_resampler_process_pcm_frames_s16(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  42810. {
  42811. MA_ASSERT(pResampler != NULL);
  42812. if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) {
  42813. return ma_linear_resampler_process_pcm_frames_s16_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42814. } else {
  42815. return ma_linear_resampler_process_pcm_frames_s16_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42816. }
  42817. }
  42818. static ma_result ma_linear_resampler_process_pcm_frames_f32_downsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  42819. {
  42820. const float* pFramesInF32;
  42821. /* */ float* pFramesOutF32;
  42822. ma_uint64 frameCountIn;
  42823. ma_uint64 frameCountOut;
  42824. ma_uint64 framesProcessedIn;
  42825. ma_uint64 framesProcessedOut;
  42826. MA_ASSERT(pResampler != NULL);
  42827. MA_ASSERT(pFrameCountIn != NULL);
  42828. MA_ASSERT(pFrameCountOut != NULL);
  42829. pFramesInF32 = (const float*)pFramesIn;
  42830. pFramesOutF32 = ( float*)pFramesOut;
  42831. frameCountIn = *pFrameCountIn;
  42832. frameCountOut = *pFrameCountOut;
  42833. framesProcessedIn = 0;
  42834. framesProcessedOut = 0;
  42835. while (framesProcessedOut < frameCountOut) {
  42836. /* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */
  42837. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  42838. ma_uint32 iChannel;
  42839. if (pFramesInF32 != NULL) {
  42840. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42841. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  42842. pResampler->x1.f32[iChannel] = pFramesInF32[iChannel];
  42843. }
  42844. pFramesInF32 += pResampler->config.channels;
  42845. } else {
  42846. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42847. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  42848. pResampler->x1.f32[iChannel] = 0;
  42849. }
  42850. }
  42851. /* Filter. */
  42852. ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pResampler->x1.f32, pResampler->x1.f32);
  42853. framesProcessedIn += 1;
  42854. pResampler->inTimeInt -= 1;
  42855. }
  42856. if (pResampler->inTimeInt > 0) {
  42857. break; /* Ran out of input data. */
  42858. }
  42859. /* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */
  42860. if (pFramesOutF32 != NULL) {
  42861. MA_ASSERT(pResampler->inTimeInt == 0);
  42862. ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32);
  42863. pFramesOutF32 += pResampler->config.channels;
  42864. }
  42865. framesProcessedOut += 1;
  42866. /* Advance time forward. */
  42867. pResampler->inTimeInt += pResampler->inAdvanceInt;
  42868. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  42869. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  42870. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  42871. pResampler->inTimeInt += 1;
  42872. }
  42873. }
  42874. *pFrameCountIn = framesProcessedIn;
  42875. *pFrameCountOut = framesProcessedOut;
  42876. return MA_SUCCESS;
  42877. }
  42878. static ma_result ma_linear_resampler_process_pcm_frames_f32_upsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  42879. {
  42880. const float* pFramesInF32;
  42881. /* */ float* pFramesOutF32;
  42882. ma_uint64 frameCountIn;
  42883. ma_uint64 frameCountOut;
  42884. ma_uint64 framesProcessedIn;
  42885. ma_uint64 framesProcessedOut;
  42886. MA_ASSERT(pResampler != NULL);
  42887. MA_ASSERT(pFrameCountIn != NULL);
  42888. MA_ASSERT(pFrameCountOut != NULL);
  42889. pFramesInF32 = (const float*)pFramesIn;
  42890. pFramesOutF32 = ( float*)pFramesOut;
  42891. frameCountIn = *pFrameCountIn;
  42892. frameCountOut = *pFrameCountOut;
  42893. framesProcessedIn = 0;
  42894. framesProcessedOut = 0;
  42895. while (framesProcessedOut < frameCountOut) {
  42896. /* Before interpolating we need to load the buffers. */
  42897. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  42898. ma_uint32 iChannel;
  42899. if (pFramesInF32 != NULL) {
  42900. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42901. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  42902. pResampler->x1.f32[iChannel] = pFramesInF32[iChannel];
  42903. }
  42904. pFramesInF32 += pResampler->config.channels;
  42905. } else {
  42906. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42907. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  42908. pResampler->x1.f32[iChannel] = 0;
  42909. }
  42910. }
  42911. framesProcessedIn += 1;
  42912. pResampler->inTimeInt -= 1;
  42913. }
  42914. if (pResampler->inTimeInt > 0) {
  42915. break; /* Ran out of input data. */
  42916. }
  42917. /* Getting here means the frames have been loaded and we can generate the next output frame. */
  42918. if (pFramesOutF32 != NULL) {
  42919. MA_ASSERT(pResampler->inTimeInt == 0);
  42920. ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32);
  42921. /* Filter. */
  42922. ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pFramesOutF32, pFramesOutF32);
  42923. pFramesOutF32 += pResampler->config.channels;
  42924. }
  42925. framesProcessedOut += 1;
  42926. /* Advance time forward. */
  42927. pResampler->inTimeInt += pResampler->inAdvanceInt;
  42928. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  42929. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  42930. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  42931. pResampler->inTimeInt += 1;
  42932. }
  42933. }
  42934. *pFrameCountIn = framesProcessedIn;
  42935. *pFrameCountOut = framesProcessedOut;
  42936. return MA_SUCCESS;
  42937. }
  42938. static ma_result ma_linear_resampler_process_pcm_frames_f32(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  42939. {
  42940. MA_ASSERT(pResampler != NULL);
  42941. if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) {
  42942. return ma_linear_resampler_process_pcm_frames_f32_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42943. } else {
  42944. return ma_linear_resampler_process_pcm_frames_f32_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42945. }
  42946. }
  42947. MA_API ma_result ma_linear_resampler_process_pcm_frames(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  42948. {
  42949. if (pResampler == NULL) {
  42950. return MA_INVALID_ARGS;
  42951. }
  42952. /* */ if (pResampler->config.format == ma_format_s16) {
  42953. return ma_linear_resampler_process_pcm_frames_s16(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42954. } else if (pResampler->config.format == ma_format_f32) {
  42955. return ma_linear_resampler_process_pcm_frames_f32(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42956. } else {
  42957. /* Should never get here. Getting here means the format is not supported and you didn't check the return value of ma_linear_resampler_init(). */
  42958. MA_ASSERT(MA_FALSE);
  42959. return MA_INVALID_ARGS;
  42960. }
  42961. }
  42962. MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  42963. {
  42964. return ma_linear_resampler_set_rate_internal(pResampler, NULL, NULL, sampleRateIn, sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_TRUE);
  42965. }
  42966. MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut)
  42967. {
  42968. ma_uint32 n;
  42969. ma_uint32 d;
  42970. if (pResampler == NULL) {
  42971. return MA_INVALID_ARGS;
  42972. }
  42973. if (ratioInOut <= 0) {
  42974. return MA_INVALID_ARGS;
  42975. }
  42976. d = 1000;
  42977. n = (ma_uint32)(ratioInOut * d);
  42978. if (n == 0) {
  42979. return MA_INVALID_ARGS; /* Ratio too small. */
  42980. }
  42981. MA_ASSERT(n != 0);
  42982. return ma_linear_resampler_set_rate(pResampler, n, d);
  42983. }
  42984. MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler)
  42985. {
  42986. if (pResampler == NULL) {
  42987. return 0;
  42988. }
  42989. return 1 + ma_lpf_get_latency(&pResampler->lpf);
  42990. }
  42991. MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler)
  42992. {
  42993. if (pResampler == NULL) {
  42994. return 0;
  42995. }
  42996. return ma_linear_resampler_get_input_latency(pResampler) * pResampler->config.sampleRateOut / pResampler->config.sampleRateIn;
  42997. }
  42998. MA_API ma_result ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  42999. {
  43000. ma_uint64 inputFrameCount;
  43001. if (pInputFrameCount == NULL) {
  43002. return MA_INVALID_ARGS;
  43003. }
  43004. *pInputFrameCount = 0;
  43005. if (pResampler == NULL) {
  43006. return MA_INVALID_ARGS;
  43007. }
  43008. if (outputFrameCount == 0) {
  43009. return MA_SUCCESS;
  43010. }
  43011. /* Any whole input frames are consumed before the first output frame is generated. */
  43012. inputFrameCount = pResampler->inTimeInt;
  43013. outputFrameCount -= 1;
  43014. /* The rest of the output frames can be calculated in constant time. */
  43015. inputFrameCount += outputFrameCount * pResampler->inAdvanceInt;
  43016. inputFrameCount += (pResampler->inTimeFrac + (outputFrameCount * pResampler->inAdvanceFrac)) / pResampler->config.sampleRateOut;
  43017. *pInputFrameCount = inputFrameCount;
  43018. return MA_SUCCESS;
  43019. }
  43020. MA_API ma_result ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  43021. {
  43022. ma_uint64 outputFrameCount;
  43023. ma_uint64 preliminaryInputFrameCountFromFrac;
  43024. ma_uint64 preliminaryInputFrameCount;
  43025. if (pOutputFrameCount == NULL) {
  43026. return MA_INVALID_ARGS;
  43027. }
  43028. *pOutputFrameCount = 0;
  43029. if (pResampler == NULL) {
  43030. return MA_INVALID_ARGS;
  43031. }
  43032. /*
  43033. The first step is to get a preliminary output frame count. This will either be exactly equal to what we need, or less by 1. We need to
  43034. determine how many input frames will be consumed by this value. If it's greater than our original input frame count it means we won't
  43035. be able to generate an extra frame because we will have run out of input data. Otherwise we will have enough input for the generation
  43036. of an extra output frame. This add-by-one logic is necessary due to how the data loading logic works when processing frames.
  43037. */
  43038. outputFrameCount = (inputFrameCount * pResampler->config.sampleRateOut) / pResampler->config.sampleRateIn;
  43039. /*
  43040. We need to determine how many *whole* input frames will have been processed to generate our preliminary output frame count. This is
  43041. used in the logic below to determine whether or not we need to add an extra output frame.
  43042. */
  43043. preliminaryInputFrameCountFromFrac = (pResampler->inTimeFrac + outputFrameCount*pResampler->inAdvanceFrac) / pResampler->config.sampleRateOut;
  43044. preliminaryInputFrameCount = (pResampler->inTimeInt + outputFrameCount*pResampler->inAdvanceInt ) + preliminaryInputFrameCountFromFrac;
  43045. /*
  43046. If the total number of *whole* input frames that would be required to generate our preliminary output frame count is greather than
  43047. the amount of whole input frames we have available as input we need to *not* add an extra output frame as there won't be enough data
  43048. to actually process. Otherwise we need to add the extra output frame.
  43049. */
  43050. if (preliminaryInputFrameCount <= inputFrameCount) {
  43051. outputFrameCount += 1;
  43052. }
  43053. *pOutputFrameCount = outputFrameCount;
  43054. return MA_SUCCESS;
  43055. }
  43056. MA_API ma_result ma_linear_resampler_reset(ma_linear_resampler* pResampler)
  43057. {
  43058. ma_uint32 iChannel;
  43059. if (pResampler == NULL) {
  43060. return MA_INVALID_ARGS;
  43061. }
  43062. /* Timers need to be cleared back to zero. */
  43063. pResampler->inTimeInt = 1; /* Set this to one to force an input sample to always be loaded for the first output frame. */
  43064. pResampler->inTimeFrac = 0;
  43065. /* Cached samples need to be cleared. */
  43066. if (pResampler->config.format == ma_format_f32) {
  43067. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  43068. pResampler->x0.f32[iChannel] = 0;
  43069. pResampler->x1.f32[iChannel] = 0;
  43070. }
  43071. } else {
  43072. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  43073. pResampler->x0.s16[iChannel] = 0;
  43074. pResampler->x1.s16[iChannel] = 0;
  43075. }
  43076. }
  43077. /* The low pass filter needs to have it's cache reset. */
  43078. ma_lpf_clear_cache(&pResampler->lpf);
  43079. return MA_SUCCESS;
  43080. }
  43081. /* Linear resampler backend vtable. */
  43082. static ma_linear_resampler_config ma_resampling_backend_get_config__linear(const ma_resampler_config* pConfig)
  43083. {
  43084. ma_linear_resampler_config linearConfig;
  43085. linearConfig = ma_linear_resampler_config_init(pConfig->format, pConfig->channels, pConfig->sampleRateIn, pConfig->sampleRateOut);
  43086. linearConfig.lpfOrder = pConfig->linear.lpfOrder;
  43087. return linearConfig;
  43088. }
  43089. static ma_result ma_resampling_backend_get_heap_size__linear(void* pUserData, const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes)
  43090. {
  43091. ma_linear_resampler_config linearConfig;
  43092. (void)pUserData;
  43093. linearConfig = ma_resampling_backend_get_config__linear(pConfig);
  43094. return ma_linear_resampler_get_heap_size(&linearConfig, pHeapSizeInBytes);
  43095. }
  43096. static ma_result ma_resampling_backend_init__linear(void* pUserData, const ma_resampler_config* pConfig, void* pHeap, ma_resampling_backend** ppBackend)
  43097. {
  43098. ma_resampler* pResampler = (ma_resampler*)pUserData;
  43099. ma_result result;
  43100. ma_linear_resampler_config linearConfig;
  43101. (void)pUserData;
  43102. linearConfig = ma_resampling_backend_get_config__linear(pConfig);
  43103. result = ma_linear_resampler_init_preallocated(&linearConfig, pHeap, &pResampler->state.linear);
  43104. if (result != MA_SUCCESS) {
  43105. return result;
  43106. }
  43107. *ppBackend = &pResampler->state.linear;
  43108. return MA_SUCCESS;
  43109. }
  43110. static void ma_resampling_backend_uninit__linear(void* pUserData, ma_resampling_backend* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  43111. {
  43112. (void)pUserData;
  43113. ma_linear_resampler_uninit((ma_linear_resampler*)pBackend, pAllocationCallbacks);
  43114. }
  43115. static ma_result ma_resampling_backend_process__linear(void* pUserData, ma_resampling_backend* pBackend, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  43116. {
  43117. (void)pUserData;
  43118. return ma_linear_resampler_process_pcm_frames((ma_linear_resampler*)pBackend, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  43119. }
  43120. static ma_result ma_resampling_backend_set_rate__linear(void* pUserData, ma_resampling_backend* pBackend, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  43121. {
  43122. (void)pUserData;
  43123. return ma_linear_resampler_set_rate((ma_linear_resampler*)pBackend, sampleRateIn, sampleRateOut);
  43124. }
  43125. static ma_uint64 ma_resampling_backend_get_input_latency__linear(void* pUserData, const ma_resampling_backend* pBackend)
  43126. {
  43127. (void)pUserData;
  43128. return ma_linear_resampler_get_input_latency((const ma_linear_resampler*)pBackend);
  43129. }
  43130. static ma_uint64 ma_resampling_backend_get_output_latency__linear(void* pUserData, const ma_resampling_backend* pBackend)
  43131. {
  43132. (void)pUserData;
  43133. return ma_linear_resampler_get_output_latency((const ma_linear_resampler*)pBackend);
  43134. }
  43135. static ma_result ma_resampling_backend_get_required_input_frame_count__linear(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  43136. {
  43137. (void)pUserData;
  43138. return ma_linear_resampler_get_required_input_frame_count((const ma_linear_resampler*)pBackend, outputFrameCount, pInputFrameCount);
  43139. }
  43140. static ma_result ma_resampling_backend_get_expected_output_frame_count__linear(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  43141. {
  43142. (void)pUserData;
  43143. return ma_linear_resampler_get_expected_output_frame_count((const ma_linear_resampler*)pBackend, inputFrameCount, pOutputFrameCount);
  43144. }
  43145. static ma_result ma_resampling_backend_reset__linear(void* pUserData, ma_resampling_backend* pBackend)
  43146. {
  43147. (void)pUserData;
  43148. return ma_linear_resampler_reset((ma_linear_resampler*)pBackend);
  43149. }
  43150. static ma_resampling_backend_vtable g_ma_linear_resampler_vtable =
  43151. {
  43152. ma_resampling_backend_get_heap_size__linear,
  43153. ma_resampling_backend_init__linear,
  43154. ma_resampling_backend_uninit__linear,
  43155. ma_resampling_backend_process__linear,
  43156. ma_resampling_backend_set_rate__linear,
  43157. ma_resampling_backend_get_input_latency__linear,
  43158. ma_resampling_backend_get_output_latency__linear,
  43159. ma_resampling_backend_get_required_input_frame_count__linear,
  43160. ma_resampling_backend_get_expected_output_frame_count__linear,
  43161. ma_resampling_backend_reset__linear
  43162. };
  43163. MA_API ma_resampler_config ma_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_resample_algorithm algorithm)
  43164. {
  43165. ma_resampler_config config;
  43166. MA_ZERO_OBJECT(&config);
  43167. config.format = format;
  43168. config.channels = channels;
  43169. config.sampleRateIn = sampleRateIn;
  43170. config.sampleRateOut = sampleRateOut;
  43171. config.algorithm = algorithm;
  43172. /* Linear. */
  43173. config.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
  43174. return config;
  43175. }
  43176. static ma_result ma_resampler_get_vtable(const ma_resampler_config* pConfig, ma_resampler* pResampler, ma_resampling_backend_vtable** ppVTable, void** ppUserData)
  43177. {
  43178. MA_ASSERT(pConfig != NULL);
  43179. MA_ASSERT(ppVTable != NULL);
  43180. MA_ASSERT(ppUserData != NULL);
  43181. /* Safety. */
  43182. *ppVTable = NULL;
  43183. *ppUserData = NULL;
  43184. switch (pConfig->algorithm)
  43185. {
  43186. case ma_resample_algorithm_linear:
  43187. {
  43188. *ppVTable = &g_ma_linear_resampler_vtable;
  43189. *ppUserData = pResampler;
  43190. } break;
  43191. case ma_resample_algorithm_custom:
  43192. {
  43193. *ppVTable = pConfig->pBackendVTable;
  43194. *ppUserData = pConfig->pBackendUserData;
  43195. } break;
  43196. default: return MA_INVALID_ARGS;
  43197. }
  43198. return MA_SUCCESS;
  43199. }
  43200. MA_API ma_result ma_resampler_get_heap_size(const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes)
  43201. {
  43202. ma_result result;
  43203. ma_resampling_backend_vtable* pVTable;
  43204. void* pVTableUserData;
  43205. if (pHeapSizeInBytes == NULL) {
  43206. return MA_INVALID_ARGS;
  43207. }
  43208. *pHeapSizeInBytes = 0;
  43209. if (pConfig == NULL) {
  43210. return MA_INVALID_ARGS;
  43211. }
  43212. result = ma_resampler_get_vtable(pConfig, NULL, &pVTable, &pVTableUserData);
  43213. if (result != MA_SUCCESS) {
  43214. return result;
  43215. }
  43216. if (pVTable == NULL || pVTable->onGetHeapSize == NULL) {
  43217. return MA_NOT_IMPLEMENTED;
  43218. }
  43219. result = pVTable->onGetHeapSize(pVTableUserData, pConfig, pHeapSizeInBytes);
  43220. if (result != MA_SUCCESS) {
  43221. return result;
  43222. }
  43223. return MA_SUCCESS;
  43224. }
  43225. MA_API ma_result ma_resampler_init_preallocated(const ma_resampler_config* pConfig, void* pHeap, ma_resampler* pResampler)
  43226. {
  43227. ma_result result;
  43228. if (pResampler == NULL) {
  43229. return MA_INVALID_ARGS;
  43230. }
  43231. MA_ZERO_OBJECT(pResampler);
  43232. if (pConfig == NULL) {
  43233. return MA_INVALID_ARGS;
  43234. }
  43235. pResampler->_pHeap = pHeap;
  43236. pResampler->format = pConfig->format;
  43237. pResampler->channels = pConfig->channels;
  43238. pResampler->sampleRateIn = pConfig->sampleRateIn;
  43239. pResampler->sampleRateOut = pConfig->sampleRateOut;
  43240. result = ma_resampler_get_vtable(pConfig, pResampler, &pResampler->pBackendVTable, &pResampler->pBackendUserData);
  43241. if (result != MA_SUCCESS) {
  43242. return result;
  43243. }
  43244. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onInit == NULL) {
  43245. return MA_NOT_IMPLEMENTED; /* onInit not implemented. */
  43246. }
  43247. result = pResampler->pBackendVTable->onInit(pResampler->pBackendUserData, pConfig, pHeap, &pResampler->pBackend);
  43248. if (result != MA_SUCCESS) {
  43249. return result;
  43250. }
  43251. return MA_SUCCESS;
  43252. }
  43253. MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_resampler* pResampler)
  43254. {
  43255. ma_result result;
  43256. size_t heapSizeInBytes;
  43257. void* pHeap;
  43258. result = ma_resampler_get_heap_size(pConfig, &heapSizeInBytes);
  43259. if (result != MA_SUCCESS) {
  43260. return result;
  43261. }
  43262. if (heapSizeInBytes > 0) {
  43263. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  43264. if (pHeap == NULL) {
  43265. return MA_OUT_OF_MEMORY;
  43266. }
  43267. } else {
  43268. pHeap = NULL;
  43269. }
  43270. result = ma_resampler_init_preallocated(pConfig, pHeap, pResampler);
  43271. if (result != MA_SUCCESS) {
  43272. ma_free(pHeap, pAllocationCallbacks);
  43273. return result;
  43274. }
  43275. pResampler->_ownsHeap = MA_TRUE;
  43276. return MA_SUCCESS;
  43277. }
  43278. MA_API void ma_resampler_uninit(ma_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks)
  43279. {
  43280. if (pResampler == NULL) {
  43281. return;
  43282. }
  43283. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onUninit == NULL) {
  43284. return;
  43285. }
  43286. pResampler->pBackendVTable->onUninit(pResampler->pBackendUserData, pResampler->pBackend, pAllocationCallbacks);
  43287. if (pResampler->_ownsHeap) {
  43288. ma_free(pResampler->_pHeap, pAllocationCallbacks);
  43289. }
  43290. }
  43291. MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  43292. {
  43293. if (pResampler == NULL) {
  43294. return MA_INVALID_ARGS;
  43295. }
  43296. if (pFrameCountOut == NULL && pFrameCountIn == NULL) {
  43297. return MA_INVALID_ARGS;
  43298. }
  43299. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onProcess == NULL) {
  43300. return MA_NOT_IMPLEMENTED;
  43301. }
  43302. return pResampler->pBackendVTable->onProcess(pResampler->pBackendUserData, pResampler->pBackend, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  43303. }
  43304. MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  43305. {
  43306. ma_result result;
  43307. if (pResampler == NULL) {
  43308. return MA_INVALID_ARGS;
  43309. }
  43310. if (sampleRateIn == 0 || sampleRateOut == 0) {
  43311. return MA_INVALID_ARGS;
  43312. }
  43313. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onSetRate == NULL) {
  43314. return MA_NOT_IMPLEMENTED;
  43315. }
  43316. result = pResampler->pBackendVTable->onSetRate(pResampler->pBackendUserData, pResampler->pBackend, sampleRateIn, sampleRateOut);
  43317. if (result != MA_SUCCESS) {
  43318. return result;
  43319. }
  43320. pResampler->sampleRateIn = sampleRateIn;
  43321. pResampler->sampleRateOut = sampleRateOut;
  43322. return MA_SUCCESS;
  43323. }
  43324. MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio)
  43325. {
  43326. ma_uint32 n;
  43327. ma_uint32 d;
  43328. if (pResampler == NULL) {
  43329. return MA_INVALID_ARGS;
  43330. }
  43331. if (ratio <= 0) {
  43332. return MA_INVALID_ARGS;
  43333. }
  43334. d = 1000;
  43335. n = (ma_uint32)(ratio * d);
  43336. if (n == 0) {
  43337. return MA_INVALID_ARGS; /* Ratio too small. */
  43338. }
  43339. MA_ASSERT(n != 0);
  43340. return ma_resampler_set_rate(pResampler, n, d);
  43341. }
  43342. MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler)
  43343. {
  43344. if (pResampler == NULL) {
  43345. return 0;
  43346. }
  43347. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetInputLatency == NULL) {
  43348. return 0;
  43349. }
  43350. return pResampler->pBackendVTable->onGetInputLatency(pResampler->pBackendUserData, pResampler->pBackend);
  43351. }
  43352. MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler)
  43353. {
  43354. if (pResampler == NULL) {
  43355. return 0;
  43356. }
  43357. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetOutputLatency == NULL) {
  43358. return 0;
  43359. }
  43360. return pResampler->pBackendVTable->onGetOutputLatency(pResampler->pBackendUserData, pResampler->pBackend);
  43361. }
  43362. MA_API ma_result ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  43363. {
  43364. if (pInputFrameCount == NULL) {
  43365. return MA_INVALID_ARGS;
  43366. }
  43367. *pInputFrameCount = 0;
  43368. if (pResampler == NULL) {
  43369. return MA_INVALID_ARGS;
  43370. }
  43371. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetRequiredInputFrameCount == NULL) {
  43372. return MA_NOT_IMPLEMENTED;
  43373. }
  43374. return pResampler->pBackendVTable->onGetRequiredInputFrameCount(pResampler->pBackendUserData, pResampler->pBackend, outputFrameCount, pInputFrameCount);
  43375. }
  43376. MA_API ma_result ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  43377. {
  43378. if (pOutputFrameCount == NULL) {
  43379. return MA_INVALID_ARGS;
  43380. }
  43381. *pOutputFrameCount = 0;
  43382. if (pResampler == NULL) {
  43383. return MA_INVALID_ARGS;
  43384. }
  43385. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetExpectedOutputFrameCount == NULL) {
  43386. return MA_NOT_IMPLEMENTED;
  43387. }
  43388. return pResampler->pBackendVTable->onGetExpectedOutputFrameCount(pResampler->pBackendUserData, pResampler->pBackend, inputFrameCount, pOutputFrameCount);
  43389. }
  43390. MA_API ma_result ma_resampler_reset(ma_resampler* pResampler)
  43391. {
  43392. if (pResampler == NULL) {
  43393. return MA_INVALID_ARGS;
  43394. }
  43395. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onReset == NULL) {
  43396. return MA_NOT_IMPLEMENTED;
  43397. }
  43398. return pResampler->pBackendVTable->onReset(pResampler->pBackendUserData, pResampler->pBackend);
  43399. }
  43400. /**************************************************************************************************************************************************************
  43401. Channel Conversion
  43402. **************************************************************************************************************************************************************/
  43403. #ifndef MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT
  43404. #define MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT 12
  43405. #endif
  43406. #define MA_PLANE_LEFT 0
  43407. #define MA_PLANE_RIGHT 1
  43408. #define MA_PLANE_FRONT 2
  43409. #define MA_PLANE_BACK 3
  43410. #define MA_PLANE_BOTTOM 4
  43411. #define MA_PLANE_TOP 5
  43412. static float g_maChannelPlaneRatios[MA_CHANNEL_POSITION_COUNT][6] = {
  43413. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_NONE */
  43414. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_MONO */
  43415. { 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_LEFT */
  43416. { 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_RIGHT */
  43417. { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_CENTER */
  43418. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_LFE */
  43419. { 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_LEFT */
  43420. { 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_RIGHT */
  43421. { 0.25f, 0.0f, 0.75f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_LEFT_CENTER */
  43422. { 0.0f, 0.25f, 0.75f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_RIGHT_CENTER */
  43423. { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_CENTER */
  43424. { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_SIDE_LEFT */
  43425. { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_SIDE_RIGHT */
  43426. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, /* MA_CHANNEL_TOP_CENTER */
  43427. { 0.33f, 0.0f, 0.33f, 0.0f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_FRONT_LEFT */
  43428. { 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f}, /* MA_CHANNEL_TOP_FRONT_CENTER */
  43429. { 0.0f, 0.33f, 0.33f, 0.0f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_FRONT_RIGHT */
  43430. { 0.33f, 0.0f, 0.0f, 0.33f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_BACK_LEFT */
  43431. { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f}, /* MA_CHANNEL_TOP_BACK_CENTER */
  43432. { 0.0f, 0.33f, 0.0f, 0.33f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_BACK_RIGHT */
  43433. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_0 */
  43434. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_1 */
  43435. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_2 */
  43436. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_3 */
  43437. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_4 */
  43438. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_5 */
  43439. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_6 */
  43440. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_7 */
  43441. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_8 */
  43442. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_9 */
  43443. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_10 */
  43444. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_11 */
  43445. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_12 */
  43446. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_13 */
  43447. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_14 */
  43448. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_15 */
  43449. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_16 */
  43450. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_17 */
  43451. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_18 */
  43452. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_19 */
  43453. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_20 */
  43454. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_21 */
  43455. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_22 */
  43456. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_23 */
  43457. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_24 */
  43458. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_25 */
  43459. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_26 */
  43460. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_27 */
  43461. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_28 */
  43462. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_29 */
  43463. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_30 */
  43464. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_31 */
  43465. };
  43466. static float ma_calculate_channel_position_rectangular_weight(ma_channel channelPositionA, ma_channel channelPositionB)
  43467. {
  43468. /*
  43469. Imagine the following simplified example: You have a single input speaker which is the front/left speaker which you want to convert to
  43470. the following output configuration:
  43471. - front/left
  43472. - side/left
  43473. - back/left
  43474. The front/left output is easy - it the same speaker position so it receives the full contribution of the front/left input. The amount
  43475. of contribution to apply to the side/left and back/left speakers, however, is a bit more complicated.
  43476. Imagine the front/left speaker as emitting audio from two planes - the front plane and the left plane. You can think of the front/left
  43477. speaker emitting half of it's total volume from the front, and the other half from the left. Since part of it's volume is being emitted
  43478. from the left side, and the side/left and back/left channels also emit audio from the left plane, one would expect that they would
  43479. receive some amount of contribution from front/left speaker. The amount of contribution depends on how many planes are shared between
  43480. the two speakers. Note that in the examples below I've added a top/front/left speaker as an example just to show how the math works
  43481. across 3 spatial dimensions.
  43482. The first thing to do is figure out how each speaker's volume is spread over each of plane:
  43483. - front/left: 2 planes (front and left) = 1/2 = half it's total volume on each plane
  43484. - side/left: 1 plane (left only) = 1/1 = entire volume from left plane
  43485. - back/left: 2 planes (back and left) = 1/2 = half it's total volume on each plane
  43486. - top/front/left: 3 planes (top, front and left) = 1/3 = one third it's total volume on each plane
  43487. The amount of volume each channel contributes to each of it's planes is what controls how much it is willing to given and take to other
  43488. channels on the same plane. The volume that is willing to the given by one channel is multiplied by the volume that is willing to be
  43489. taken by the other to produce the final contribution.
  43490. */
  43491. /* Contribution = Sum(Volume to Give * Volume to Take) */
  43492. float contribution =
  43493. g_maChannelPlaneRatios[channelPositionA][0] * g_maChannelPlaneRatios[channelPositionB][0] +
  43494. g_maChannelPlaneRatios[channelPositionA][1] * g_maChannelPlaneRatios[channelPositionB][1] +
  43495. g_maChannelPlaneRatios[channelPositionA][2] * g_maChannelPlaneRatios[channelPositionB][2] +
  43496. g_maChannelPlaneRatios[channelPositionA][3] * g_maChannelPlaneRatios[channelPositionB][3] +
  43497. g_maChannelPlaneRatios[channelPositionA][4] * g_maChannelPlaneRatios[channelPositionB][4] +
  43498. g_maChannelPlaneRatios[channelPositionA][5] * g_maChannelPlaneRatios[channelPositionB][5];
  43499. return contribution;
  43500. }
  43501. MA_API ma_channel_converter_config ma_channel_converter_config_init(ma_format format, ma_uint32 channelsIn, const ma_channel* pChannelMapIn, ma_uint32 channelsOut, const ma_channel* pChannelMapOut, ma_channel_mix_mode mixingMode)
  43502. {
  43503. ma_channel_converter_config config;
  43504. MA_ZERO_OBJECT(&config);
  43505. config.format = format;
  43506. config.channelsIn = channelsIn;
  43507. config.channelsOut = channelsOut;
  43508. config.pChannelMapIn = pChannelMapIn;
  43509. config.pChannelMapOut = pChannelMapOut;
  43510. config.mixingMode = mixingMode;
  43511. return config;
  43512. }
  43513. static ma_int32 ma_channel_converter_float_to_fixed(float x)
  43514. {
  43515. return (ma_int32)(x * (1<<MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT));
  43516. }
  43517. static ma_uint32 ma_channel_map_get_spatial_channel_count(const ma_channel* pChannelMap, ma_uint32 channels)
  43518. {
  43519. ma_uint32 spatialChannelCount = 0;
  43520. ma_uint32 iChannel;
  43521. MA_ASSERT(pChannelMap != NULL);
  43522. MA_ASSERT(channels > 0);
  43523. for (iChannel = 0; iChannel < channels; ++iChannel) {
  43524. if (ma_is_spatial_channel_position(ma_channel_map_get_channel(pChannelMap, channels, iChannel))) {
  43525. spatialChannelCount++;
  43526. }
  43527. }
  43528. return spatialChannelCount;
  43529. }
  43530. static ma_bool32 ma_is_spatial_channel_position(ma_channel channelPosition)
  43531. {
  43532. int i;
  43533. if (channelPosition == MA_CHANNEL_NONE || channelPosition == MA_CHANNEL_MONO || channelPosition == MA_CHANNEL_LFE) {
  43534. return MA_FALSE;
  43535. }
  43536. if (channelPosition >= MA_CHANNEL_AUX_0 && channelPosition <= MA_CHANNEL_AUX_31) {
  43537. return MA_FALSE;
  43538. }
  43539. for (i = 0; i < 6; ++i) { /* Each side of a cube. */
  43540. if (g_maChannelPlaneRatios[channelPosition][i] != 0) {
  43541. return MA_TRUE;
  43542. }
  43543. }
  43544. return MA_FALSE;
  43545. }
  43546. static ma_bool32 ma_channel_map_is_passthrough(const ma_channel* pChannelMapIn, ma_uint32 channelsIn, const ma_channel* pChannelMapOut, ma_uint32 channelsOut)
  43547. {
  43548. if (channelsOut == channelsIn) {
  43549. return ma_channel_map_is_equal(pChannelMapOut, pChannelMapIn, channelsOut);
  43550. } else {
  43551. return MA_FALSE; /* Channel counts differ, so cannot be a passthrough. */
  43552. }
  43553. }
  43554. static ma_channel_conversion_path ma_channel_map_get_conversion_path(const ma_channel* pChannelMapIn, ma_uint32 channelsIn, const ma_channel* pChannelMapOut, ma_uint32 channelsOut, ma_channel_mix_mode mode)
  43555. {
  43556. if (ma_channel_map_is_passthrough(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut)) {
  43557. return ma_channel_conversion_path_passthrough;
  43558. }
  43559. if (channelsOut == 1 && (pChannelMapOut == NULL || pChannelMapOut[0] == MA_CHANNEL_MONO)) {
  43560. return ma_channel_conversion_path_mono_out;
  43561. }
  43562. if (channelsIn == 1 && (pChannelMapIn == NULL || pChannelMapIn[0] == MA_CHANNEL_MONO)) {
  43563. return ma_channel_conversion_path_mono_in;
  43564. }
  43565. if (mode == ma_channel_mix_mode_custom_weights) {
  43566. return ma_channel_conversion_path_weights;
  43567. }
  43568. /*
  43569. We can use a simple shuffle if both channel maps have the same channel count and all channel
  43570. positions are present in both.
  43571. */
  43572. if (channelsIn == channelsOut) {
  43573. ma_uint32 iChannelIn;
  43574. ma_bool32 areAllChannelPositionsPresent = MA_TRUE;
  43575. for (iChannelIn = 0; iChannelIn < channelsIn; ++iChannelIn) {
  43576. ma_bool32 isInputChannelPositionInOutput = MA_FALSE;
  43577. if (ma_channel_map_contains_channel_position(channelsOut, pChannelMapOut, ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn))) {
  43578. isInputChannelPositionInOutput = MA_TRUE;
  43579. break;
  43580. }
  43581. if (!isInputChannelPositionInOutput) {
  43582. areAllChannelPositionsPresent = MA_FALSE;
  43583. break;
  43584. }
  43585. }
  43586. if (areAllChannelPositionsPresent) {
  43587. return ma_channel_conversion_path_shuffle;
  43588. }
  43589. }
  43590. /* Getting here means we'll need to use weights. */
  43591. return ma_channel_conversion_path_weights;
  43592. }
  43593. static ma_result ma_channel_map_build_shuffle_table(const ma_channel* pChannelMapIn, ma_uint32 channelCountIn, const ma_channel* pChannelMapOut, ma_uint32 channelCountOut, ma_uint8* pShuffleTable)
  43594. {
  43595. ma_uint32 iChannelIn;
  43596. ma_uint32 iChannelOut;
  43597. if (pShuffleTable == NULL || channelCountIn == 0 || channelCountOut == 0) {
  43598. return MA_INVALID_ARGS;
  43599. }
  43600. /*
  43601. When building the shuffle table we just do a 1:1 mapping based on the first occurance of a channel. If the
  43602. input channel has more than one occurance of a channel position, the second one will be ignored.
  43603. */
  43604. for (iChannelOut = 0; iChannelOut < channelCountOut; iChannelOut += 1) {
  43605. ma_channel channelOut;
  43606. /* Default to MA_CHANNEL_INDEX_NULL so that if a mapping is not found it'll be set appropriately. */
  43607. pShuffleTable[iChannelOut] = MA_CHANNEL_INDEX_NULL;
  43608. channelOut = ma_channel_map_get_channel(pChannelMapOut, channelCountOut, iChannelOut);
  43609. for (iChannelIn = 0; iChannelIn < channelCountIn; iChannelIn += 1) {
  43610. ma_channel channelIn;
  43611. channelIn = ma_channel_map_get_channel(pChannelMapIn, channelCountIn, iChannelIn);
  43612. if (channelOut == channelIn) {
  43613. pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn;
  43614. break;
  43615. }
  43616. /*
  43617. Getting here means the channels don't exactly match, but we are going to support some
  43618. relaxed matching for practicality. If, for example, there are two stereo channel maps,
  43619. but one uses front left/right and the other uses side left/right, it makes logical
  43620. sense to just map these. The way we'll do it is we'll check if there is a logical
  43621. corresponding mapping, and if so, apply it, but we will *not* break from the loop,
  43622. thereby giving the loop a chance to find an exact match later which will take priority.
  43623. */
  43624. switch (channelOut)
  43625. {
  43626. /* Left channels. */
  43627. case MA_CHANNEL_FRONT_LEFT:
  43628. case MA_CHANNEL_SIDE_LEFT:
  43629. {
  43630. switch (channelIn) {
  43631. case MA_CHANNEL_FRONT_LEFT:
  43632. case MA_CHANNEL_SIDE_LEFT:
  43633. {
  43634. pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn;
  43635. } break;
  43636. }
  43637. } break;
  43638. /* Right channels. */
  43639. case MA_CHANNEL_FRONT_RIGHT:
  43640. case MA_CHANNEL_SIDE_RIGHT:
  43641. {
  43642. switch (channelIn) {
  43643. case MA_CHANNEL_FRONT_RIGHT:
  43644. case MA_CHANNEL_SIDE_RIGHT:
  43645. {
  43646. pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn;
  43647. } break;
  43648. }
  43649. } break;
  43650. default: break;
  43651. }
  43652. }
  43653. }
  43654. return MA_SUCCESS;
  43655. }
  43656. static void ma_channel_map_apply_shuffle_table_u8(ma_uint8* pFramesOut, ma_uint32 channelsOut, const ma_uint8* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable)
  43657. {
  43658. ma_uint64 iFrame;
  43659. ma_uint32 iChannelOut;
  43660. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43661. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43662. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  43663. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  43664. pFramesOut[iChannelOut] = pFramesIn[iChannelIn];
  43665. } else {
  43666. pFramesOut[iChannelOut] = 0;
  43667. }
  43668. }
  43669. pFramesOut += channelsOut;
  43670. pFramesIn += channelsIn;
  43671. }
  43672. }
  43673. static void ma_channel_map_apply_shuffle_table_s16(ma_int16* pFramesOut, ma_uint32 channelsOut, const ma_int16* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable)
  43674. {
  43675. ma_uint64 iFrame;
  43676. ma_uint32 iChannelOut;
  43677. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43678. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43679. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  43680. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  43681. pFramesOut[iChannelOut] = pFramesIn[iChannelIn];
  43682. } else {
  43683. pFramesOut[iChannelOut] = 0;
  43684. }
  43685. }
  43686. pFramesOut += channelsOut;
  43687. pFramesIn += channelsIn;
  43688. }
  43689. }
  43690. static void ma_channel_map_apply_shuffle_table_s24(ma_uint8* pFramesOut, ma_uint32 channelsOut, const ma_uint8* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable)
  43691. {
  43692. ma_uint64 iFrame;
  43693. ma_uint32 iChannelOut;
  43694. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43695. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43696. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  43697. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  43698. pFramesOut[iChannelOut*3 + 0] = pFramesIn[iChannelIn*3 + 0];
  43699. pFramesOut[iChannelOut*3 + 1] = pFramesIn[iChannelIn*3 + 1];
  43700. pFramesOut[iChannelOut*3 + 2] = pFramesIn[iChannelIn*3 + 2];
  43701. } else {
  43702. pFramesOut[iChannelOut*3 + 0] = 0;
  43703. } pFramesOut[iChannelOut*3 + 1] = 0;
  43704. } pFramesOut[iChannelOut*3 + 2] = 0;
  43705. pFramesOut += channelsOut*3;
  43706. pFramesIn += channelsIn*3;
  43707. }
  43708. }
  43709. static void ma_channel_map_apply_shuffle_table_s32(ma_int32* pFramesOut, ma_uint32 channelsOut, const ma_int32* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable)
  43710. {
  43711. ma_uint64 iFrame;
  43712. ma_uint32 iChannelOut;
  43713. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43714. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43715. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  43716. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  43717. pFramesOut[iChannelOut] = pFramesIn[iChannelIn];
  43718. } else {
  43719. pFramesOut[iChannelOut] = 0;
  43720. }
  43721. }
  43722. pFramesOut += channelsOut;
  43723. pFramesIn += channelsIn;
  43724. }
  43725. }
  43726. static void ma_channel_map_apply_shuffle_table_f32(float* pFramesOut, ma_uint32 channelsOut, const float* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable)
  43727. {
  43728. ma_uint64 iFrame;
  43729. ma_uint32 iChannelOut;
  43730. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43731. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43732. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  43733. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  43734. pFramesOut[iChannelOut] = pFramesIn[iChannelIn];
  43735. } else {
  43736. pFramesOut[iChannelOut] = 0;
  43737. }
  43738. }
  43739. pFramesOut += channelsOut;
  43740. pFramesIn += channelsIn;
  43741. }
  43742. }
  43743. static ma_result ma_channel_map_apply_shuffle_table(void* pFramesOut, ma_uint32 channelsOut, const void* pFramesIn, ma_uint32 channelsIn, ma_uint64 frameCount, const ma_uint8* pShuffleTable, ma_format format)
  43744. {
  43745. if (pFramesOut == NULL || pFramesIn == NULL || channelsOut == 0 || pShuffleTable == NULL) {
  43746. return MA_INVALID_ARGS;
  43747. }
  43748. switch (format)
  43749. {
  43750. case ma_format_u8:
  43751. {
  43752. ma_channel_map_apply_shuffle_table_u8((ma_uint8*)pFramesOut, channelsOut, (const ma_uint8*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43753. } break;
  43754. case ma_format_s16:
  43755. {
  43756. ma_channel_map_apply_shuffle_table_s16((ma_int16*)pFramesOut, channelsOut, (const ma_int16*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43757. } break;
  43758. case ma_format_s24:
  43759. {
  43760. ma_channel_map_apply_shuffle_table_s24((ma_uint8*)pFramesOut, channelsOut, (const ma_uint8*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43761. } break;
  43762. case ma_format_s32:
  43763. {
  43764. ma_channel_map_apply_shuffle_table_s32((ma_int32*)pFramesOut, channelsOut, (const ma_int32*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43765. } break;
  43766. case ma_format_f32:
  43767. {
  43768. ma_channel_map_apply_shuffle_table_f32((float*)pFramesOut, channelsOut, (const float*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43769. } break;
  43770. default: return MA_INVALID_ARGS; /* Unknown format. */
  43771. }
  43772. return MA_SUCCESS;
  43773. }
  43774. static ma_result ma_channel_map_apply_mono_out_f32(float* pFramesOut, const float* pFramesIn, const ma_channel* pChannelMapIn, ma_uint32 channelsIn, ma_uint64 frameCount)
  43775. {
  43776. ma_uint64 iFrame;
  43777. ma_uint32 iChannelIn;
  43778. ma_uint32 accumulationCount;
  43779. if (pFramesOut == NULL || pFramesIn == NULL || channelsIn == 0) {
  43780. return MA_INVALID_ARGS;
  43781. }
  43782. /* In this case the output stream needs to be the average of all channels, ignoring NONE. */
  43783. /* A quick pre-processing step to get the accumulation counter since we're ignoring NONE channels. */
  43784. accumulationCount = 0;
  43785. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  43786. if (ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn) != MA_CHANNEL_NONE) {
  43787. accumulationCount += 1;
  43788. }
  43789. }
  43790. if (accumulationCount > 0) { /* <-- Prevent a division by zero. */
  43791. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43792. float accumulation = 0;
  43793. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  43794. ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn);
  43795. if (channelIn != MA_CHANNEL_NONE) {
  43796. accumulation += pFramesIn[iChannelIn];
  43797. }
  43798. }
  43799. pFramesOut[0] = accumulation / accumulationCount;
  43800. pFramesOut += 1;
  43801. pFramesIn += channelsIn;
  43802. }
  43803. } else {
  43804. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, 1);
  43805. }
  43806. return MA_SUCCESS;
  43807. }
  43808. static ma_result ma_channel_map_apply_mono_in_f32(float* MA_RESTRICT pFramesOut, const ma_channel* pChannelMapOut, ma_uint32 channelsOut, const float* MA_RESTRICT pFramesIn, ma_uint64 frameCount, ma_mono_expansion_mode monoExpansionMode)
  43809. {
  43810. ma_uint64 iFrame;
  43811. ma_uint32 iChannelOut;
  43812. if (pFramesOut == NULL || channelsOut == 0 || pFramesIn == NULL) {
  43813. return MA_INVALID_ARGS;
  43814. }
  43815. /* Note that the MA_CHANNEL_NONE channel must be ignored in all cases. */
  43816. switch (monoExpansionMode)
  43817. {
  43818. case ma_mono_expansion_mode_average:
  43819. {
  43820. float weight;
  43821. ma_uint32 validChannelCount = 0;
  43822. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43823. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43824. if (channelOut != MA_CHANNEL_NONE) {
  43825. validChannelCount += 1;
  43826. }
  43827. }
  43828. weight = 1.0f / validChannelCount;
  43829. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43830. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43831. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43832. if (channelOut != MA_CHANNEL_NONE) {
  43833. pFramesOut[iChannelOut] = pFramesIn[0] * weight;
  43834. }
  43835. }
  43836. pFramesOut += channelsOut;
  43837. pFramesIn += 1;
  43838. }
  43839. } break;
  43840. case ma_mono_expansion_mode_stereo_only:
  43841. {
  43842. if (channelsOut >= 2) {
  43843. ma_uint32 iChannelLeft = (ma_uint32)-1;
  43844. ma_uint32 iChannelRight = (ma_uint32)-1;
  43845. /*
  43846. We first need to find our stereo channels. We prefer front-left and front-right, but
  43847. if they're not available, we'll also try side-left and side-right. If neither are
  43848. available we'll fall through to the default case below.
  43849. */
  43850. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43851. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43852. if (channelOut == MA_CHANNEL_SIDE_LEFT) {
  43853. iChannelLeft = iChannelOut;
  43854. }
  43855. if (channelOut == MA_CHANNEL_SIDE_RIGHT) {
  43856. iChannelRight = iChannelOut;
  43857. }
  43858. }
  43859. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43860. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43861. if (channelOut == MA_CHANNEL_FRONT_LEFT) {
  43862. iChannelLeft = iChannelOut;
  43863. }
  43864. if (channelOut == MA_CHANNEL_FRONT_RIGHT) {
  43865. iChannelRight = iChannelOut;
  43866. }
  43867. }
  43868. if (iChannelLeft != (ma_uint32)-1 && iChannelRight != (ma_uint32)-1) {
  43869. /* We found our stereo channels so we can duplicate the signal across those channels. */
  43870. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43871. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43872. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43873. if (channelOut != MA_CHANNEL_NONE) {
  43874. if (iChannelOut == iChannelLeft || iChannelOut == iChannelRight) {
  43875. pFramesOut[iChannelOut] = pFramesIn[0];
  43876. } else {
  43877. pFramesOut[iChannelOut] = 0.0f;
  43878. }
  43879. }
  43880. }
  43881. pFramesOut += channelsOut;
  43882. pFramesIn += 1;
  43883. }
  43884. break; /* Get out of the switch. */
  43885. } else {
  43886. /* Fallthrough. Does not have left and right channels. */
  43887. goto default_handler;
  43888. }
  43889. } else {
  43890. /* Fallthrough. Does not have stereo channels. */
  43891. goto default_handler;
  43892. }
  43893. }; /* Fallthrough. See comments above. */
  43894. case ma_mono_expansion_mode_duplicate:
  43895. default:
  43896. {
  43897. default_handler:
  43898. {
  43899. if (channelsOut <= MA_MAX_CHANNELS) {
  43900. ma_bool32 hasEmptyChannel = MA_FALSE;
  43901. ma_channel channelPositions[MA_MAX_CHANNELS];
  43902. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43903. channelPositions[iChannelOut] = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43904. if (channelPositions[iChannelOut] == MA_CHANNEL_NONE) {
  43905. hasEmptyChannel = MA_TRUE;
  43906. }
  43907. }
  43908. if (hasEmptyChannel == MA_FALSE) {
  43909. /*
  43910. Faster path when there's no MA_CHANNEL_NONE channel positions. This should hopefully
  43911. help the compiler with auto-vectorization.m
  43912. */
  43913. if (channelsOut == 2) {
  43914. #if defined(MA_SUPPORT_SSE2)
  43915. if (ma_has_sse2()) {
  43916. /* We want to do two frames in each iteration. */
  43917. ma_uint64 unrolledFrameCount = frameCount >> 1;
  43918. for (iFrame = 0; iFrame < unrolledFrameCount; iFrame += 1) {
  43919. __m128 in0 = _mm_set1_ps(pFramesIn[iFrame*2 + 0]);
  43920. __m128 in1 = _mm_set1_ps(pFramesIn[iFrame*2 + 1]);
  43921. _mm_storeu_ps(&pFramesOut[iFrame*4 + 0], _mm_shuffle_ps(in1, in0, _MM_SHUFFLE(0, 0, 0, 0)));
  43922. }
  43923. /* Tail. */
  43924. iFrame = unrolledFrameCount << 1;
  43925. goto generic_on_fastpath;
  43926. } else
  43927. #endif
  43928. {
  43929. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43930. for (iChannelOut = 0; iChannelOut < 2; iChannelOut += 1) {
  43931. pFramesOut[iFrame*2 + iChannelOut] = pFramesIn[iFrame];
  43932. }
  43933. }
  43934. }
  43935. } else if (channelsOut == 6) {
  43936. #if defined(MA_SUPPORT_SSE2)
  43937. if (ma_has_sse2()) {
  43938. /* We want to do two frames in each iteration so we can have a multiple of 4 samples. */
  43939. ma_uint64 unrolledFrameCount = frameCount >> 1;
  43940. for (iFrame = 0; iFrame < unrolledFrameCount; iFrame += 1) {
  43941. __m128 in0 = _mm_set1_ps(pFramesIn[iFrame*2 + 0]);
  43942. __m128 in1 = _mm_set1_ps(pFramesIn[iFrame*2 + 1]);
  43943. _mm_storeu_ps(&pFramesOut[iFrame*12 + 0], in0);
  43944. _mm_storeu_ps(&pFramesOut[iFrame*12 + 4], _mm_shuffle_ps(in1, in0, _MM_SHUFFLE(0, 0, 0, 0)));
  43945. _mm_storeu_ps(&pFramesOut[iFrame*12 + 8], in1);
  43946. }
  43947. /* Tail. */
  43948. iFrame = unrolledFrameCount << 1;
  43949. goto generic_on_fastpath;
  43950. } else
  43951. #endif
  43952. {
  43953. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43954. for (iChannelOut = 0; iChannelOut < 6; iChannelOut += 1) {
  43955. pFramesOut[iFrame*6 + iChannelOut] = pFramesIn[iFrame];
  43956. }
  43957. }
  43958. }
  43959. } else if (channelsOut == 8) {
  43960. #if defined(MA_SUPPORT_SSE2)
  43961. if (ma_has_sse2()) {
  43962. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43963. __m128 in = _mm_set1_ps(pFramesIn[iFrame]);
  43964. _mm_storeu_ps(&pFramesOut[iFrame*8 + 0], in);
  43965. _mm_storeu_ps(&pFramesOut[iFrame*8 + 4], in);
  43966. }
  43967. } else
  43968. #endif
  43969. {
  43970. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43971. for (iChannelOut = 0; iChannelOut < 8; iChannelOut += 1) {
  43972. pFramesOut[iFrame*8 + iChannelOut] = pFramesIn[iFrame];
  43973. }
  43974. }
  43975. }
  43976. } else {
  43977. iFrame = 0;
  43978. #if defined(MA_SUPPORT_SSE2) /* For silencing a warning with non-x86 builds. */
  43979. generic_on_fastpath:
  43980. #endif
  43981. {
  43982. for (; iFrame < frameCount; iFrame += 1) {
  43983. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43984. pFramesOut[iFrame*channelsOut + iChannelOut] = pFramesIn[iFrame];
  43985. }
  43986. }
  43987. }
  43988. }
  43989. } else {
  43990. /* Slow path. Need to handle MA_CHANNEL_NONE. */
  43991. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43992. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43993. if (channelPositions[iChannelOut] != MA_CHANNEL_NONE) {
  43994. pFramesOut[iFrame*channelsOut + iChannelOut] = pFramesIn[iFrame];
  43995. }
  43996. }
  43997. }
  43998. }
  43999. } else {
  44000. /* Slow path. Too many channels to store on the stack. */
  44001. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44002. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44003. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  44004. if (channelOut != MA_CHANNEL_NONE) {
  44005. pFramesOut[iFrame*channelsOut + iChannelOut] = pFramesIn[iFrame];
  44006. }
  44007. }
  44008. }
  44009. }
  44010. }
  44011. } break;
  44012. }
  44013. return MA_SUCCESS;
  44014. }
  44015. static void ma_channel_map_apply_f32(float* pFramesOut, const ma_channel* pChannelMapOut, ma_uint32 channelsOut, const float* pFramesIn, const ma_channel* pChannelMapIn, ma_uint32 channelsIn, ma_uint64 frameCount, ma_channel_mix_mode mode, ma_mono_expansion_mode monoExpansionMode)
  44016. {
  44017. ma_channel_conversion_path conversionPath = ma_channel_map_get_conversion_path(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut, mode);
  44018. /* Optimized Path: Passthrough */
  44019. if (conversionPath == ma_channel_conversion_path_passthrough) {
  44020. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, ma_format_f32, channelsOut);
  44021. return;
  44022. }
  44023. /* Special Path: Mono Output. */
  44024. if (conversionPath == ma_channel_conversion_path_mono_out) {
  44025. ma_channel_map_apply_mono_out_f32(pFramesOut, pFramesIn, pChannelMapIn, channelsIn, frameCount);
  44026. return;
  44027. }
  44028. /* Special Path: Mono Input. */
  44029. if (conversionPath == ma_channel_conversion_path_mono_in) {
  44030. ma_channel_map_apply_mono_in_f32(pFramesOut, pChannelMapOut, channelsOut, pFramesIn, frameCount, monoExpansionMode);
  44031. return;
  44032. }
  44033. /* Getting here means we aren't running on an optimized conversion path. */
  44034. if (channelsOut <= MA_MAX_CHANNELS) {
  44035. ma_result result;
  44036. if (mode == ma_channel_mix_mode_simple) {
  44037. ma_channel shuffleTable[MA_MAX_CHANNELS];
  44038. result = ma_channel_map_build_shuffle_table(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut, shuffleTable);
  44039. if (result != MA_SUCCESS) {
  44040. return;
  44041. }
  44042. result = ma_channel_map_apply_shuffle_table(pFramesOut, channelsOut, pFramesIn, channelsIn, frameCount, shuffleTable, ma_format_f32);
  44043. if (result != MA_SUCCESS) {
  44044. return;
  44045. }
  44046. } else {
  44047. ma_uint32 iFrame;
  44048. ma_uint32 iChannelOut;
  44049. ma_uint32 iChannelIn;
  44050. float weights[32][32]; /* Do not use MA_MAX_CHANNELS here! */
  44051. /*
  44052. If we have a small enough number of channels, pre-compute the weights. Otherwise we'll just need to
  44053. fall back to a slower path because otherwise we'll run out of stack space.
  44054. */
  44055. if (channelsIn <= ma_countof(weights) && channelsOut <= ma_countof(weights)) {
  44056. /* Pre-compute weights. */
  44057. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44058. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  44059. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44060. ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn);
  44061. weights[iChannelOut][iChannelIn] = ma_calculate_channel_position_rectangular_weight(channelOut, channelIn);
  44062. }
  44063. }
  44064. iFrame = 0;
  44065. /* Experiment: Try an optimized unroll for some specific cases to see how it improves performance. RESULT: Good gains. */
  44066. if (channelsOut == 8) {
  44067. /* Experiment 2: Expand the inner loop to see what kind of different it makes. RESULT: Small, but worthwhile gain. */
  44068. if (channelsIn == 2) {
  44069. for (; iFrame < frameCount; iFrame += 1) {
  44070. float accumulation[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
  44071. accumulation[0] += pFramesIn[iFrame*2 + 0] * weights[0][0];
  44072. accumulation[1] += pFramesIn[iFrame*2 + 0] * weights[1][0];
  44073. accumulation[2] += pFramesIn[iFrame*2 + 0] * weights[2][0];
  44074. accumulation[3] += pFramesIn[iFrame*2 + 0] * weights[3][0];
  44075. accumulation[4] += pFramesIn[iFrame*2 + 0] * weights[4][0];
  44076. accumulation[5] += pFramesIn[iFrame*2 + 0] * weights[5][0];
  44077. accumulation[6] += pFramesIn[iFrame*2 + 0] * weights[6][0];
  44078. accumulation[7] += pFramesIn[iFrame*2 + 0] * weights[7][0];
  44079. accumulation[0] += pFramesIn[iFrame*2 + 1] * weights[0][1];
  44080. accumulation[1] += pFramesIn[iFrame*2 + 1] * weights[1][1];
  44081. accumulation[2] += pFramesIn[iFrame*2 + 1] * weights[2][1];
  44082. accumulation[3] += pFramesIn[iFrame*2 + 1] * weights[3][1];
  44083. accumulation[4] += pFramesIn[iFrame*2 + 1] * weights[4][1];
  44084. accumulation[5] += pFramesIn[iFrame*2 + 1] * weights[5][1];
  44085. accumulation[6] += pFramesIn[iFrame*2 + 1] * weights[6][1];
  44086. accumulation[7] += pFramesIn[iFrame*2 + 1] * weights[7][1];
  44087. pFramesOut[iFrame*8 + 0] = accumulation[0];
  44088. pFramesOut[iFrame*8 + 1] = accumulation[1];
  44089. pFramesOut[iFrame*8 + 2] = accumulation[2];
  44090. pFramesOut[iFrame*8 + 3] = accumulation[3];
  44091. pFramesOut[iFrame*8 + 4] = accumulation[4];
  44092. pFramesOut[iFrame*8 + 5] = accumulation[5];
  44093. pFramesOut[iFrame*8 + 6] = accumulation[6];
  44094. pFramesOut[iFrame*8 + 7] = accumulation[7];
  44095. }
  44096. } else {
  44097. /* When outputting to 8 channels, we can do everything in groups of two 4x SIMD operations. */
  44098. for (; iFrame < frameCount; iFrame += 1) {
  44099. float accumulation[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
  44100. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44101. accumulation[0] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[0][iChannelIn];
  44102. accumulation[1] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[1][iChannelIn];
  44103. accumulation[2] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[2][iChannelIn];
  44104. accumulation[3] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[3][iChannelIn];
  44105. accumulation[4] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[4][iChannelIn];
  44106. accumulation[5] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[5][iChannelIn];
  44107. accumulation[6] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[6][iChannelIn];
  44108. accumulation[7] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[7][iChannelIn];
  44109. }
  44110. pFramesOut[iFrame*8 + 0] = accumulation[0];
  44111. pFramesOut[iFrame*8 + 1] = accumulation[1];
  44112. pFramesOut[iFrame*8 + 2] = accumulation[2];
  44113. pFramesOut[iFrame*8 + 3] = accumulation[3];
  44114. pFramesOut[iFrame*8 + 4] = accumulation[4];
  44115. pFramesOut[iFrame*8 + 5] = accumulation[5];
  44116. pFramesOut[iFrame*8 + 6] = accumulation[6];
  44117. pFramesOut[iFrame*8 + 7] = accumulation[7];
  44118. }
  44119. }
  44120. } else if (channelsOut == 6) {
  44121. /*
  44122. When outputting to 6 channels we unfortunately don't have a nice multiple of 4 to do 4x SIMD operations. Instead we'll
  44123. expand our weights and do two frames at a time.
  44124. */
  44125. for (; iFrame < frameCount; iFrame += 1) {
  44126. float accumulation[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  44127. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44128. accumulation[0] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[0][iChannelIn];
  44129. accumulation[1] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[1][iChannelIn];
  44130. accumulation[2] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[2][iChannelIn];
  44131. accumulation[3] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[3][iChannelIn];
  44132. accumulation[4] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[4][iChannelIn];
  44133. accumulation[5] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[5][iChannelIn];
  44134. }
  44135. pFramesOut[iFrame*6 + 0] = accumulation[0];
  44136. pFramesOut[iFrame*6 + 1] = accumulation[1];
  44137. pFramesOut[iFrame*6 + 2] = accumulation[2];
  44138. pFramesOut[iFrame*6 + 3] = accumulation[3];
  44139. pFramesOut[iFrame*6 + 4] = accumulation[4];
  44140. pFramesOut[iFrame*6 + 5] = accumulation[5];
  44141. }
  44142. }
  44143. /* Leftover frames. */
  44144. for (; iFrame < frameCount; iFrame += 1) {
  44145. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44146. float accumulation = 0;
  44147. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44148. accumulation += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[iChannelOut][iChannelIn];
  44149. }
  44150. pFramesOut[iFrame*channelsOut + iChannelOut] = accumulation;
  44151. }
  44152. }
  44153. } else {
  44154. /* Cannot pre-compute weights because not enough room in stack-allocated buffer. */
  44155. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44156. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44157. float accumulation = 0;
  44158. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  44159. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44160. ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn);
  44161. accumulation += pFramesIn[iFrame*channelsIn + iChannelIn] * ma_calculate_channel_position_rectangular_weight(channelOut, channelIn);
  44162. }
  44163. pFramesOut[iFrame*channelsOut + iChannelOut] = accumulation;
  44164. }
  44165. }
  44166. }
  44167. }
  44168. } else {
  44169. /* Fall back to silence. If you hit this, what are you doing with so many channels?! */
  44170. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, channelsOut);
  44171. }
  44172. }
  44173. typedef struct
  44174. {
  44175. size_t sizeInBytes;
  44176. size_t channelMapInOffset;
  44177. size_t channelMapOutOffset;
  44178. size_t shuffleTableOffset;
  44179. size_t weightsOffset;
  44180. } ma_channel_converter_heap_layout;
  44181. static ma_channel_conversion_path ma_channel_converter_config_get_conversion_path(const ma_channel_converter_config* pConfig)
  44182. {
  44183. return ma_channel_map_get_conversion_path(pConfig->pChannelMapIn, pConfig->channelsIn, pConfig->pChannelMapOut, pConfig->channelsOut, pConfig->mixingMode);
  44184. }
  44185. static ma_result ma_channel_converter_get_heap_layout(const ma_channel_converter_config* pConfig, ma_channel_converter_heap_layout* pHeapLayout)
  44186. {
  44187. ma_channel_conversion_path conversionPath;
  44188. MA_ASSERT(pHeapLayout != NULL);
  44189. if (pConfig == NULL) {
  44190. return MA_INVALID_ARGS;
  44191. }
  44192. if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) {
  44193. return MA_INVALID_ARGS;
  44194. }
  44195. if (!ma_channel_map_is_valid(pConfig->pChannelMapIn, pConfig->channelsIn)) {
  44196. return MA_INVALID_ARGS;
  44197. }
  44198. if (!ma_channel_map_is_valid(pConfig->pChannelMapOut, pConfig->channelsOut)) {
  44199. return MA_INVALID_ARGS;
  44200. }
  44201. pHeapLayout->sizeInBytes = 0;
  44202. /* Input channel map. Only need to allocate this if we have an input channel map (otherwise default channel map is assumed). */
  44203. pHeapLayout->channelMapInOffset = pHeapLayout->sizeInBytes;
  44204. if (pConfig->pChannelMapIn != NULL) {
  44205. pHeapLayout->sizeInBytes += sizeof(ma_channel) * pConfig->channelsIn;
  44206. }
  44207. /* Output channel map. Only need to allocate this if we have an output channel map (otherwise default channel map is assumed). */
  44208. pHeapLayout->channelMapOutOffset = pHeapLayout->sizeInBytes;
  44209. if (pConfig->pChannelMapOut != NULL) {
  44210. pHeapLayout->sizeInBytes += sizeof(ma_channel) * pConfig->channelsOut;
  44211. }
  44212. /* Alignment for the next section. */
  44213. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  44214. /* Whether or not we use weights of a shuffle table depends on the channel map themselves and the algorithm we've chosen. */
  44215. conversionPath = ma_channel_converter_config_get_conversion_path(pConfig);
  44216. /* Shuffle table */
  44217. pHeapLayout->shuffleTableOffset = pHeapLayout->sizeInBytes;
  44218. if (conversionPath == ma_channel_conversion_path_shuffle) {
  44219. pHeapLayout->sizeInBytes += sizeof(ma_uint8) * pConfig->channelsOut;
  44220. }
  44221. /* Weights */
  44222. pHeapLayout->weightsOffset = pHeapLayout->sizeInBytes;
  44223. if (conversionPath == ma_channel_conversion_path_weights) {
  44224. pHeapLayout->sizeInBytes += sizeof(float*) * pConfig->channelsIn;
  44225. pHeapLayout->sizeInBytes += sizeof(float ) * pConfig->channelsIn * pConfig->channelsOut;
  44226. }
  44227. /* Make sure allocation size is aligned. */
  44228. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  44229. return MA_SUCCESS;
  44230. }
  44231. MA_API ma_result ma_channel_converter_get_heap_size(const ma_channel_converter_config* pConfig, size_t* pHeapSizeInBytes)
  44232. {
  44233. ma_result result;
  44234. ma_channel_converter_heap_layout heapLayout;
  44235. if (pHeapSizeInBytes == NULL) {
  44236. return MA_INVALID_ARGS;
  44237. }
  44238. *pHeapSizeInBytes = 0;
  44239. result = ma_channel_converter_get_heap_layout(pConfig, &heapLayout);
  44240. if (result != MA_SUCCESS) {
  44241. return result;
  44242. }
  44243. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  44244. return MA_SUCCESS;
  44245. }
  44246. MA_API ma_result ma_channel_converter_init_preallocated(const ma_channel_converter_config* pConfig, void* pHeap, ma_channel_converter* pConverter)
  44247. {
  44248. ma_result result;
  44249. ma_channel_converter_heap_layout heapLayout;
  44250. if (pConverter == NULL) {
  44251. return MA_INVALID_ARGS;
  44252. }
  44253. MA_ZERO_OBJECT(pConverter);
  44254. result = ma_channel_converter_get_heap_layout(pConfig, &heapLayout);
  44255. if (result != MA_SUCCESS) {
  44256. return result;
  44257. }
  44258. pConverter->_pHeap = pHeap;
  44259. MA_ZERO_MEMORY(pConverter->_pHeap, heapLayout.sizeInBytes);
  44260. pConverter->format = pConfig->format;
  44261. pConverter->channelsIn = pConfig->channelsIn;
  44262. pConverter->channelsOut = pConfig->channelsOut;
  44263. pConverter->mixingMode = pConfig->mixingMode;
  44264. if (pConfig->pChannelMapIn != NULL) {
  44265. pConverter->pChannelMapIn = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapInOffset);
  44266. ma_channel_map_copy_or_default(pConverter->pChannelMapIn, pConfig->channelsIn, pConfig->pChannelMapIn, pConfig->channelsIn);
  44267. } else {
  44268. pConverter->pChannelMapIn = NULL; /* Use default channel map. */
  44269. }
  44270. if (pConfig->pChannelMapOut != NULL) {
  44271. pConverter->pChannelMapOut = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapOutOffset);
  44272. ma_channel_map_copy_or_default(pConverter->pChannelMapOut, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelsOut);
  44273. } else {
  44274. pConverter->pChannelMapOut = NULL; /* Use default channel map. */
  44275. }
  44276. pConverter->conversionPath = ma_channel_converter_config_get_conversion_path(pConfig);
  44277. if (pConverter->conversionPath == ma_channel_conversion_path_shuffle) {
  44278. pConverter->pShuffleTable = (ma_uint8*)ma_offset_ptr(pHeap, heapLayout.shuffleTableOffset);
  44279. ma_channel_map_build_shuffle_table(pConverter->pChannelMapIn, pConverter->channelsIn, pConverter->pChannelMapOut, pConverter->channelsOut, pConverter->pShuffleTable);
  44280. }
  44281. if (pConverter->conversionPath == ma_channel_conversion_path_weights) {
  44282. ma_uint32 iChannelIn;
  44283. ma_uint32 iChannelOut;
  44284. if (pConverter->format == ma_format_f32) {
  44285. pConverter->weights.f32 = (float** )ma_offset_ptr(pHeap, heapLayout.weightsOffset);
  44286. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  44287. pConverter->weights.f32[iChannelIn] = (float*)ma_offset_ptr(pHeap, heapLayout.weightsOffset + ((sizeof(float*) * pConverter->channelsIn) + (sizeof(float) * pConverter->channelsOut * iChannelIn)));
  44288. }
  44289. } else {
  44290. pConverter->weights.s16 = (ma_int32**)ma_offset_ptr(pHeap, heapLayout.weightsOffset);
  44291. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  44292. pConverter->weights.s16[iChannelIn] = (ma_int32*)ma_offset_ptr(pHeap, heapLayout.weightsOffset + ((sizeof(ma_int32*) * pConverter->channelsIn) + (sizeof(ma_int32) * pConverter->channelsOut * iChannelIn)));
  44293. }
  44294. }
  44295. /* Silence our weights by default. */
  44296. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  44297. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; iChannelOut += 1) {
  44298. if (pConverter->format == ma_format_f32) {
  44299. pConverter->weights.f32[iChannelIn][iChannelOut] = 0.0f;
  44300. } else {
  44301. pConverter->weights.s16[iChannelIn][iChannelOut] = 0;
  44302. }
  44303. }
  44304. }
  44305. /*
  44306. We now need to fill out our weights table. This is determined by the mixing mode.
  44307. */
  44308. /* In all cases we need to make sure all channels that are present in both channel maps have a 1:1 mapping. */
  44309. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44310. ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  44311. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44312. ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut);
  44313. if (channelPosIn == channelPosOut) {
  44314. float weight = 1;
  44315. if (pConverter->format == ma_format_f32) {
  44316. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  44317. } else {
  44318. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  44319. }
  44320. }
  44321. }
  44322. }
  44323. switch (pConverter->mixingMode)
  44324. {
  44325. case ma_channel_mix_mode_custom_weights:
  44326. {
  44327. if (pConfig->ppWeights == NULL) {
  44328. return MA_INVALID_ARGS; /* Config specified a custom weights mixing mode, but no custom weights have been specified. */
  44329. }
  44330. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  44331. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; iChannelOut += 1) {
  44332. float weight = pConfig->ppWeights[iChannelIn][iChannelOut];
  44333. if (pConverter->format == ma_format_f32) {
  44334. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  44335. } else {
  44336. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  44337. }
  44338. }
  44339. }
  44340. } break;
  44341. case ma_channel_mix_mode_simple:
  44342. {
  44343. /*
  44344. In simple mode, only set weights for channels that have exactly matching types, leave the rest at
  44345. zero. The 1:1 mappings have already been covered before this switch statement.
  44346. */
  44347. } break;
  44348. case ma_channel_mix_mode_rectangular:
  44349. default:
  44350. {
  44351. /* Unmapped input channels. */
  44352. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44353. ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  44354. if (ma_is_spatial_channel_position(channelPosIn)) {
  44355. if (!ma_channel_map_contains_channel_position(pConverter->channelsOut, pConverter->pChannelMapOut, channelPosIn)) {
  44356. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44357. ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut);
  44358. if (ma_is_spatial_channel_position(channelPosOut)) {
  44359. float weight = 0;
  44360. if (pConverter->mixingMode == ma_channel_mix_mode_rectangular) {
  44361. weight = ma_calculate_channel_position_rectangular_weight(channelPosIn, channelPosOut);
  44362. }
  44363. /* Only apply the weight if we haven't already got some contribution from the respective channels. */
  44364. if (pConverter->format == ma_format_f32) {
  44365. if (pConverter->weights.f32[iChannelIn][iChannelOut] == 0) {
  44366. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  44367. }
  44368. } else {
  44369. if (pConverter->weights.s16[iChannelIn][iChannelOut] == 0) {
  44370. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  44371. }
  44372. }
  44373. }
  44374. }
  44375. }
  44376. }
  44377. }
  44378. /* Unmapped output channels. */
  44379. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44380. ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut);
  44381. if (ma_is_spatial_channel_position(channelPosOut)) {
  44382. if (!ma_channel_map_contains_channel_position(pConverter->channelsIn, pConverter->pChannelMapIn, channelPosOut)) {
  44383. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44384. ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  44385. if (ma_is_spatial_channel_position(channelPosIn)) {
  44386. float weight = 0;
  44387. if (pConverter->mixingMode == ma_channel_mix_mode_rectangular) {
  44388. weight = ma_calculate_channel_position_rectangular_weight(channelPosIn, channelPosOut);
  44389. }
  44390. /* Only apply the weight if we haven't already got some contribution from the respective channels. */
  44391. if (pConverter->format == ma_format_f32) {
  44392. if (pConverter->weights.f32[iChannelIn][iChannelOut] == 0) {
  44393. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  44394. }
  44395. } else {
  44396. if (pConverter->weights.s16[iChannelIn][iChannelOut] == 0) {
  44397. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  44398. }
  44399. }
  44400. }
  44401. }
  44402. }
  44403. }
  44404. }
  44405. /* If LFE is in the output channel map but was not present in the input channel map, configure its weight now */
  44406. if (pConfig->calculateLFEFromSpatialChannels) {
  44407. if (!ma_channel_map_contains_channel_position(pConverter->channelsIn, pConverter->pChannelMapIn, MA_CHANNEL_LFE)) {
  44408. ma_uint32 spatialChannelCount = ma_channel_map_get_spatial_channel_count(pConverter->pChannelMapIn, pConverter->channelsIn);
  44409. ma_uint32 iChannelOutLFE;
  44410. if (spatialChannelCount > 0 && ma_channel_map_find_channel_position(pConverter->channelsOut, pConverter->pChannelMapOut, MA_CHANNEL_LFE, &iChannelOutLFE)) {
  44411. const float weightForLFE = 1.0f / spatialChannelCount;
  44412. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44413. const ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  44414. if (ma_is_spatial_channel_position(channelPosIn)) {
  44415. if (pConverter->format == ma_format_f32) {
  44416. if (pConverter->weights.f32[iChannelIn][iChannelOutLFE] == 0) {
  44417. pConverter->weights.f32[iChannelIn][iChannelOutLFE] = weightForLFE;
  44418. }
  44419. } else {
  44420. if (pConverter->weights.s16[iChannelIn][iChannelOutLFE] == 0) {
  44421. pConverter->weights.s16[iChannelIn][iChannelOutLFE] = ma_channel_converter_float_to_fixed(weightForLFE);
  44422. }
  44423. }
  44424. }
  44425. }
  44426. }
  44427. }
  44428. }
  44429. } break;
  44430. }
  44431. }
  44432. return MA_SUCCESS;
  44433. }
  44434. MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_channel_converter* pConverter)
  44435. {
  44436. ma_result result;
  44437. size_t heapSizeInBytes;
  44438. void* pHeap;
  44439. result = ma_channel_converter_get_heap_size(pConfig, &heapSizeInBytes);
  44440. if (result != MA_SUCCESS) {
  44441. return result;
  44442. }
  44443. if (heapSizeInBytes > 0) {
  44444. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  44445. if (pHeap == NULL) {
  44446. return MA_OUT_OF_MEMORY;
  44447. }
  44448. } else {
  44449. pHeap = NULL;
  44450. }
  44451. result = ma_channel_converter_init_preallocated(pConfig, pHeap, pConverter);
  44452. if (result != MA_SUCCESS) {
  44453. ma_free(pHeap, pAllocationCallbacks);
  44454. return result;
  44455. }
  44456. pConverter->_ownsHeap = MA_TRUE;
  44457. return MA_SUCCESS;
  44458. }
  44459. MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks)
  44460. {
  44461. if (pConverter == NULL) {
  44462. return;
  44463. }
  44464. if (pConverter->_ownsHeap) {
  44465. ma_free(pConverter->_pHeap, pAllocationCallbacks);
  44466. }
  44467. }
  44468. static ma_result ma_channel_converter_process_pcm_frames__passthrough(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44469. {
  44470. MA_ASSERT(pConverter != NULL);
  44471. MA_ASSERT(pFramesOut != NULL);
  44472. MA_ASSERT(pFramesIn != NULL);
  44473. ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
  44474. return MA_SUCCESS;
  44475. }
  44476. static ma_result ma_channel_converter_process_pcm_frames__shuffle(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44477. {
  44478. MA_ASSERT(pConverter != NULL);
  44479. MA_ASSERT(pFramesOut != NULL);
  44480. MA_ASSERT(pFramesIn != NULL);
  44481. MA_ASSERT(pConverter->channelsIn == pConverter->channelsOut);
  44482. return ma_channel_map_apply_shuffle_table(pFramesOut, pConverter->channelsOut, pFramesIn, pConverter->channelsIn, frameCount, pConverter->pShuffleTable, pConverter->format);
  44483. }
  44484. static ma_result ma_channel_converter_process_pcm_frames__mono_in(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44485. {
  44486. ma_uint64 iFrame;
  44487. MA_ASSERT(pConverter != NULL);
  44488. MA_ASSERT(pFramesOut != NULL);
  44489. MA_ASSERT(pFramesIn != NULL);
  44490. MA_ASSERT(pConverter->channelsIn == 1);
  44491. switch (pConverter->format)
  44492. {
  44493. case ma_format_u8:
  44494. {
  44495. /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
  44496. const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
  44497. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44498. ma_uint32 iChannel;
  44499. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44500. pFramesOutU8[iFrame*pConverter->channelsOut + iChannel] = pFramesInU8[iFrame];
  44501. }
  44502. }
  44503. } break;
  44504. case ma_format_s16:
  44505. {
  44506. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  44507. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  44508. if (pConverter->channelsOut == 2) {
  44509. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44510. pFramesOutS16[iFrame*2 + 0] = pFramesInS16[iFrame];
  44511. pFramesOutS16[iFrame*2 + 1] = pFramesInS16[iFrame];
  44512. }
  44513. } else {
  44514. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44515. ma_uint32 iChannel;
  44516. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44517. pFramesOutS16[iFrame*pConverter->channelsOut + iChannel] = pFramesInS16[iFrame];
  44518. }
  44519. }
  44520. }
  44521. } break;
  44522. case ma_format_s24:
  44523. {
  44524. /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
  44525. const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
  44526. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44527. ma_uint32 iChannel;
  44528. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44529. ma_uint64 iSampleOut = iFrame*pConverter->channelsOut + iChannel;
  44530. ma_uint64 iSampleIn = iFrame;
  44531. pFramesOutS24[iSampleOut*3 + 0] = pFramesInS24[iSampleIn*3 + 0];
  44532. pFramesOutS24[iSampleOut*3 + 1] = pFramesInS24[iSampleIn*3 + 1];
  44533. pFramesOutS24[iSampleOut*3 + 2] = pFramesInS24[iSampleIn*3 + 2];
  44534. }
  44535. }
  44536. } break;
  44537. case ma_format_s32:
  44538. {
  44539. /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
  44540. const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
  44541. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44542. ma_uint32 iChannel;
  44543. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44544. pFramesOutS32[iFrame*pConverter->channelsOut + iChannel] = pFramesInS32[iFrame];
  44545. }
  44546. }
  44547. } break;
  44548. case ma_format_f32:
  44549. {
  44550. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  44551. const float* pFramesInF32 = (const float*)pFramesIn;
  44552. if (pConverter->channelsOut == 2) {
  44553. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44554. pFramesOutF32[iFrame*2 + 0] = pFramesInF32[iFrame];
  44555. pFramesOutF32[iFrame*2 + 1] = pFramesInF32[iFrame];
  44556. }
  44557. } else {
  44558. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44559. ma_uint32 iChannel;
  44560. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44561. pFramesOutF32[iFrame*pConverter->channelsOut + iChannel] = pFramesInF32[iFrame];
  44562. }
  44563. }
  44564. }
  44565. } break;
  44566. default: return MA_INVALID_OPERATION; /* Unknown format. */
  44567. }
  44568. return MA_SUCCESS;
  44569. }
  44570. static ma_result ma_channel_converter_process_pcm_frames__mono_out(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44571. {
  44572. ma_uint64 iFrame;
  44573. ma_uint32 iChannel;
  44574. MA_ASSERT(pConverter != NULL);
  44575. MA_ASSERT(pFramesOut != NULL);
  44576. MA_ASSERT(pFramesIn != NULL);
  44577. MA_ASSERT(pConverter->channelsOut == 1);
  44578. switch (pConverter->format)
  44579. {
  44580. case ma_format_u8:
  44581. {
  44582. /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
  44583. const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
  44584. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44585. ma_int32 t = 0;
  44586. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44587. t += ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8[iFrame*pConverter->channelsIn + iChannel]);
  44588. }
  44589. pFramesOutU8[iFrame] = ma_clip_u8(t / pConverter->channelsOut);
  44590. }
  44591. } break;
  44592. case ma_format_s16:
  44593. {
  44594. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  44595. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  44596. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44597. ma_int32 t = 0;
  44598. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44599. t += pFramesInS16[iFrame*pConverter->channelsIn + iChannel];
  44600. }
  44601. pFramesOutS16[iFrame] = (ma_int16)(t / pConverter->channelsIn);
  44602. }
  44603. } break;
  44604. case ma_format_s24:
  44605. {
  44606. /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
  44607. const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
  44608. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44609. ma_int64 t = 0;
  44610. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44611. t += ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24[(iFrame*pConverter->channelsIn + iChannel)*3]);
  44612. }
  44613. ma_pcm_sample_s32_to_s24_no_scale(t / pConverter->channelsIn, &pFramesOutS24[iFrame*3]);
  44614. }
  44615. } break;
  44616. case ma_format_s32:
  44617. {
  44618. /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
  44619. const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
  44620. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44621. ma_int64 t = 0;
  44622. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44623. t += pFramesInS32[iFrame*pConverter->channelsIn + iChannel];
  44624. }
  44625. pFramesOutS32[iFrame] = (ma_int32)(t / pConverter->channelsIn);
  44626. }
  44627. } break;
  44628. case ma_format_f32:
  44629. {
  44630. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  44631. const float* pFramesInF32 = (const float*)pFramesIn;
  44632. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44633. float t = 0;
  44634. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44635. t += pFramesInF32[iFrame*pConverter->channelsIn + iChannel];
  44636. }
  44637. pFramesOutF32[iFrame] = t / pConverter->channelsIn;
  44638. }
  44639. } break;
  44640. default: return MA_INVALID_OPERATION; /* Unknown format. */
  44641. }
  44642. return MA_SUCCESS;
  44643. }
  44644. static ma_result ma_channel_converter_process_pcm_frames__weights(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44645. {
  44646. ma_uint32 iFrame;
  44647. ma_uint32 iChannelIn;
  44648. ma_uint32 iChannelOut;
  44649. MA_ASSERT(pConverter != NULL);
  44650. MA_ASSERT(pFramesOut != NULL);
  44651. MA_ASSERT(pFramesIn != NULL);
  44652. /* This is the more complicated case. Each of the output channels is accumulated with 0 or more input channels. */
  44653. /* Clear. */
  44654. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
  44655. /* Accumulate. */
  44656. switch (pConverter->format)
  44657. {
  44658. case ma_format_u8:
  44659. {
  44660. /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
  44661. const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
  44662. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44663. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44664. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44665. ma_int16 u8_O = ma_pcm_sample_u8_to_s16_no_scale(pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut]);
  44666. ma_int16 u8_I = ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8 [iFrame*pConverter->channelsIn + iChannelIn ]);
  44667. ma_int32 s = (ma_int32)ma_clamp(u8_O + ((u8_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -128, 127);
  44668. pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_u8((ma_int16)s);
  44669. }
  44670. }
  44671. }
  44672. } break;
  44673. case ma_format_s16:
  44674. {
  44675. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  44676. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  44677. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44678. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44679. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44680. ma_int32 s = pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut];
  44681. s += (pFramesInS16[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT;
  44682. pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut] = (ma_int16)ma_clamp(s, -32768, 32767);
  44683. }
  44684. }
  44685. }
  44686. } break;
  44687. case ma_format_s24:
  44688. {
  44689. /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
  44690. const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
  44691. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44692. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44693. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44694. ma_int64 s24_O = ma_pcm_sample_s24_to_s32_no_scale(&pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]);
  44695. ma_int64 s24_I = ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24 [(iFrame*pConverter->channelsIn + iChannelIn )*3]);
  44696. ma_int64 s24 = (ma_int32)ma_clamp(s24_O + ((s24_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -8388608, 8388607);
  44697. ma_pcm_sample_s32_to_s24_no_scale(s24, &pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]);
  44698. }
  44699. }
  44700. }
  44701. } break;
  44702. case ma_format_s32:
  44703. {
  44704. /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
  44705. const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
  44706. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44707. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44708. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44709. ma_int64 s = pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut];
  44710. s += ((ma_int64)pFramesInS32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT;
  44711. pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_s32(s);
  44712. }
  44713. }
  44714. }
  44715. } break;
  44716. case ma_format_f32:
  44717. {
  44718. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  44719. const float* pFramesInF32 = (const float*)pFramesIn;
  44720. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44721. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44722. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44723. pFramesOutF32[iFrame*pConverter->channelsOut + iChannelOut] += pFramesInF32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.f32[iChannelIn][iChannelOut];
  44724. }
  44725. }
  44726. }
  44727. } break;
  44728. default: return MA_INVALID_OPERATION; /* Unknown format. */
  44729. }
  44730. return MA_SUCCESS;
  44731. }
  44732. MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44733. {
  44734. if (pConverter == NULL) {
  44735. return MA_INVALID_ARGS;
  44736. }
  44737. if (pFramesOut == NULL) {
  44738. return MA_INVALID_ARGS;
  44739. }
  44740. if (pFramesIn == NULL) {
  44741. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
  44742. return MA_SUCCESS;
  44743. }
  44744. switch (pConverter->conversionPath)
  44745. {
  44746. case ma_channel_conversion_path_passthrough: return ma_channel_converter_process_pcm_frames__passthrough(pConverter, pFramesOut, pFramesIn, frameCount);
  44747. case ma_channel_conversion_path_mono_out: return ma_channel_converter_process_pcm_frames__mono_out(pConverter, pFramesOut, pFramesIn, frameCount);
  44748. case ma_channel_conversion_path_mono_in: return ma_channel_converter_process_pcm_frames__mono_in(pConverter, pFramesOut, pFramesIn, frameCount);
  44749. case ma_channel_conversion_path_shuffle: return ma_channel_converter_process_pcm_frames__shuffle(pConverter, pFramesOut, pFramesIn, frameCount);
  44750. case ma_channel_conversion_path_weights:
  44751. default:
  44752. {
  44753. return ma_channel_converter_process_pcm_frames__weights(pConverter, pFramesOut, pFramesIn, frameCount);
  44754. }
  44755. }
  44756. }
  44757. MA_API ma_result ma_channel_converter_get_input_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  44758. {
  44759. if (pConverter == NULL || pChannelMap == NULL) {
  44760. return MA_INVALID_ARGS;
  44761. }
  44762. ma_channel_map_copy_or_default(pChannelMap, channelMapCap, pConverter->pChannelMapIn, pConverter->channelsIn);
  44763. return MA_SUCCESS;
  44764. }
  44765. MA_API ma_result ma_channel_converter_get_output_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  44766. {
  44767. if (pConverter == NULL || pChannelMap == NULL) {
  44768. return MA_INVALID_ARGS;
  44769. }
  44770. ma_channel_map_copy_or_default(pChannelMap, channelMapCap, pConverter->pChannelMapOut, pConverter->channelsOut);
  44771. return MA_SUCCESS;
  44772. }
  44773. /**************************************************************************************************************************************************************
  44774. Data Conversion
  44775. **************************************************************************************************************************************************************/
  44776. MA_API ma_data_converter_config ma_data_converter_config_init_default(void)
  44777. {
  44778. ma_data_converter_config config;
  44779. MA_ZERO_OBJECT(&config);
  44780. config.ditherMode = ma_dither_mode_none;
  44781. config.resampling.algorithm = ma_resample_algorithm_linear;
  44782. config.allowDynamicSampleRate = MA_FALSE; /* Disable dynamic sample rates by default because dynamic rate adjustments should be quite rare and it allows an optimization for cases when the in and out sample rates are the same. */
  44783. /* Linear resampling defaults. */
  44784. config.resampling.linear.lpfOrder = 1;
  44785. return config;
  44786. }
  44787. MA_API ma_data_converter_config ma_data_converter_config_init(ma_format formatIn, ma_format formatOut, ma_uint32 channelsIn, ma_uint32 channelsOut, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  44788. {
  44789. ma_data_converter_config config = ma_data_converter_config_init_default();
  44790. config.formatIn = formatIn;
  44791. config.formatOut = formatOut;
  44792. config.channelsIn = channelsIn;
  44793. config.channelsOut = channelsOut;
  44794. config.sampleRateIn = sampleRateIn;
  44795. config.sampleRateOut = sampleRateOut;
  44796. return config;
  44797. }
  44798. typedef struct
  44799. {
  44800. size_t sizeInBytes;
  44801. size_t channelConverterOffset;
  44802. size_t resamplerOffset;
  44803. } ma_data_converter_heap_layout;
  44804. static ma_bool32 ma_data_converter_config_is_resampler_required(const ma_data_converter_config* pConfig)
  44805. {
  44806. MA_ASSERT(pConfig != NULL);
  44807. return pConfig->allowDynamicSampleRate || pConfig->sampleRateIn != pConfig->sampleRateOut;
  44808. }
  44809. static ma_format ma_data_converter_config_get_mid_format(const ma_data_converter_config* pConfig)
  44810. {
  44811. MA_ASSERT(pConfig != NULL);
  44812. /*
  44813. We want to avoid as much data conversion as possible. The channel converter and linear
  44814. resampler both support s16 and f32 natively. We need to decide on the format to use for this
  44815. stage. We call this the mid format because it's used in the middle stage of the conversion
  44816. pipeline. If the output format is either s16 or f32 we use that one. If that is not the case it
  44817. will do the same thing for the input format. If it's neither we just use f32. If we are using a
  44818. custom resampling backend, we can only guarantee that f32 will be supported so we'll be forced
  44819. to use that if resampling is required.
  44820. */
  44821. if (ma_data_converter_config_is_resampler_required(pConfig) && pConfig->resampling.algorithm != ma_resample_algorithm_linear) {
  44822. return ma_format_f32; /* <-- Force f32 since that is the only one we can guarantee will be supported by the resampler. */
  44823. } else {
  44824. /* */ if (pConfig->formatOut == ma_format_s16 || pConfig->formatOut == ma_format_f32) {
  44825. return pConfig->formatOut;
  44826. } else if (pConfig->formatIn == ma_format_s16 || pConfig->formatIn == ma_format_f32) {
  44827. return pConfig->formatIn;
  44828. } else {
  44829. return ma_format_f32;
  44830. }
  44831. }
  44832. }
  44833. static ma_channel_converter_config ma_channel_converter_config_init_from_data_converter_config(const ma_data_converter_config* pConfig)
  44834. {
  44835. ma_channel_converter_config channelConverterConfig;
  44836. MA_ASSERT(pConfig != NULL);
  44837. channelConverterConfig = ma_channel_converter_config_init(ma_data_converter_config_get_mid_format(pConfig), pConfig->channelsIn, pConfig->pChannelMapIn, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelMixMode);
  44838. channelConverterConfig.ppWeights = pConfig->ppChannelWeights;
  44839. channelConverterConfig.calculateLFEFromSpatialChannels = pConfig->calculateLFEFromSpatialChannels;
  44840. return channelConverterConfig;
  44841. }
  44842. static ma_resampler_config ma_resampler_config_init_from_data_converter_config(const ma_data_converter_config* pConfig)
  44843. {
  44844. ma_resampler_config resamplerConfig;
  44845. ma_uint32 resamplerChannels;
  44846. MA_ASSERT(pConfig != NULL);
  44847. /* The resampler is the most expensive part of the conversion process, so we need to do it at the stage where the channel count is at it's lowest. */
  44848. if (pConfig->channelsIn < pConfig->channelsOut) {
  44849. resamplerChannels = pConfig->channelsIn;
  44850. } else {
  44851. resamplerChannels = pConfig->channelsOut;
  44852. }
  44853. resamplerConfig = ma_resampler_config_init(ma_data_converter_config_get_mid_format(pConfig), resamplerChannels, pConfig->sampleRateIn, pConfig->sampleRateOut, pConfig->resampling.algorithm);
  44854. resamplerConfig.linear = pConfig->resampling.linear;
  44855. resamplerConfig.pBackendVTable = pConfig->resampling.pBackendVTable;
  44856. resamplerConfig.pBackendUserData = pConfig->resampling.pBackendUserData;
  44857. return resamplerConfig;
  44858. }
  44859. static ma_result ma_data_converter_get_heap_layout(const ma_data_converter_config* pConfig, ma_data_converter_heap_layout* pHeapLayout)
  44860. {
  44861. ma_result result;
  44862. MA_ASSERT(pHeapLayout != NULL);
  44863. MA_ZERO_OBJECT(pHeapLayout);
  44864. if (pConfig == NULL) {
  44865. return MA_INVALID_ARGS;
  44866. }
  44867. if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) {
  44868. return MA_INVALID_ARGS;
  44869. }
  44870. pHeapLayout->sizeInBytes = 0;
  44871. /* Channel converter. */
  44872. pHeapLayout->channelConverterOffset = pHeapLayout->sizeInBytes;
  44873. {
  44874. size_t heapSizeInBytes;
  44875. ma_channel_converter_config channelConverterConfig = ma_channel_converter_config_init_from_data_converter_config(pConfig);
  44876. result = ma_channel_converter_get_heap_size(&channelConverterConfig, &heapSizeInBytes);
  44877. if (result != MA_SUCCESS) {
  44878. return result;
  44879. }
  44880. pHeapLayout->sizeInBytes += heapSizeInBytes;
  44881. }
  44882. /* Resampler. */
  44883. pHeapLayout->resamplerOffset = pHeapLayout->sizeInBytes;
  44884. if (ma_data_converter_config_is_resampler_required(pConfig)) {
  44885. size_t heapSizeInBytes;
  44886. ma_resampler_config resamplerConfig = ma_resampler_config_init_from_data_converter_config(pConfig);
  44887. result = ma_resampler_get_heap_size(&resamplerConfig, &heapSizeInBytes);
  44888. if (result != MA_SUCCESS) {
  44889. return result;
  44890. }
  44891. pHeapLayout->sizeInBytes += heapSizeInBytes;
  44892. }
  44893. /* Make sure allocation size is aligned. */
  44894. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  44895. return MA_SUCCESS;
  44896. }
  44897. MA_API ma_result ma_data_converter_get_heap_size(const ma_data_converter_config* pConfig, size_t* pHeapSizeInBytes)
  44898. {
  44899. ma_result result;
  44900. ma_data_converter_heap_layout heapLayout;
  44901. if (pHeapSizeInBytes == NULL) {
  44902. return MA_INVALID_ARGS;
  44903. }
  44904. *pHeapSizeInBytes = 0;
  44905. result = ma_data_converter_get_heap_layout(pConfig, &heapLayout);
  44906. if (result != MA_SUCCESS) {
  44907. return result;
  44908. }
  44909. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  44910. return MA_SUCCESS;
  44911. }
  44912. MA_API ma_result ma_data_converter_init_preallocated(const ma_data_converter_config* pConfig, void* pHeap, ma_data_converter* pConverter)
  44913. {
  44914. ma_result result;
  44915. ma_data_converter_heap_layout heapLayout;
  44916. ma_format midFormat;
  44917. ma_bool32 isResamplingRequired;
  44918. if (pConverter == NULL) {
  44919. return MA_INVALID_ARGS;
  44920. }
  44921. MA_ZERO_OBJECT(pConverter);
  44922. result = ma_data_converter_get_heap_layout(pConfig, &heapLayout);
  44923. if (result != MA_SUCCESS) {
  44924. return result;
  44925. }
  44926. pConverter->_pHeap = pHeap;
  44927. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  44928. pConverter->formatIn = pConfig->formatIn;
  44929. pConverter->formatOut = pConfig->formatOut;
  44930. pConverter->channelsIn = pConfig->channelsIn;
  44931. pConverter->channelsOut = pConfig->channelsOut;
  44932. pConverter->sampleRateIn = pConfig->sampleRateIn;
  44933. pConverter->sampleRateOut = pConfig->sampleRateOut;
  44934. pConverter->ditherMode = pConfig->ditherMode;
  44935. /*
  44936. Determine if resampling is required. We need to do this so we can determine an appropriate
  44937. mid format to use. If resampling is required, the mid format must be ma_format_f32 since
  44938. that is the only one that is guaranteed to supported by custom resampling backends.
  44939. */
  44940. isResamplingRequired = ma_data_converter_config_is_resampler_required(pConfig);
  44941. midFormat = ma_data_converter_config_get_mid_format(pConfig);
  44942. /* Channel converter. We always initialize this, but we check if it configures itself as a passthrough to determine whether or not it's needed. */
  44943. {
  44944. ma_channel_converter_config channelConverterConfig = ma_channel_converter_config_init_from_data_converter_config(pConfig);
  44945. result = ma_channel_converter_init_preallocated(&channelConverterConfig, ma_offset_ptr(pHeap, heapLayout.channelConverterOffset), &pConverter->channelConverter);
  44946. if (result != MA_SUCCESS) {
  44947. return result;
  44948. }
  44949. /* If the channel converter is not a passthrough we need to enable it. Otherwise we can skip it. */
  44950. if (pConverter->channelConverter.conversionPath != ma_channel_conversion_path_passthrough) {
  44951. pConverter->hasChannelConverter = MA_TRUE;
  44952. }
  44953. }
  44954. /* Resampler. */
  44955. if (isResamplingRequired) {
  44956. ma_resampler_config resamplerConfig = ma_resampler_config_init_from_data_converter_config(pConfig);
  44957. result = ma_resampler_init_preallocated(&resamplerConfig, ma_offset_ptr(pHeap, heapLayout.resamplerOffset), &pConverter->resampler);
  44958. if (result != MA_SUCCESS) {
  44959. return result;
  44960. }
  44961. pConverter->hasResampler = MA_TRUE;
  44962. }
  44963. /* We can simplify pre- and post-format conversion if we have neither channel conversion nor resampling. */
  44964. if (pConverter->hasChannelConverter == MA_FALSE && pConverter->hasResampler == MA_FALSE) {
  44965. /* We have neither channel conversion nor resampling so we'll only need one of pre- or post-format conversion, or none if the input and output formats are the same. */
  44966. if (pConverter->formatIn == pConverter->formatOut) {
  44967. /* The formats are the same so we can just pass through. */
  44968. pConverter->hasPreFormatConversion = MA_FALSE;
  44969. pConverter->hasPostFormatConversion = MA_FALSE;
  44970. } else {
  44971. /* The formats are different so we need to do either pre- or post-format conversion. It doesn't matter which. */
  44972. pConverter->hasPreFormatConversion = MA_FALSE;
  44973. pConverter->hasPostFormatConversion = MA_TRUE;
  44974. }
  44975. } else {
  44976. /* We have a channel converter and/or resampler so we'll need channel conversion based on the mid format. */
  44977. if (pConverter->formatIn != midFormat) {
  44978. pConverter->hasPreFormatConversion = MA_TRUE;
  44979. }
  44980. if (pConverter->formatOut != midFormat) {
  44981. pConverter->hasPostFormatConversion = MA_TRUE;
  44982. }
  44983. }
  44984. /* We can enable passthrough optimizations if applicable. Note that we'll only be able to do this if the sample rate is static. */
  44985. if (pConverter->hasPreFormatConversion == MA_FALSE &&
  44986. pConverter->hasPostFormatConversion == MA_FALSE &&
  44987. pConverter->hasChannelConverter == MA_FALSE &&
  44988. pConverter->hasResampler == MA_FALSE) {
  44989. pConverter->isPassthrough = MA_TRUE;
  44990. }
  44991. /* We now need to determine our execution path. */
  44992. if (pConverter->isPassthrough) {
  44993. pConverter->executionPath = ma_data_converter_execution_path_passthrough;
  44994. } else {
  44995. if (pConverter->channelsIn < pConverter->channelsOut) {
  44996. /* Do resampling first, if necessary. */
  44997. MA_ASSERT(pConverter->hasChannelConverter == MA_TRUE);
  44998. if (pConverter->hasResampler) {
  44999. pConverter->executionPath = ma_data_converter_execution_path_resample_first;
  45000. } else {
  45001. pConverter->executionPath = ma_data_converter_execution_path_channels_only;
  45002. }
  45003. } else {
  45004. /* Do channel conversion first, if necessary. */
  45005. if (pConverter->hasChannelConverter) {
  45006. if (pConverter->hasResampler) {
  45007. pConverter->executionPath = ma_data_converter_execution_path_channels_first;
  45008. } else {
  45009. pConverter->executionPath = ma_data_converter_execution_path_channels_only;
  45010. }
  45011. } else {
  45012. /* Channel routing not required. */
  45013. if (pConverter->hasResampler) {
  45014. pConverter->executionPath = ma_data_converter_execution_path_resample_only;
  45015. } else {
  45016. pConverter->executionPath = ma_data_converter_execution_path_format_only;
  45017. }
  45018. }
  45019. }
  45020. }
  45021. return MA_SUCCESS;
  45022. }
  45023. MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_converter* pConverter)
  45024. {
  45025. ma_result result;
  45026. size_t heapSizeInBytes;
  45027. void* pHeap;
  45028. result = ma_data_converter_get_heap_size(pConfig, &heapSizeInBytes);
  45029. if (result != MA_SUCCESS) {
  45030. return result;
  45031. }
  45032. if (heapSizeInBytes > 0) {
  45033. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  45034. if (pHeap == NULL) {
  45035. return MA_OUT_OF_MEMORY;
  45036. }
  45037. } else {
  45038. pHeap = NULL;
  45039. }
  45040. result = ma_data_converter_init_preallocated(pConfig, pHeap, pConverter);
  45041. if (result != MA_SUCCESS) {
  45042. ma_free(pHeap, pAllocationCallbacks);
  45043. return result;
  45044. }
  45045. pConverter->_ownsHeap = MA_TRUE;
  45046. return MA_SUCCESS;
  45047. }
  45048. MA_API void ma_data_converter_uninit(ma_data_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks)
  45049. {
  45050. if (pConverter == NULL) {
  45051. return;
  45052. }
  45053. if (pConverter->hasResampler) {
  45054. ma_resampler_uninit(&pConverter->resampler, pAllocationCallbacks);
  45055. }
  45056. ma_channel_converter_uninit(&pConverter->channelConverter, pAllocationCallbacks);
  45057. if (pConverter->_ownsHeap) {
  45058. ma_free(pConverter->_pHeap, pAllocationCallbacks);
  45059. }
  45060. }
  45061. static ma_result ma_data_converter_process_pcm_frames__passthrough(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  45062. {
  45063. ma_uint64 frameCountIn;
  45064. ma_uint64 frameCountOut;
  45065. ma_uint64 frameCount;
  45066. MA_ASSERT(pConverter != NULL);
  45067. frameCountIn = 0;
  45068. if (pFrameCountIn != NULL) {
  45069. frameCountIn = *pFrameCountIn;
  45070. }
  45071. frameCountOut = 0;
  45072. if (pFrameCountOut != NULL) {
  45073. frameCountOut = *pFrameCountOut;
  45074. }
  45075. frameCount = ma_min(frameCountIn, frameCountOut);
  45076. if (pFramesOut != NULL) {
  45077. if (pFramesIn != NULL) {
  45078. ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45079. } else {
  45080. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45081. }
  45082. }
  45083. if (pFrameCountIn != NULL) {
  45084. *pFrameCountIn = frameCount;
  45085. }
  45086. if (pFrameCountOut != NULL) {
  45087. *pFrameCountOut = frameCount;
  45088. }
  45089. return MA_SUCCESS;
  45090. }
  45091. static ma_result ma_data_converter_process_pcm_frames__format_only(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  45092. {
  45093. ma_uint64 frameCountIn;
  45094. ma_uint64 frameCountOut;
  45095. ma_uint64 frameCount;
  45096. MA_ASSERT(pConverter != NULL);
  45097. frameCountIn = 0;
  45098. if (pFrameCountIn != NULL) {
  45099. frameCountIn = *pFrameCountIn;
  45100. }
  45101. frameCountOut = 0;
  45102. if (pFrameCountOut != NULL) {
  45103. frameCountOut = *pFrameCountOut;
  45104. }
  45105. frameCount = ma_min(frameCountIn, frameCountOut);
  45106. if (pFramesOut != NULL) {
  45107. if (pFramesIn != NULL) {
  45108. ma_convert_pcm_frames_format(pFramesOut, pConverter->formatOut, pFramesIn, pConverter->formatIn, frameCount, pConverter->channelsIn, pConverter->ditherMode);
  45109. } else {
  45110. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45111. }
  45112. }
  45113. if (pFrameCountIn != NULL) {
  45114. *pFrameCountIn = frameCount;
  45115. }
  45116. if (pFrameCountOut != NULL) {
  45117. *pFrameCountOut = frameCount;
  45118. }
  45119. return MA_SUCCESS;
  45120. }
  45121. static ma_result ma_data_converter_process_pcm_frames__resample_with_format_conversion(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  45122. {
  45123. ma_result result = MA_SUCCESS;
  45124. ma_uint64 frameCountIn;
  45125. ma_uint64 frameCountOut;
  45126. ma_uint64 framesProcessedIn;
  45127. ma_uint64 framesProcessedOut;
  45128. MA_ASSERT(pConverter != NULL);
  45129. frameCountIn = 0;
  45130. if (pFrameCountIn != NULL) {
  45131. frameCountIn = *pFrameCountIn;
  45132. }
  45133. frameCountOut = 0;
  45134. if (pFrameCountOut != NULL) {
  45135. frameCountOut = *pFrameCountOut;
  45136. }
  45137. framesProcessedIn = 0;
  45138. framesProcessedOut = 0;
  45139. while (framesProcessedOut < frameCountOut) {
  45140. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  45141. const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45142. const void* pFramesInThisIteration;
  45143. /* */ void* pFramesOutThisIteration;
  45144. ma_uint64 frameCountInThisIteration;
  45145. ma_uint64 frameCountOutThisIteration;
  45146. if (pFramesIn != NULL) {
  45147. pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  45148. } else {
  45149. pFramesInThisIteration = NULL;
  45150. }
  45151. if (pFramesOut != NULL) {
  45152. pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45153. } else {
  45154. pFramesOutThisIteration = NULL;
  45155. }
  45156. /* Do a pre format conversion if necessary. */
  45157. if (pConverter->hasPreFormatConversion) {
  45158. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  45159. const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45160. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  45161. if (frameCountInThisIteration > tempBufferInCap) {
  45162. frameCountInThisIteration = tempBufferInCap;
  45163. }
  45164. if (pConverter->hasPostFormatConversion) {
  45165. if (frameCountInThisIteration > tempBufferOutCap) {
  45166. frameCountInThisIteration = tempBufferOutCap;
  45167. }
  45168. }
  45169. if (pFramesInThisIteration != NULL) {
  45170. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.format, pFramesInThisIteration, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  45171. } else {
  45172. MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn));
  45173. }
  45174. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  45175. if (pConverter->hasPostFormatConversion) {
  45176. /* Both input and output conversion required. Output to the temp buffer. */
  45177. if (frameCountOutThisIteration > tempBufferOutCap) {
  45178. frameCountOutThisIteration = tempBufferOutCap;
  45179. }
  45180. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration);
  45181. } else {
  45182. /* Only pre-format required. Output straight to the output buffer. */
  45183. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pFramesOutThisIteration, &frameCountOutThisIteration);
  45184. }
  45185. if (result != MA_SUCCESS) {
  45186. break;
  45187. }
  45188. } else {
  45189. /* No pre-format required. Just read straight from the input buffer. */
  45190. MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE);
  45191. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  45192. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  45193. if (frameCountOutThisIteration > tempBufferOutCap) {
  45194. frameCountOutThisIteration = tempBufferOutCap;
  45195. }
  45196. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesInThisIteration, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration);
  45197. if (result != MA_SUCCESS) {
  45198. break;
  45199. }
  45200. }
  45201. /* If we are doing a post format conversion we need to do that now. */
  45202. if (pConverter->hasPostFormatConversion) {
  45203. if (pFramesOutThisIteration != NULL) {
  45204. ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->formatOut, pTempBufferOut, pConverter->resampler.format, frameCountOutThisIteration, pConverter->resampler.channels, pConverter->ditherMode);
  45205. }
  45206. }
  45207. framesProcessedIn += frameCountInThisIteration;
  45208. framesProcessedOut += frameCountOutThisIteration;
  45209. MA_ASSERT(framesProcessedIn <= frameCountIn);
  45210. MA_ASSERT(framesProcessedOut <= frameCountOut);
  45211. if (frameCountOutThisIteration == 0) {
  45212. break; /* Consumed all of our input data. */
  45213. }
  45214. }
  45215. if (pFrameCountIn != NULL) {
  45216. *pFrameCountIn = framesProcessedIn;
  45217. }
  45218. if (pFrameCountOut != NULL) {
  45219. *pFrameCountOut = framesProcessedOut;
  45220. }
  45221. return result;
  45222. }
  45223. static ma_result ma_data_converter_process_pcm_frames__resample_only(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  45224. {
  45225. MA_ASSERT(pConverter != NULL);
  45226. if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) {
  45227. /* Neither pre- nor post-format required. This is simple case where only resampling is required. */
  45228. return ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45229. } else {
  45230. /* Format conversion required. */
  45231. return ma_data_converter_process_pcm_frames__resample_with_format_conversion(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45232. }
  45233. }
  45234. static ma_result ma_data_converter_process_pcm_frames__channels_only(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  45235. {
  45236. ma_result result;
  45237. ma_uint64 frameCountIn;
  45238. ma_uint64 frameCountOut;
  45239. ma_uint64 frameCount;
  45240. MA_ASSERT(pConverter != NULL);
  45241. frameCountIn = 0;
  45242. if (pFrameCountIn != NULL) {
  45243. frameCountIn = *pFrameCountIn;
  45244. }
  45245. frameCountOut = 0;
  45246. if (pFrameCountOut != NULL) {
  45247. frameCountOut = *pFrameCountOut;
  45248. }
  45249. frameCount = ma_min(frameCountIn, frameCountOut);
  45250. if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) {
  45251. /* No format conversion required. */
  45252. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOut, pFramesIn, frameCount);
  45253. if (result != MA_SUCCESS) {
  45254. return result;
  45255. }
  45256. } else {
  45257. /* Format conversion required. */
  45258. ma_uint64 framesProcessed = 0;
  45259. while (framesProcessed < frameCount) {
  45260. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  45261. const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
  45262. const void* pFramesInThisIteration;
  45263. /* */ void* pFramesOutThisIteration;
  45264. ma_uint64 frameCountThisIteration;
  45265. if (pFramesIn != NULL) {
  45266. pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessed * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  45267. } else {
  45268. pFramesInThisIteration = NULL;
  45269. }
  45270. if (pFramesOut != NULL) {
  45271. pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessed * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45272. } else {
  45273. pFramesOutThisIteration = NULL;
  45274. }
  45275. /* Do a pre format conversion if necessary. */
  45276. if (pConverter->hasPreFormatConversion) {
  45277. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  45278. const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn);
  45279. frameCountThisIteration = (frameCount - framesProcessed);
  45280. if (frameCountThisIteration > tempBufferInCap) {
  45281. frameCountThisIteration = tempBufferInCap;
  45282. }
  45283. if (pConverter->hasPostFormatConversion) {
  45284. if (frameCountThisIteration > tempBufferOutCap) {
  45285. frameCountThisIteration = tempBufferOutCap;
  45286. }
  45287. }
  45288. if (pFramesInThisIteration != NULL) {
  45289. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pFramesInThisIteration, pConverter->formatIn, frameCountThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  45290. } else {
  45291. MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn));
  45292. }
  45293. if (pConverter->hasPostFormatConversion) {
  45294. /* Both input and output conversion required. Output to the temp buffer. */
  45295. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pTempBufferIn, frameCountThisIteration);
  45296. } else {
  45297. /* Only pre-format required. Output straight to the output buffer. */
  45298. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOutThisIteration, pTempBufferIn, frameCountThisIteration);
  45299. }
  45300. if (result != MA_SUCCESS) {
  45301. break;
  45302. }
  45303. } else {
  45304. /* No pre-format required. Just read straight from the input buffer. */
  45305. MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE);
  45306. frameCountThisIteration = (frameCount - framesProcessed);
  45307. if (frameCountThisIteration > tempBufferOutCap) {
  45308. frameCountThisIteration = tempBufferOutCap;
  45309. }
  45310. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pFramesInThisIteration, frameCountThisIteration);
  45311. if (result != MA_SUCCESS) {
  45312. break;
  45313. }
  45314. }
  45315. /* If we are doing a post format conversion we need to do that now. */
  45316. if (pConverter->hasPostFormatConversion) {
  45317. if (pFramesOutThisIteration != NULL) {
  45318. ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->formatOut, pTempBufferOut, pConverter->channelConverter.format, frameCountThisIteration, pConverter->channelConverter.channelsOut, pConverter->ditherMode);
  45319. }
  45320. }
  45321. framesProcessed += frameCountThisIteration;
  45322. }
  45323. }
  45324. if (pFrameCountIn != NULL) {
  45325. *pFrameCountIn = frameCount;
  45326. }
  45327. if (pFrameCountOut != NULL) {
  45328. *pFrameCountOut = frameCount;
  45329. }
  45330. return MA_SUCCESS;
  45331. }
  45332. static ma_result ma_data_converter_process_pcm_frames__resample_first(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  45333. {
  45334. ma_result result;
  45335. ma_uint64 frameCountIn;
  45336. ma_uint64 frameCountOut;
  45337. ma_uint64 framesProcessedIn;
  45338. ma_uint64 framesProcessedOut;
  45339. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */
  45340. ma_uint64 tempBufferInCap;
  45341. ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */
  45342. ma_uint64 tempBufferMidCap;
  45343. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */
  45344. ma_uint64 tempBufferOutCap;
  45345. MA_ASSERT(pConverter != NULL);
  45346. MA_ASSERT(pConverter->resampler.format == pConverter->channelConverter.format);
  45347. MA_ASSERT(pConverter->resampler.channels == pConverter->channelConverter.channelsIn);
  45348. MA_ASSERT(pConverter->resampler.channels < pConverter->channelConverter.channelsOut);
  45349. frameCountIn = 0;
  45350. if (pFrameCountIn != NULL) {
  45351. frameCountIn = *pFrameCountIn;
  45352. }
  45353. frameCountOut = 0;
  45354. if (pFrameCountOut != NULL) {
  45355. frameCountOut = *pFrameCountOut;
  45356. }
  45357. framesProcessedIn = 0;
  45358. framesProcessedOut = 0;
  45359. tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45360. tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45361. tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
  45362. while (framesProcessedOut < frameCountOut) {
  45363. ma_uint64 frameCountInThisIteration;
  45364. ma_uint64 frameCountOutThisIteration;
  45365. const void* pRunningFramesIn = NULL;
  45366. void* pRunningFramesOut = NULL;
  45367. const void* pResampleBufferIn;
  45368. void* pChannelsBufferOut;
  45369. if (pFramesIn != NULL) {
  45370. pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  45371. }
  45372. if (pFramesOut != NULL) {
  45373. pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45374. }
  45375. /* Run input data through the resampler and output it to the temporary buffer. */
  45376. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  45377. if (pConverter->hasPreFormatConversion) {
  45378. if (frameCountInThisIteration > tempBufferInCap) {
  45379. frameCountInThisIteration = tempBufferInCap;
  45380. }
  45381. }
  45382. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  45383. if (frameCountOutThisIteration > tempBufferMidCap) {
  45384. frameCountOutThisIteration = tempBufferMidCap;
  45385. }
  45386. /* We can't read more frames than can fit in the output buffer. */
  45387. if (pConverter->hasPostFormatConversion) {
  45388. if (frameCountOutThisIteration > tempBufferOutCap) {
  45389. frameCountOutThisIteration = tempBufferOutCap;
  45390. }
  45391. }
  45392. /* We need to ensure we don't try to process too many input frames that we run out of room in the output buffer. If this happens we'll end up glitching. */
  45393. /*
  45394. We need to try to predict how many input frames will be required for the resampler. If the
  45395. resampler can tell us, we'll use that. Otherwise we'll need to make a best guess. The further
  45396. off we are from this, the more wasted format conversions we'll end up doing.
  45397. */
  45398. #if 1
  45399. {
  45400. ma_uint64 requiredInputFrameCount;
  45401. result = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration, &requiredInputFrameCount);
  45402. if (result != MA_SUCCESS) {
  45403. /* Fall back to a best guess. */
  45404. requiredInputFrameCount = (frameCountOutThisIteration * pConverter->resampler.sampleRateIn) / pConverter->resampler.sampleRateOut;
  45405. }
  45406. if (frameCountInThisIteration > requiredInputFrameCount) {
  45407. frameCountInThisIteration = requiredInputFrameCount;
  45408. }
  45409. }
  45410. #endif
  45411. if (pConverter->hasPreFormatConversion) {
  45412. if (pFramesIn != NULL) {
  45413. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.format, pRunningFramesIn, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  45414. pResampleBufferIn = pTempBufferIn;
  45415. } else {
  45416. pResampleBufferIn = NULL;
  45417. }
  45418. } else {
  45419. pResampleBufferIn = pRunningFramesIn;
  45420. }
  45421. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pResampleBufferIn, &frameCountInThisIteration, pTempBufferMid, &frameCountOutThisIteration);
  45422. if (result != MA_SUCCESS) {
  45423. return result;
  45424. }
  45425. /*
  45426. The input data has been resampled so now we need to run it through the channel converter. The input data is always contained in pTempBufferMid. We only need to do
  45427. this part if we have an output buffer.
  45428. */
  45429. if (pFramesOut != NULL) {
  45430. if (pConverter->hasPostFormatConversion) {
  45431. pChannelsBufferOut = pTempBufferOut;
  45432. } else {
  45433. pChannelsBufferOut = pRunningFramesOut;
  45434. }
  45435. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pChannelsBufferOut, pTempBufferMid, frameCountOutThisIteration);
  45436. if (result != MA_SUCCESS) {
  45437. return result;
  45438. }
  45439. /* Finally we do post format conversion. */
  45440. if (pConverter->hasPostFormatConversion) {
  45441. ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->formatOut, pChannelsBufferOut, pConverter->channelConverter.format, frameCountOutThisIteration, pConverter->channelConverter.channelsOut, pConverter->ditherMode);
  45442. }
  45443. }
  45444. framesProcessedIn += frameCountInThisIteration;
  45445. framesProcessedOut += frameCountOutThisIteration;
  45446. MA_ASSERT(framesProcessedIn <= frameCountIn);
  45447. MA_ASSERT(framesProcessedOut <= frameCountOut);
  45448. if (frameCountOutThisIteration == 0) {
  45449. break; /* Consumed all of our input data. */
  45450. }
  45451. }
  45452. if (pFrameCountIn != NULL) {
  45453. *pFrameCountIn = framesProcessedIn;
  45454. }
  45455. if (pFrameCountOut != NULL) {
  45456. *pFrameCountOut = framesProcessedOut;
  45457. }
  45458. return MA_SUCCESS;
  45459. }
  45460. static ma_result ma_data_converter_process_pcm_frames__channels_first(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  45461. {
  45462. ma_result result;
  45463. ma_uint64 frameCountIn;
  45464. ma_uint64 frameCountOut;
  45465. ma_uint64 framesProcessedIn;
  45466. ma_uint64 framesProcessedOut;
  45467. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */
  45468. ma_uint64 tempBufferInCap;
  45469. ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */
  45470. ma_uint64 tempBufferMidCap;
  45471. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */
  45472. ma_uint64 tempBufferOutCap;
  45473. MA_ASSERT(pConverter != NULL);
  45474. MA_ASSERT(pConverter->resampler.format == pConverter->channelConverter.format);
  45475. MA_ASSERT(pConverter->resampler.channels == pConverter->channelConverter.channelsOut);
  45476. MA_ASSERT(pConverter->resampler.channels <= pConverter->channelConverter.channelsIn);
  45477. frameCountIn = 0;
  45478. if (pFrameCountIn != NULL) {
  45479. frameCountIn = *pFrameCountIn;
  45480. }
  45481. frameCountOut = 0;
  45482. if (pFrameCountOut != NULL) {
  45483. frameCountOut = *pFrameCountOut;
  45484. }
  45485. framesProcessedIn = 0;
  45486. framesProcessedOut = 0;
  45487. tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn);
  45488. tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
  45489. tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45490. while (framesProcessedOut < frameCountOut) {
  45491. ma_uint64 frameCountInThisIteration;
  45492. ma_uint64 frameCountOutThisIteration;
  45493. const void* pRunningFramesIn = NULL;
  45494. void* pRunningFramesOut = NULL;
  45495. const void* pChannelsBufferIn;
  45496. void* pResampleBufferOut;
  45497. if (pFramesIn != NULL) {
  45498. pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  45499. }
  45500. if (pFramesOut != NULL) {
  45501. pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45502. }
  45503. /*
  45504. Before doing any processing we need to determine how many frames we should try processing
  45505. this iteration, for both input and output. The resampler requires us to perform format and
  45506. channel conversion before passing any data into it. If we get our input count wrong, we'll
  45507. end up peforming redundant pre-processing. This isn't the end of the world, but it does
  45508. result in some inefficiencies proportionate to how far our estimates are off.
  45509. If the resampler has a means to calculate exactly how much we'll need, we'll use that.
  45510. Otherwise we'll make a best guess. In order to do this, we'll need to calculate the output
  45511. frame count first.
  45512. */
  45513. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  45514. if (frameCountOutThisIteration > tempBufferMidCap) {
  45515. frameCountOutThisIteration = tempBufferMidCap;
  45516. }
  45517. if (pConverter->hasPostFormatConversion) {
  45518. if (frameCountOutThisIteration > tempBufferOutCap) {
  45519. frameCountOutThisIteration = tempBufferOutCap;
  45520. }
  45521. }
  45522. /* Now that we have the output frame count we can determine the input frame count. */
  45523. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  45524. if (pConverter->hasPreFormatConversion) {
  45525. if (frameCountInThisIteration > tempBufferInCap) {
  45526. frameCountInThisIteration = tempBufferInCap;
  45527. }
  45528. }
  45529. if (frameCountInThisIteration > tempBufferMidCap) {
  45530. frameCountInThisIteration = tempBufferMidCap;
  45531. }
  45532. #if 1
  45533. {
  45534. ma_uint64 requiredInputFrameCount;
  45535. result = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration, &requiredInputFrameCount);
  45536. if (result != MA_SUCCESS) {
  45537. /* Fall back to a best guess. */
  45538. requiredInputFrameCount = (frameCountOutThisIteration * pConverter->resampler.sampleRateIn) / pConverter->resampler.sampleRateOut;
  45539. }
  45540. if (frameCountInThisIteration > requiredInputFrameCount) {
  45541. frameCountInThisIteration = requiredInputFrameCount;
  45542. }
  45543. }
  45544. #endif
  45545. /* Pre format conversion. */
  45546. if (pConverter->hasPreFormatConversion) {
  45547. if (pRunningFramesIn != NULL) {
  45548. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pRunningFramesIn, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  45549. pChannelsBufferIn = pTempBufferIn;
  45550. } else {
  45551. pChannelsBufferIn = NULL;
  45552. }
  45553. } else {
  45554. pChannelsBufferIn = pRunningFramesIn;
  45555. }
  45556. /* Channel conversion. */
  45557. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferMid, pChannelsBufferIn, frameCountInThisIteration);
  45558. if (result != MA_SUCCESS) {
  45559. return result;
  45560. }
  45561. /* Resampling. */
  45562. if (pConverter->hasPostFormatConversion) {
  45563. pResampleBufferOut = pTempBufferOut;
  45564. } else {
  45565. pResampleBufferOut = pRunningFramesOut;
  45566. }
  45567. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferMid, &frameCountInThisIteration, pResampleBufferOut, &frameCountOutThisIteration);
  45568. if (result != MA_SUCCESS) {
  45569. return result;
  45570. }
  45571. /* Post format conversion. */
  45572. if (pConverter->hasPostFormatConversion) {
  45573. if (pRunningFramesOut != NULL) {
  45574. ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->formatOut, pResampleBufferOut, pConverter->resampler.format, frameCountOutThisIteration, pConverter->channelsOut, pConverter->ditherMode);
  45575. }
  45576. }
  45577. framesProcessedIn += frameCountInThisIteration;
  45578. framesProcessedOut += frameCountOutThisIteration;
  45579. MA_ASSERT(framesProcessedIn <= frameCountIn);
  45580. MA_ASSERT(framesProcessedOut <= frameCountOut);
  45581. if (frameCountOutThisIteration == 0) {
  45582. break; /* Consumed all of our input data. */
  45583. }
  45584. }
  45585. if (pFrameCountIn != NULL) {
  45586. *pFrameCountIn = framesProcessedIn;
  45587. }
  45588. if (pFrameCountOut != NULL) {
  45589. *pFrameCountOut = framesProcessedOut;
  45590. }
  45591. return MA_SUCCESS;
  45592. }
  45593. MA_API ma_result ma_data_converter_process_pcm_frames(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  45594. {
  45595. if (pConverter == NULL) {
  45596. return MA_INVALID_ARGS;
  45597. }
  45598. switch (pConverter->executionPath)
  45599. {
  45600. case ma_data_converter_execution_path_passthrough: return ma_data_converter_process_pcm_frames__passthrough(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45601. case ma_data_converter_execution_path_format_only: return ma_data_converter_process_pcm_frames__format_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45602. case ma_data_converter_execution_path_channels_only: return ma_data_converter_process_pcm_frames__channels_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45603. case ma_data_converter_execution_path_resample_only: return ma_data_converter_process_pcm_frames__resample_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45604. case ma_data_converter_execution_path_resample_first: return ma_data_converter_process_pcm_frames__resample_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45605. case ma_data_converter_execution_path_channels_first: return ma_data_converter_process_pcm_frames__channels_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45606. default: return MA_INVALID_OPERATION; /* Should never hit this. */
  45607. }
  45608. }
  45609. MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  45610. {
  45611. if (pConverter == NULL) {
  45612. return MA_INVALID_ARGS;
  45613. }
  45614. if (pConverter->hasResampler == MA_FALSE) {
  45615. return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */
  45616. }
  45617. return ma_resampler_set_rate(&pConverter->resampler, sampleRateIn, sampleRateOut);
  45618. }
  45619. MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut)
  45620. {
  45621. if (pConverter == NULL) {
  45622. return MA_INVALID_ARGS;
  45623. }
  45624. if (pConverter->hasResampler == MA_FALSE) {
  45625. return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */
  45626. }
  45627. return ma_resampler_set_rate_ratio(&pConverter->resampler, ratioInOut);
  45628. }
  45629. MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter)
  45630. {
  45631. if (pConverter == NULL) {
  45632. return 0;
  45633. }
  45634. if (pConverter->hasResampler) {
  45635. return ma_resampler_get_input_latency(&pConverter->resampler);
  45636. }
  45637. return 0; /* No latency without a resampler. */
  45638. }
  45639. MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter)
  45640. {
  45641. if (pConverter == NULL) {
  45642. return 0;
  45643. }
  45644. if (pConverter->hasResampler) {
  45645. return ma_resampler_get_output_latency(&pConverter->resampler);
  45646. }
  45647. return 0; /* No latency without a resampler. */
  45648. }
  45649. MA_API ma_result ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  45650. {
  45651. if (pInputFrameCount == NULL) {
  45652. return MA_INVALID_ARGS;
  45653. }
  45654. *pInputFrameCount = 0;
  45655. if (pConverter == NULL) {
  45656. return MA_INVALID_ARGS;
  45657. }
  45658. if (pConverter->hasResampler) {
  45659. return ma_resampler_get_required_input_frame_count(&pConverter->resampler, outputFrameCount, pInputFrameCount);
  45660. } else {
  45661. *pInputFrameCount = outputFrameCount; /* 1:1 */
  45662. return MA_SUCCESS;
  45663. }
  45664. }
  45665. MA_API ma_result ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  45666. {
  45667. if (pOutputFrameCount == NULL) {
  45668. return MA_INVALID_ARGS;
  45669. }
  45670. *pOutputFrameCount = 0;
  45671. if (pConverter == NULL) {
  45672. return MA_INVALID_ARGS;
  45673. }
  45674. if (pConverter->hasResampler) {
  45675. return ma_resampler_get_expected_output_frame_count(&pConverter->resampler, inputFrameCount, pOutputFrameCount);
  45676. } else {
  45677. *pOutputFrameCount = inputFrameCount; /* 1:1 */
  45678. return MA_SUCCESS;
  45679. }
  45680. }
  45681. MA_API ma_result ma_data_converter_get_input_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  45682. {
  45683. if (pConverter == NULL || pChannelMap == NULL) {
  45684. return MA_INVALID_ARGS;
  45685. }
  45686. if (pConverter->hasChannelConverter) {
  45687. ma_channel_converter_get_output_channel_map(&pConverter->channelConverter, pChannelMap, channelMapCap);
  45688. } else {
  45689. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pConverter->channelsOut);
  45690. }
  45691. return MA_SUCCESS;
  45692. }
  45693. MA_API ma_result ma_data_converter_get_output_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  45694. {
  45695. if (pConverter == NULL || pChannelMap == NULL) {
  45696. return MA_INVALID_ARGS;
  45697. }
  45698. if (pConverter->hasChannelConverter) {
  45699. ma_channel_converter_get_input_channel_map(&pConverter->channelConverter, pChannelMap, channelMapCap);
  45700. } else {
  45701. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pConverter->channelsIn);
  45702. }
  45703. return MA_SUCCESS;
  45704. }
  45705. MA_API ma_result ma_data_converter_reset(ma_data_converter* pConverter)
  45706. {
  45707. if (pConverter == NULL) {
  45708. return MA_INVALID_ARGS;
  45709. }
  45710. /* There's nothing to do if we're not resampling. */
  45711. if (pConverter->hasResampler == MA_FALSE) {
  45712. return MA_SUCCESS;
  45713. }
  45714. return ma_resampler_reset(&pConverter->resampler);
  45715. }
  45716. /**************************************************************************************************************************************************************
  45717. Channel Maps
  45718. **************************************************************************************************************************************************************/
  45719. static ma_channel ma_channel_map_init_standard_channel(ma_standard_channel_map standardChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex);
  45720. MA_API ma_channel ma_channel_map_get_channel(const ma_channel* pChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex)
  45721. {
  45722. if (pChannelMap == NULL) {
  45723. return ma_channel_map_init_standard_channel(ma_standard_channel_map_default, channelCount, channelIndex);
  45724. } else {
  45725. if (channelIndex >= channelCount) {
  45726. return MA_CHANNEL_NONE;
  45727. }
  45728. return pChannelMap[channelIndex];
  45729. }
  45730. }
  45731. MA_API void ma_channel_map_init_blank(ma_channel* pChannelMap, ma_uint32 channels)
  45732. {
  45733. if (pChannelMap == NULL) {
  45734. return;
  45735. }
  45736. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channels);
  45737. }
  45738. static ma_channel ma_channel_map_init_standard_channel_microsoft(ma_uint32 channelCount, ma_uint32 channelIndex)
  45739. {
  45740. if (channelCount == 0 || channelIndex >= channelCount) {
  45741. return MA_CHANNEL_NONE;
  45742. }
  45743. /* This is the Microsoft channel map. Based off the speaker configurations mentioned here: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ksmedia/ns-ksmedia-ksaudio_channel_config */
  45744. switch (channelCount)
  45745. {
  45746. case 0: return MA_CHANNEL_NONE;
  45747. case 1:
  45748. {
  45749. return MA_CHANNEL_MONO;
  45750. } break;
  45751. case 2:
  45752. {
  45753. switch (channelIndex) {
  45754. case 0: return MA_CHANNEL_FRONT_LEFT;
  45755. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45756. }
  45757. } break;
  45758. case 3: /* No defined, but best guess. */
  45759. {
  45760. switch (channelIndex) {
  45761. case 0: return MA_CHANNEL_FRONT_LEFT;
  45762. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45763. case 2: return MA_CHANNEL_FRONT_CENTER;
  45764. }
  45765. } break;
  45766. case 4:
  45767. {
  45768. switch (channelIndex) {
  45769. #ifndef MA_USE_QUAD_MICROSOFT_CHANNEL_MAP
  45770. /* Surround. Using the Surround profile has the advantage of the 3rd channel (MA_CHANNEL_FRONT_CENTER) mapping nicely with higher channel counts. */
  45771. case 0: return MA_CHANNEL_FRONT_LEFT;
  45772. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45773. case 2: return MA_CHANNEL_FRONT_CENTER;
  45774. case 3: return MA_CHANNEL_BACK_CENTER;
  45775. #else
  45776. /* Quad. */
  45777. case 0: return MA_CHANNEL_FRONT_LEFT;
  45778. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45779. case 2: return MA_CHANNEL_BACK_LEFT;
  45780. case 3: return MA_CHANNEL_BACK_RIGHT;
  45781. #endif
  45782. }
  45783. } break;
  45784. case 5: /* Not defined, but best guess. */
  45785. {
  45786. switch (channelIndex) {
  45787. case 0: return MA_CHANNEL_FRONT_LEFT;
  45788. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45789. case 2: return MA_CHANNEL_FRONT_CENTER;
  45790. case 3: return MA_CHANNEL_BACK_LEFT;
  45791. case 4: return MA_CHANNEL_BACK_RIGHT;
  45792. }
  45793. } break;
  45794. case 6:
  45795. {
  45796. switch (channelIndex) {
  45797. case 0: return MA_CHANNEL_FRONT_LEFT;
  45798. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45799. case 2: return MA_CHANNEL_FRONT_CENTER;
  45800. case 3: return MA_CHANNEL_LFE;
  45801. case 4: return MA_CHANNEL_SIDE_LEFT;
  45802. case 5: return MA_CHANNEL_SIDE_RIGHT;
  45803. }
  45804. } break;
  45805. case 7: /* Not defined, but best guess. */
  45806. {
  45807. switch (channelIndex) {
  45808. case 0: return MA_CHANNEL_FRONT_LEFT;
  45809. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45810. case 2: return MA_CHANNEL_FRONT_CENTER;
  45811. case 3: return MA_CHANNEL_LFE;
  45812. case 4: return MA_CHANNEL_BACK_CENTER;
  45813. case 5: return MA_CHANNEL_SIDE_LEFT;
  45814. case 6: return MA_CHANNEL_SIDE_RIGHT;
  45815. }
  45816. } break;
  45817. case 8:
  45818. default:
  45819. {
  45820. switch (channelIndex) {
  45821. case 0: return MA_CHANNEL_FRONT_LEFT;
  45822. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45823. case 2: return MA_CHANNEL_FRONT_CENTER;
  45824. case 3: return MA_CHANNEL_LFE;
  45825. case 4: return MA_CHANNEL_BACK_LEFT;
  45826. case 5: return MA_CHANNEL_BACK_RIGHT;
  45827. case 6: return MA_CHANNEL_SIDE_LEFT;
  45828. case 7: return MA_CHANNEL_SIDE_RIGHT;
  45829. }
  45830. } break;
  45831. }
  45832. if (channelCount > 8) {
  45833. if (channelIndex < 32) { /* We have 32 AUX channels. */
  45834. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  45835. }
  45836. }
  45837. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  45838. return MA_CHANNEL_NONE;
  45839. }
  45840. static ma_channel ma_channel_map_init_standard_channel_alsa(ma_uint32 channelCount, ma_uint32 channelIndex)
  45841. {
  45842. switch (channelCount)
  45843. {
  45844. case 0: return MA_CHANNEL_NONE;
  45845. case 1:
  45846. {
  45847. return MA_CHANNEL_MONO;
  45848. } break;
  45849. case 2:
  45850. {
  45851. switch (channelIndex) {
  45852. case 0: return MA_CHANNEL_FRONT_LEFT;
  45853. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45854. }
  45855. } break;
  45856. case 3:
  45857. {
  45858. switch (channelIndex) {
  45859. case 0: return MA_CHANNEL_FRONT_LEFT;
  45860. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45861. case 2: return MA_CHANNEL_FRONT_CENTER;
  45862. }
  45863. } break;
  45864. case 4:
  45865. {
  45866. switch (channelIndex) {
  45867. case 0: return MA_CHANNEL_FRONT_LEFT;
  45868. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45869. case 2: return MA_CHANNEL_BACK_LEFT;
  45870. case 3: return MA_CHANNEL_BACK_RIGHT;
  45871. }
  45872. } break;
  45873. case 5:
  45874. {
  45875. switch (channelIndex) {
  45876. case 0: return MA_CHANNEL_FRONT_LEFT;
  45877. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45878. case 2: return MA_CHANNEL_BACK_LEFT;
  45879. case 3: return MA_CHANNEL_BACK_RIGHT;
  45880. case 4: return MA_CHANNEL_FRONT_CENTER;
  45881. }
  45882. } break;
  45883. case 6:
  45884. {
  45885. switch (channelIndex) {
  45886. case 0: return MA_CHANNEL_FRONT_LEFT;
  45887. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45888. case 2: return MA_CHANNEL_BACK_LEFT;
  45889. case 3: return MA_CHANNEL_BACK_RIGHT;
  45890. case 4: return MA_CHANNEL_FRONT_CENTER;
  45891. case 5: return MA_CHANNEL_LFE;
  45892. }
  45893. } break;
  45894. case 7:
  45895. {
  45896. switch (channelIndex) {
  45897. case 0: return MA_CHANNEL_FRONT_LEFT;
  45898. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45899. case 2: return MA_CHANNEL_BACK_LEFT;
  45900. case 3: return MA_CHANNEL_BACK_RIGHT;
  45901. case 4: return MA_CHANNEL_FRONT_CENTER;
  45902. case 5: return MA_CHANNEL_LFE;
  45903. case 6: return MA_CHANNEL_BACK_CENTER;
  45904. }
  45905. } break;
  45906. case 8:
  45907. default:
  45908. {
  45909. switch (channelIndex) {
  45910. case 0: return MA_CHANNEL_FRONT_LEFT;
  45911. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45912. case 2: return MA_CHANNEL_BACK_LEFT;
  45913. case 3: return MA_CHANNEL_BACK_RIGHT;
  45914. case 4: return MA_CHANNEL_FRONT_CENTER;
  45915. case 5: return MA_CHANNEL_LFE;
  45916. case 6: return MA_CHANNEL_SIDE_LEFT;
  45917. case 7: return MA_CHANNEL_SIDE_RIGHT;
  45918. }
  45919. } break;
  45920. }
  45921. if (channelCount > 8) {
  45922. if (channelIndex < 32) { /* We have 32 AUX channels. */
  45923. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  45924. }
  45925. }
  45926. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  45927. return MA_CHANNEL_NONE;
  45928. }
  45929. static ma_channel ma_channel_map_init_standard_channel_rfc3551(ma_uint32 channelCount, ma_uint32 channelIndex)
  45930. {
  45931. switch (channelCount)
  45932. {
  45933. case 0: return MA_CHANNEL_NONE;
  45934. case 1:
  45935. {
  45936. return MA_CHANNEL_MONO;
  45937. } break;
  45938. case 2:
  45939. {
  45940. switch (channelIndex) {
  45941. case 0: return MA_CHANNEL_FRONT_LEFT;
  45942. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45943. }
  45944. } break;
  45945. case 3:
  45946. {
  45947. switch (channelIndex) {
  45948. case 0: return MA_CHANNEL_FRONT_LEFT;
  45949. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45950. case 2: return MA_CHANNEL_FRONT_CENTER;
  45951. }
  45952. } break;
  45953. case 4:
  45954. {
  45955. switch (channelIndex) {
  45956. case 0: return MA_CHANNEL_FRONT_LEFT;
  45957. case 2: return MA_CHANNEL_FRONT_CENTER;
  45958. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45959. case 3: return MA_CHANNEL_BACK_CENTER;
  45960. }
  45961. } break;
  45962. case 5:
  45963. {
  45964. switch (channelIndex) {
  45965. case 0: return MA_CHANNEL_FRONT_LEFT;
  45966. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45967. case 2: return MA_CHANNEL_FRONT_CENTER;
  45968. case 3: return MA_CHANNEL_BACK_LEFT;
  45969. case 4: return MA_CHANNEL_BACK_RIGHT;
  45970. }
  45971. } break;
  45972. case 6:
  45973. default:
  45974. {
  45975. switch (channelIndex) {
  45976. case 0: return MA_CHANNEL_FRONT_LEFT;
  45977. case 1: return MA_CHANNEL_SIDE_LEFT;
  45978. case 2: return MA_CHANNEL_FRONT_CENTER;
  45979. case 3: return MA_CHANNEL_FRONT_RIGHT;
  45980. case 4: return MA_CHANNEL_SIDE_RIGHT;
  45981. case 5: return MA_CHANNEL_BACK_CENTER;
  45982. }
  45983. } break;
  45984. }
  45985. if (channelCount > 6) {
  45986. if (channelIndex < 32) { /* We have 32 AUX channels. */
  45987. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 6));
  45988. }
  45989. }
  45990. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  45991. return MA_CHANNEL_NONE;
  45992. }
  45993. static ma_channel ma_channel_map_init_standard_channel_flac(ma_uint32 channelCount, ma_uint32 channelIndex)
  45994. {
  45995. switch (channelCount)
  45996. {
  45997. case 0: return MA_CHANNEL_NONE;
  45998. case 1:
  45999. {
  46000. return MA_CHANNEL_MONO;
  46001. } break;
  46002. case 2:
  46003. {
  46004. switch (channelIndex) {
  46005. case 0: return MA_CHANNEL_FRONT_LEFT;
  46006. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46007. }
  46008. } break;
  46009. case 3:
  46010. {
  46011. switch (channelIndex) {
  46012. case 0: return MA_CHANNEL_FRONT_LEFT;
  46013. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46014. case 2: return MA_CHANNEL_FRONT_CENTER;
  46015. }
  46016. } break;
  46017. case 4:
  46018. {
  46019. switch (channelIndex) {
  46020. case 0: return MA_CHANNEL_FRONT_LEFT;
  46021. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46022. case 2: return MA_CHANNEL_BACK_LEFT;
  46023. case 3: return MA_CHANNEL_BACK_RIGHT;
  46024. }
  46025. } break;
  46026. case 5:
  46027. {
  46028. switch (channelIndex) {
  46029. case 0: return MA_CHANNEL_FRONT_LEFT;
  46030. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46031. case 2: return MA_CHANNEL_FRONT_CENTER;
  46032. case 3: return MA_CHANNEL_BACK_LEFT;
  46033. case 4: return MA_CHANNEL_BACK_RIGHT;
  46034. }
  46035. } break;
  46036. case 6:
  46037. {
  46038. switch (channelIndex) {
  46039. case 0: return MA_CHANNEL_FRONT_LEFT;
  46040. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46041. case 2: return MA_CHANNEL_FRONT_CENTER;
  46042. case 3: return MA_CHANNEL_LFE;
  46043. case 4: return MA_CHANNEL_BACK_LEFT;
  46044. case 5: return MA_CHANNEL_BACK_RIGHT;
  46045. }
  46046. } break;
  46047. case 7:
  46048. {
  46049. switch (channelIndex) {
  46050. case 0: return MA_CHANNEL_FRONT_LEFT;
  46051. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46052. case 2: return MA_CHANNEL_FRONT_CENTER;
  46053. case 3: return MA_CHANNEL_LFE;
  46054. case 4: return MA_CHANNEL_BACK_CENTER;
  46055. case 5: return MA_CHANNEL_SIDE_LEFT;
  46056. case 6: return MA_CHANNEL_SIDE_RIGHT;
  46057. }
  46058. } break;
  46059. case 8:
  46060. default:
  46061. {
  46062. switch (channelIndex) {
  46063. case 0: return MA_CHANNEL_FRONT_LEFT;
  46064. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46065. case 2: return MA_CHANNEL_FRONT_CENTER;
  46066. case 3: return MA_CHANNEL_LFE;
  46067. case 4: return MA_CHANNEL_BACK_LEFT;
  46068. case 5: return MA_CHANNEL_BACK_RIGHT;
  46069. case 6: return MA_CHANNEL_SIDE_LEFT;
  46070. case 7: return MA_CHANNEL_SIDE_RIGHT;
  46071. }
  46072. } break;
  46073. }
  46074. if (channelCount > 8) {
  46075. if (channelIndex < 32) { /* We have 32 AUX channels. */
  46076. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  46077. }
  46078. }
  46079. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  46080. return MA_CHANNEL_NONE;
  46081. }
  46082. static ma_channel ma_channel_map_init_standard_channel_vorbis(ma_uint32 channelCount, ma_uint32 channelIndex)
  46083. {
  46084. switch (channelCount)
  46085. {
  46086. case 0: return MA_CHANNEL_NONE;
  46087. case 1:
  46088. {
  46089. return MA_CHANNEL_MONO;
  46090. } break;
  46091. case 2:
  46092. {
  46093. switch (channelIndex) {
  46094. case 0: return MA_CHANNEL_FRONT_LEFT;
  46095. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46096. }
  46097. } break;
  46098. case 3:
  46099. {
  46100. switch (channelIndex) {
  46101. case 0: return MA_CHANNEL_FRONT_LEFT;
  46102. case 1: return MA_CHANNEL_FRONT_CENTER;
  46103. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46104. }
  46105. } break;
  46106. case 4:
  46107. {
  46108. switch (channelIndex) {
  46109. case 0: return MA_CHANNEL_FRONT_LEFT;
  46110. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46111. case 2: return MA_CHANNEL_BACK_LEFT;
  46112. case 3: return MA_CHANNEL_BACK_RIGHT;
  46113. }
  46114. } break;
  46115. case 5:
  46116. {
  46117. switch (channelIndex) {
  46118. case 0: return MA_CHANNEL_FRONT_LEFT;
  46119. case 1: return MA_CHANNEL_FRONT_CENTER;
  46120. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46121. case 3: return MA_CHANNEL_BACK_LEFT;
  46122. case 4: return MA_CHANNEL_BACK_RIGHT;
  46123. }
  46124. } break;
  46125. case 6:
  46126. {
  46127. switch (channelIndex) {
  46128. case 0: return MA_CHANNEL_FRONT_LEFT;
  46129. case 1: return MA_CHANNEL_FRONT_CENTER;
  46130. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46131. case 3: return MA_CHANNEL_BACK_LEFT;
  46132. case 4: return MA_CHANNEL_BACK_RIGHT;
  46133. case 5: return MA_CHANNEL_LFE;
  46134. }
  46135. } break;
  46136. case 7:
  46137. {
  46138. switch (channelIndex) {
  46139. case 0: return MA_CHANNEL_FRONT_LEFT;
  46140. case 1: return MA_CHANNEL_FRONT_CENTER;
  46141. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46142. case 3: return MA_CHANNEL_SIDE_LEFT;
  46143. case 4: return MA_CHANNEL_SIDE_RIGHT;
  46144. case 5: return MA_CHANNEL_BACK_CENTER;
  46145. case 6: return MA_CHANNEL_LFE;
  46146. }
  46147. } break;
  46148. case 8:
  46149. default:
  46150. {
  46151. switch (channelIndex) {
  46152. case 0: return MA_CHANNEL_FRONT_LEFT;
  46153. case 1: return MA_CHANNEL_FRONT_CENTER;
  46154. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46155. case 3: return MA_CHANNEL_SIDE_LEFT;
  46156. case 4: return MA_CHANNEL_SIDE_RIGHT;
  46157. case 5: return MA_CHANNEL_BACK_LEFT;
  46158. case 6: return MA_CHANNEL_BACK_RIGHT;
  46159. case 7: return MA_CHANNEL_LFE;
  46160. }
  46161. } break;
  46162. }
  46163. if (channelCount > 8) {
  46164. if (channelIndex < 32) { /* We have 32 AUX channels. */
  46165. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  46166. }
  46167. }
  46168. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  46169. return MA_CHANNEL_NONE;
  46170. }
  46171. static ma_channel ma_channel_map_init_standard_channel_sound4(ma_uint32 channelCount, ma_uint32 channelIndex)
  46172. {
  46173. switch (channelCount)
  46174. {
  46175. case 0: return MA_CHANNEL_NONE;
  46176. case 1:
  46177. {
  46178. return MA_CHANNEL_MONO;
  46179. } break;
  46180. case 2:
  46181. {
  46182. switch (channelIndex) {
  46183. case 0: return MA_CHANNEL_FRONT_LEFT;
  46184. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46185. }
  46186. } break;
  46187. case 3:
  46188. {
  46189. switch (channelIndex) {
  46190. case 0: return MA_CHANNEL_FRONT_LEFT;
  46191. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46192. case 2: return MA_CHANNEL_FRONT_CENTER;
  46193. }
  46194. } break;
  46195. case 4:
  46196. {
  46197. switch (channelIndex) {
  46198. case 0: return MA_CHANNEL_FRONT_LEFT;
  46199. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46200. case 2: return MA_CHANNEL_BACK_LEFT;
  46201. case 3: return MA_CHANNEL_BACK_RIGHT;
  46202. }
  46203. } break;
  46204. case 5:
  46205. {
  46206. switch (channelIndex) {
  46207. case 0: return MA_CHANNEL_FRONT_LEFT;
  46208. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46209. case 2: return MA_CHANNEL_FRONT_CENTER;
  46210. case 3: return MA_CHANNEL_BACK_LEFT;
  46211. case 4: return MA_CHANNEL_BACK_RIGHT;
  46212. }
  46213. } break;
  46214. case 6:
  46215. {
  46216. switch (channelIndex) {
  46217. case 0: return MA_CHANNEL_FRONT_LEFT;
  46218. case 1: return MA_CHANNEL_FRONT_CENTER;
  46219. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46220. case 3: return MA_CHANNEL_BACK_LEFT;
  46221. case 4: return MA_CHANNEL_BACK_RIGHT;
  46222. case 5: return MA_CHANNEL_LFE;
  46223. }
  46224. } break;
  46225. case 7:
  46226. {
  46227. switch (channelIndex) {
  46228. case 0: return MA_CHANNEL_FRONT_LEFT;
  46229. case 1: return MA_CHANNEL_FRONT_CENTER;
  46230. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46231. case 3: return MA_CHANNEL_SIDE_LEFT;
  46232. case 4: return MA_CHANNEL_SIDE_RIGHT;
  46233. case 5: return MA_CHANNEL_BACK_CENTER;
  46234. case 6: return MA_CHANNEL_LFE;
  46235. }
  46236. } break;
  46237. case 8:
  46238. default:
  46239. {
  46240. switch (channelIndex) {
  46241. case 0: return MA_CHANNEL_FRONT_LEFT;
  46242. case 1: return MA_CHANNEL_FRONT_CENTER;
  46243. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46244. case 3: return MA_CHANNEL_SIDE_LEFT;
  46245. case 4: return MA_CHANNEL_SIDE_RIGHT;
  46246. case 5: return MA_CHANNEL_BACK_LEFT;
  46247. case 6: return MA_CHANNEL_BACK_RIGHT;
  46248. case 7: return MA_CHANNEL_LFE;
  46249. }
  46250. } break;
  46251. }
  46252. if (channelCount > 8) {
  46253. if (channelIndex < 32) { /* We have 32 AUX channels. */
  46254. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  46255. }
  46256. }
  46257. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  46258. return MA_CHANNEL_NONE;
  46259. }
  46260. static ma_channel ma_channel_map_init_standard_channel_sndio(ma_uint32 channelCount, ma_uint32 channelIndex)
  46261. {
  46262. switch (channelCount)
  46263. {
  46264. case 0: return MA_CHANNEL_NONE;
  46265. case 1:
  46266. {
  46267. return MA_CHANNEL_MONO;
  46268. } break;
  46269. case 2:
  46270. {
  46271. switch (channelIndex) {
  46272. case 0: return MA_CHANNEL_FRONT_LEFT;
  46273. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46274. }
  46275. } break;
  46276. case 3: /* No defined, but best guess. */
  46277. {
  46278. switch (channelIndex) {
  46279. case 0: return MA_CHANNEL_FRONT_LEFT;
  46280. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46281. case 2: return MA_CHANNEL_FRONT_CENTER;
  46282. }
  46283. } break;
  46284. case 4:
  46285. {
  46286. switch (channelIndex) {
  46287. case 0: return MA_CHANNEL_FRONT_LEFT;
  46288. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46289. case 2: return MA_CHANNEL_BACK_LEFT;
  46290. case 3: return MA_CHANNEL_BACK_RIGHT;
  46291. }
  46292. } break;
  46293. case 5: /* Not defined, but best guess. */
  46294. {
  46295. switch (channelIndex) {
  46296. case 0: return MA_CHANNEL_FRONT_LEFT;
  46297. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46298. case 2: return MA_CHANNEL_BACK_LEFT;
  46299. case 3: return MA_CHANNEL_BACK_RIGHT;
  46300. case 4: return MA_CHANNEL_FRONT_CENTER;
  46301. }
  46302. } break;
  46303. case 6:
  46304. default:
  46305. {
  46306. switch (channelIndex) {
  46307. case 0: return MA_CHANNEL_FRONT_LEFT;
  46308. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46309. case 2: return MA_CHANNEL_BACK_LEFT;
  46310. case 3: return MA_CHANNEL_BACK_RIGHT;
  46311. case 4: return MA_CHANNEL_FRONT_CENTER;
  46312. case 5: return MA_CHANNEL_LFE;
  46313. }
  46314. } break;
  46315. }
  46316. if (channelCount > 6) {
  46317. if (channelIndex < 32) { /* We have 32 AUX channels. */
  46318. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 6));
  46319. }
  46320. }
  46321. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  46322. return MA_CHANNEL_NONE;
  46323. }
  46324. static ma_channel ma_channel_map_init_standard_channel(ma_standard_channel_map standardChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex)
  46325. {
  46326. if (channelCount == 0 || channelIndex >= channelCount) {
  46327. return MA_CHANNEL_NONE;
  46328. }
  46329. switch (standardChannelMap)
  46330. {
  46331. case ma_standard_channel_map_alsa:
  46332. {
  46333. return ma_channel_map_init_standard_channel_alsa(channelCount, channelIndex);
  46334. } break;
  46335. case ma_standard_channel_map_rfc3551:
  46336. {
  46337. return ma_channel_map_init_standard_channel_rfc3551(channelCount, channelIndex);
  46338. } break;
  46339. case ma_standard_channel_map_flac:
  46340. {
  46341. return ma_channel_map_init_standard_channel_flac(channelCount, channelIndex);
  46342. } break;
  46343. case ma_standard_channel_map_vorbis:
  46344. {
  46345. return ma_channel_map_init_standard_channel_vorbis(channelCount, channelIndex);
  46346. } break;
  46347. case ma_standard_channel_map_sound4:
  46348. {
  46349. return ma_channel_map_init_standard_channel_sound4(channelCount, channelIndex);
  46350. } break;
  46351. case ma_standard_channel_map_sndio:
  46352. {
  46353. return ma_channel_map_init_standard_channel_sndio(channelCount, channelIndex);
  46354. } break;
  46355. case ma_standard_channel_map_microsoft: /* Also default. */
  46356. /*case ma_standard_channel_map_default;*/
  46357. default:
  46358. {
  46359. return ma_channel_map_init_standard_channel_microsoft(channelCount, channelIndex);
  46360. } break;
  46361. }
  46362. }
  46363. MA_API void ma_channel_map_init_standard(ma_standard_channel_map standardChannelMap, ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channels)
  46364. {
  46365. ma_uint32 iChannel;
  46366. if (pChannelMap == NULL || channelMapCap == 0 || channels == 0) {
  46367. return;
  46368. }
  46369. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  46370. if (channelMapCap == 0) {
  46371. break; /* Ran out of room. */
  46372. }
  46373. pChannelMap[0] = ma_channel_map_init_standard_channel(standardChannelMap, channels, iChannel);
  46374. pChannelMap += 1;
  46375. channelMapCap -= 1;
  46376. }
  46377. }
  46378. MA_API void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels)
  46379. {
  46380. if (pOut != NULL && pIn != NULL && channels > 0) {
  46381. MA_COPY_MEMORY(pOut, pIn, sizeof(*pOut) * channels);
  46382. }
  46383. }
  46384. MA_API void ma_channel_map_copy_or_default(ma_channel* pOut, size_t channelMapCapOut, const ma_channel* pIn, ma_uint32 channels)
  46385. {
  46386. if (pOut == NULL || channels == 0) {
  46387. return;
  46388. }
  46389. if (pIn != NULL) {
  46390. ma_channel_map_copy(pOut, pIn, channels);
  46391. } else {
  46392. ma_channel_map_init_standard(ma_standard_channel_map_default, pOut, channelMapCapOut, channels);
  46393. }
  46394. }
  46395. MA_API ma_bool32 ma_channel_map_is_valid(const ma_channel* pChannelMap, ma_uint32 channels)
  46396. {
  46397. /* A channel count of 0 is invalid. */
  46398. if (channels == 0) {
  46399. return MA_FALSE;
  46400. }
  46401. /* It does not make sense to have a mono channel when there is more than 1 channel. */
  46402. if (channels > 1) {
  46403. ma_uint32 iChannel;
  46404. for (iChannel = 0; iChannel < channels; ++iChannel) {
  46405. if (ma_channel_map_get_channel(pChannelMap, channels, iChannel) == MA_CHANNEL_MONO) {
  46406. return MA_FALSE;
  46407. }
  46408. }
  46409. }
  46410. return MA_TRUE;
  46411. }
  46412. MA_API ma_bool32 ma_channel_map_is_equal(const ma_channel* pChannelMapA, const ma_channel* pChannelMapB, ma_uint32 channels)
  46413. {
  46414. ma_uint32 iChannel;
  46415. if (pChannelMapA == pChannelMapB) {
  46416. return MA_TRUE;
  46417. }
  46418. for (iChannel = 0; iChannel < channels; ++iChannel) {
  46419. if (ma_channel_map_get_channel(pChannelMapA, channels, iChannel) != ma_channel_map_get_channel(pChannelMapB, channels, iChannel)) {
  46420. return MA_FALSE;
  46421. }
  46422. }
  46423. return MA_TRUE;
  46424. }
  46425. MA_API ma_bool32 ma_channel_map_is_blank(const ma_channel* pChannelMap, ma_uint32 channels)
  46426. {
  46427. ma_uint32 iChannel;
  46428. /* A null channel map is equivalent to the default channel map. */
  46429. if (pChannelMap == NULL) {
  46430. return MA_FALSE;
  46431. }
  46432. for (iChannel = 0; iChannel < channels; ++iChannel) {
  46433. if (pChannelMap[iChannel] != MA_CHANNEL_NONE) {
  46434. return MA_FALSE;
  46435. }
  46436. }
  46437. return MA_TRUE;
  46438. }
  46439. MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition)
  46440. {
  46441. return ma_channel_map_find_channel_position(channels, pChannelMap, channelPosition, NULL);
  46442. }
  46443. MA_API ma_bool32 ma_channel_map_find_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition, ma_uint32* pChannelIndex)
  46444. {
  46445. ma_uint32 iChannel;
  46446. if (pChannelIndex != NULL) {
  46447. *pChannelIndex = (ma_uint32)-1;
  46448. }
  46449. for (iChannel = 0; iChannel < channels; ++iChannel) {
  46450. if (ma_channel_map_get_channel(pChannelMap, channels, iChannel) == channelPosition) {
  46451. if (pChannelIndex != NULL) {
  46452. *pChannelIndex = iChannel;
  46453. }
  46454. return MA_TRUE;
  46455. }
  46456. }
  46457. /* Getting here means the channel position was not found. */
  46458. return MA_FALSE;
  46459. }
  46460. MA_API size_t ma_channel_map_to_string(const ma_channel* pChannelMap, ma_uint32 channels, char* pBufferOut, size_t bufferCap)
  46461. {
  46462. size_t len;
  46463. ma_uint32 iChannel;
  46464. len = 0;
  46465. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  46466. const char* pChannelStr = ma_channel_position_to_string(ma_channel_map_get_channel(pChannelMap, channels, iChannel));
  46467. size_t channelStrLen = strlen(pChannelStr);
  46468. /* Append the string if necessary. */
  46469. if (pBufferOut != NULL && bufferCap > len + channelStrLen) {
  46470. MA_COPY_MEMORY(pBufferOut + len, pChannelStr, channelStrLen);
  46471. }
  46472. len += channelStrLen;
  46473. /* Append a space if it's not the last item. */
  46474. if (iChannel+1 < channels) {
  46475. if (pBufferOut != NULL && bufferCap > len + 1) {
  46476. pBufferOut[len] = ' ';
  46477. }
  46478. len += 1;
  46479. }
  46480. }
  46481. /* Null terminate. Don't increment the length here. */
  46482. if (pBufferOut != NULL && bufferCap > len + 1) {
  46483. pBufferOut[len] = '\0';
  46484. }
  46485. return len;
  46486. }
  46487. MA_API const char* ma_channel_position_to_string(ma_channel channel)
  46488. {
  46489. switch (channel)
  46490. {
  46491. case MA_CHANNEL_NONE : return "CHANNEL_NONE";
  46492. case MA_CHANNEL_MONO : return "CHANNEL_MONO";
  46493. case MA_CHANNEL_FRONT_LEFT : return "CHANNEL_FRONT_LEFT";
  46494. case MA_CHANNEL_FRONT_RIGHT : return "CHANNEL_FRONT_RIGHT";
  46495. case MA_CHANNEL_FRONT_CENTER : return "CHANNEL_FRONT_CENTER";
  46496. case MA_CHANNEL_LFE : return "CHANNEL_LFE";
  46497. case MA_CHANNEL_BACK_LEFT : return "CHANNEL_BACK_LEFT";
  46498. case MA_CHANNEL_BACK_RIGHT : return "CHANNEL_BACK_RIGHT";
  46499. case MA_CHANNEL_FRONT_LEFT_CENTER : return "CHANNEL_FRONT_LEFT_CENTER ";
  46500. case MA_CHANNEL_FRONT_RIGHT_CENTER: return "CHANNEL_FRONT_RIGHT_CENTER";
  46501. case MA_CHANNEL_BACK_CENTER : return "CHANNEL_BACK_CENTER";
  46502. case MA_CHANNEL_SIDE_LEFT : return "CHANNEL_SIDE_LEFT";
  46503. case MA_CHANNEL_SIDE_RIGHT : return "CHANNEL_SIDE_RIGHT";
  46504. case MA_CHANNEL_TOP_CENTER : return "CHANNEL_TOP_CENTER";
  46505. case MA_CHANNEL_TOP_FRONT_LEFT : return "CHANNEL_TOP_FRONT_LEFT";
  46506. case MA_CHANNEL_TOP_FRONT_CENTER : return "CHANNEL_TOP_FRONT_CENTER";
  46507. case MA_CHANNEL_TOP_FRONT_RIGHT : return "CHANNEL_TOP_FRONT_RIGHT";
  46508. case MA_CHANNEL_TOP_BACK_LEFT : return "CHANNEL_TOP_BACK_LEFT";
  46509. case MA_CHANNEL_TOP_BACK_CENTER : return "CHANNEL_TOP_BACK_CENTER";
  46510. case MA_CHANNEL_TOP_BACK_RIGHT : return "CHANNEL_TOP_BACK_RIGHT";
  46511. case MA_CHANNEL_AUX_0 : return "CHANNEL_AUX_0";
  46512. case MA_CHANNEL_AUX_1 : return "CHANNEL_AUX_1";
  46513. case MA_CHANNEL_AUX_2 : return "CHANNEL_AUX_2";
  46514. case MA_CHANNEL_AUX_3 : return "CHANNEL_AUX_3";
  46515. case MA_CHANNEL_AUX_4 : return "CHANNEL_AUX_4";
  46516. case MA_CHANNEL_AUX_5 : return "CHANNEL_AUX_5";
  46517. case MA_CHANNEL_AUX_6 : return "CHANNEL_AUX_6";
  46518. case MA_CHANNEL_AUX_7 : return "CHANNEL_AUX_7";
  46519. case MA_CHANNEL_AUX_8 : return "CHANNEL_AUX_8";
  46520. case MA_CHANNEL_AUX_9 : return "CHANNEL_AUX_9";
  46521. case MA_CHANNEL_AUX_10 : return "CHANNEL_AUX_10";
  46522. case MA_CHANNEL_AUX_11 : return "CHANNEL_AUX_11";
  46523. case MA_CHANNEL_AUX_12 : return "CHANNEL_AUX_12";
  46524. case MA_CHANNEL_AUX_13 : return "CHANNEL_AUX_13";
  46525. case MA_CHANNEL_AUX_14 : return "CHANNEL_AUX_14";
  46526. case MA_CHANNEL_AUX_15 : return "CHANNEL_AUX_15";
  46527. case MA_CHANNEL_AUX_16 : return "CHANNEL_AUX_16";
  46528. case MA_CHANNEL_AUX_17 : return "CHANNEL_AUX_17";
  46529. case MA_CHANNEL_AUX_18 : return "CHANNEL_AUX_18";
  46530. case MA_CHANNEL_AUX_19 : return "CHANNEL_AUX_19";
  46531. case MA_CHANNEL_AUX_20 : return "CHANNEL_AUX_20";
  46532. case MA_CHANNEL_AUX_21 : return "CHANNEL_AUX_21";
  46533. case MA_CHANNEL_AUX_22 : return "CHANNEL_AUX_22";
  46534. case MA_CHANNEL_AUX_23 : return "CHANNEL_AUX_23";
  46535. case MA_CHANNEL_AUX_24 : return "CHANNEL_AUX_24";
  46536. case MA_CHANNEL_AUX_25 : return "CHANNEL_AUX_25";
  46537. case MA_CHANNEL_AUX_26 : return "CHANNEL_AUX_26";
  46538. case MA_CHANNEL_AUX_27 : return "CHANNEL_AUX_27";
  46539. case MA_CHANNEL_AUX_28 : return "CHANNEL_AUX_28";
  46540. case MA_CHANNEL_AUX_29 : return "CHANNEL_AUX_29";
  46541. case MA_CHANNEL_AUX_30 : return "CHANNEL_AUX_30";
  46542. case MA_CHANNEL_AUX_31 : return "CHANNEL_AUX_31";
  46543. default: break;
  46544. }
  46545. return "UNKNOWN";
  46546. }
  46547. /**************************************************************************************************************************************************************
  46548. Conversion Helpers
  46549. **************************************************************************************************************************************************************/
  46550. MA_API ma_uint64 ma_convert_frames(void* pOut, ma_uint64 frameCountOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, const void* pIn, ma_uint64 frameCountIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn)
  46551. {
  46552. ma_data_converter_config config;
  46553. config = ma_data_converter_config_init(formatIn, formatOut, channelsIn, channelsOut, sampleRateIn, sampleRateOut);
  46554. config.resampling.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
  46555. return ma_convert_frames_ex(pOut, frameCountOut, pIn, frameCountIn, &config);
  46556. }
  46557. MA_API ma_uint64 ma_convert_frames_ex(void* pOut, ma_uint64 frameCountOut, const void* pIn, ma_uint64 frameCountIn, const ma_data_converter_config* pConfig)
  46558. {
  46559. ma_result result;
  46560. ma_data_converter converter;
  46561. if (frameCountIn == 0 || pConfig == NULL) {
  46562. return 0;
  46563. }
  46564. result = ma_data_converter_init(pConfig, NULL, &converter);
  46565. if (result != MA_SUCCESS) {
  46566. return 0; /* Failed to initialize the data converter. */
  46567. }
  46568. if (pOut == NULL) {
  46569. result = ma_data_converter_get_expected_output_frame_count(&converter, frameCountIn, &frameCountOut);
  46570. if (result != MA_SUCCESS) {
  46571. if (result == MA_NOT_IMPLEMENTED) {
  46572. /* No way to calculate the number of frames, so we'll need to brute force it and loop. */
  46573. frameCountOut = 0;
  46574. while (frameCountIn > 0) {
  46575. ma_uint64 framesProcessedIn = frameCountIn;
  46576. ma_uint64 framesProcessedOut = 0xFFFFFFFF;
  46577. result = ma_data_converter_process_pcm_frames(&converter, pIn, &framesProcessedIn, NULL, &framesProcessedOut);
  46578. if (result != MA_SUCCESS) {
  46579. break;
  46580. }
  46581. frameCountIn -= framesProcessedIn;
  46582. }
  46583. }
  46584. }
  46585. } else {
  46586. result = ma_data_converter_process_pcm_frames(&converter, pIn, &frameCountIn, pOut, &frameCountOut);
  46587. if (result != MA_SUCCESS) {
  46588. frameCountOut = 0;
  46589. }
  46590. }
  46591. ma_data_converter_uninit(&converter, NULL);
  46592. return frameCountOut;
  46593. }
  46594. /**************************************************************************************************************************************************************
  46595. Ring Buffer
  46596. **************************************************************************************************************************************************************/
  46597. static MA_INLINE ma_uint32 ma_rb__extract_offset_in_bytes(ma_uint32 encodedOffset)
  46598. {
  46599. return encodedOffset & 0x7FFFFFFF;
  46600. }
  46601. static MA_INLINE ma_uint32 ma_rb__extract_offset_loop_flag(ma_uint32 encodedOffset)
  46602. {
  46603. return encodedOffset & 0x80000000;
  46604. }
  46605. static MA_INLINE void* ma_rb__get_read_ptr(ma_rb* pRB)
  46606. {
  46607. MA_ASSERT(pRB != NULL);
  46608. return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(c89atomic_load_32(&pRB->encodedReadOffset)));
  46609. }
  46610. static MA_INLINE void* ma_rb__get_write_ptr(ma_rb* pRB)
  46611. {
  46612. MA_ASSERT(pRB != NULL);
  46613. return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(c89atomic_load_32(&pRB->encodedWriteOffset)));
  46614. }
  46615. static MA_INLINE ma_uint32 ma_rb__construct_offset(ma_uint32 offsetInBytes, ma_uint32 offsetLoopFlag)
  46616. {
  46617. return offsetLoopFlag | offsetInBytes;
  46618. }
  46619. static MA_INLINE void ma_rb__deconstruct_offset(ma_uint32 encodedOffset, ma_uint32* pOffsetInBytes, ma_uint32* pOffsetLoopFlag)
  46620. {
  46621. MA_ASSERT(pOffsetInBytes != NULL);
  46622. MA_ASSERT(pOffsetLoopFlag != NULL);
  46623. *pOffsetInBytes = ma_rb__extract_offset_in_bytes(encodedOffset);
  46624. *pOffsetLoopFlag = ma_rb__extract_offset_loop_flag(encodedOffset);
  46625. }
  46626. MA_API ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size_t subbufferStrideInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB)
  46627. {
  46628. ma_result result;
  46629. const ma_uint32 maxSubBufferSize = 0x7FFFFFFF - (MA_SIMD_ALIGNMENT-1);
  46630. if (pRB == NULL) {
  46631. return MA_INVALID_ARGS;
  46632. }
  46633. if (subbufferSizeInBytes == 0 || subbufferCount == 0) {
  46634. return MA_INVALID_ARGS;
  46635. }
  46636. if (subbufferSizeInBytes > maxSubBufferSize) {
  46637. return MA_INVALID_ARGS; /* Maximum buffer size is ~2GB. The most significant bit is a flag for use internally. */
  46638. }
  46639. MA_ZERO_OBJECT(pRB);
  46640. result = ma_allocation_callbacks_init_copy(&pRB->allocationCallbacks, pAllocationCallbacks);
  46641. if (result != MA_SUCCESS) {
  46642. return result;
  46643. }
  46644. pRB->subbufferSizeInBytes = (ma_uint32)subbufferSizeInBytes;
  46645. pRB->subbufferCount = (ma_uint32)subbufferCount;
  46646. if (pOptionalPreallocatedBuffer != NULL) {
  46647. pRB->subbufferStrideInBytes = (ma_uint32)subbufferStrideInBytes;
  46648. pRB->pBuffer = pOptionalPreallocatedBuffer;
  46649. } else {
  46650. size_t bufferSizeInBytes;
  46651. /*
  46652. Here is where we allocate our own buffer. We always want to align this to MA_SIMD_ALIGNMENT for future SIMD optimization opportunity. To do this
  46653. we need to make sure the stride is a multiple of MA_SIMD_ALIGNMENT.
  46654. */
  46655. pRB->subbufferStrideInBytes = (pRB->subbufferSizeInBytes + (MA_SIMD_ALIGNMENT-1)) & ~MA_SIMD_ALIGNMENT;
  46656. bufferSizeInBytes = (size_t)pRB->subbufferCount*pRB->subbufferStrideInBytes;
  46657. pRB->pBuffer = ma_aligned_malloc(bufferSizeInBytes, MA_SIMD_ALIGNMENT, &pRB->allocationCallbacks);
  46658. if (pRB->pBuffer == NULL) {
  46659. return MA_OUT_OF_MEMORY;
  46660. }
  46661. MA_ZERO_MEMORY(pRB->pBuffer, bufferSizeInBytes);
  46662. pRB->ownsBuffer = MA_TRUE;
  46663. }
  46664. return MA_SUCCESS;
  46665. }
  46666. MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB)
  46667. {
  46668. return ma_rb_init_ex(bufferSizeInBytes, 1, 0, pOptionalPreallocatedBuffer, pAllocationCallbacks, pRB);
  46669. }
  46670. MA_API void ma_rb_uninit(ma_rb* pRB)
  46671. {
  46672. if (pRB == NULL) {
  46673. return;
  46674. }
  46675. if (pRB->ownsBuffer) {
  46676. ma_aligned_free(pRB->pBuffer, &pRB->allocationCallbacks);
  46677. }
  46678. }
  46679. MA_API void ma_rb_reset(ma_rb* pRB)
  46680. {
  46681. if (pRB == NULL) {
  46682. return;
  46683. }
  46684. c89atomic_exchange_32(&pRB->encodedReadOffset, 0);
  46685. c89atomic_exchange_32(&pRB->encodedWriteOffset, 0);
  46686. }
  46687. MA_API ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut)
  46688. {
  46689. ma_uint32 writeOffset;
  46690. ma_uint32 writeOffsetInBytes;
  46691. ma_uint32 writeOffsetLoopFlag;
  46692. ma_uint32 readOffset;
  46693. ma_uint32 readOffsetInBytes;
  46694. ma_uint32 readOffsetLoopFlag;
  46695. size_t bytesAvailable;
  46696. size_t bytesRequested;
  46697. if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) {
  46698. return MA_INVALID_ARGS;
  46699. }
  46700. /* The returned buffer should never move ahead of the write pointer. */
  46701. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  46702. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46703. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  46704. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46705. /*
  46706. The number of bytes available depends on whether or not the read and write pointers are on the same loop iteration. If so, we
  46707. can only read up to the write pointer. If not, we can only read up to the end of the buffer.
  46708. */
  46709. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  46710. bytesAvailable = writeOffsetInBytes - readOffsetInBytes;
  46711. } else {
  46712. bytesAvailable = pRB->subbufferSizeInBytes - readOffsetInBytes;
  46713. }
  46714. bytesRequested = *pSizeInBytes;
  46715. if (bytesRequested > bytesAvailable) {
  46716. bytesRequested = bytesAvailable;
  46717. }
  46718. *pSizeInBytes = bytesRequested;
  46719. (*ppBufferOut) = ma_rb__get_read_ptr(pRB);
  46720. return MA_SUCCESS;
  46721. }
  46722. MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes)
  46723. {
  46724. ma_uint32 readOffset;
  46725. ma_uint32 readOffsetInBytes;
  46726. ma_uint32 readOffsetLoopFlag;
  46727. ma_uint32 newReadOffsetInBytes;
  46728. ma_uint32 newReadOffsetLoopFlag;
  46729. if (pRB == NULL) {
  46730. return MA_INVALID_ARGS;
  46731. }
  46732. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  46733. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46734. /* Check that sizeInBytes is correct. It should never go beyond the end of the buffer. */
  46735. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + sizeInBytes);
  46736. if (newReadOffsetInBytes > pRB->subbufferSizeInBytes) {
  46737. return MA_INVALID_ARGS; /* <-- sizeInBytes will cause the read offset to overflow. */
  46738. }
  46739. /* Move the read pointer back to the start if necessary. */
  46740. newReadOffsetLoopFlag = readOffsetLoopFlag;
  46741. if (newReadOffsetInBytes == pRB->subbufferSizeInBytes) {
  46742. newReadOffsetInBytes = 0;
  46743. newReadOffsetLoopFlag ^= 0x80000000;
  46744. }
  46745. c89atomic_exchange_32(&pRB->encodedReadOffset, ma_rb__construct_offset(newReadOffsetLoopFlag, newReadOffsetInBytes));
  46746. if (ma_rb_pointer_distance(pRB) == 0) {
  46747. return MA_AT_END;
  46748. } else {
  46749. return MA_SUCCESS;
  46750. }
  46751. }
  46752. MA_API ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut)
  46753. {
  46754. ma_uint32 readOffset;
  46755. ma_uint32 readOffsetInBytes;
  46756. ma_uint32 readOffsetLoopFlag;
  46757. ma_uint32 writeOffset;
  46758. ma_uint32 writeOffsetInBytes;
  46759. ma_uint32 writeOffsetLoopFlag;
  46760. size_t bytesAvailable;
  46761. size_t bytesRequested;
  46762. if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) {
  46763. return MA_INVALID_ARGS;
  46764. }
  46765. /* The returned buffer should never overtake the read buffer. */
  46766. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  46767. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46768. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  46769. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46770. /*
  46771. In the case of writing, if the write pointer and the read pointer are on the same loop iteration we can only
  46772. write up to the end of the buffer. Otherwise we can only write up to the read pointer. The write pointer should
  46773. never overtake the read pointer.
  46774. */
  46775. if (writeOffsetLoopFlag == readOffsetLoopFlag) {
  46776. bytesAvailable = pRB->subbufferSizeInBytes - writeOffsetInBytes;
  46777. } else {
  46778. bytesAvailable = readOffsetInBytes - writeOffsetInBytes;
  46779. }
  46780. bytesRequested = *pSizeInBytes;
  46781. if (bytesRequested > bytesAvailable) {
  46782. bytesRequested = bytesAvailable;
  46783. }
  46784. *pSizeInBytes = bytesRequested;
  46785. *ppBufferOut = ma_rb__get_write_ptr(pRB);
  46786. /* Clear the buffer if desired. */
  46787. if (pRB->clearOnWriteAcquire) {
  46788. MA_ZERO_MEMORY(*ppBufferOut, *pSizeInBytes);
  46789. }
  46790. return MA_SUCCESS;
  46791. }
  46792. MA_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes)
  46793. {
  46794. ma_uint32 writeOffset;
  46795. ma_uint32 writeOffsetInBytes;
  46796. ma_uint32 writeOffsetLoopFlag;
  46797. ma_uint32 newWriteOffsetInBytes;
  46798. ma_uint32 newWriteOffsetLoopFlag;
  46799. if (pRB == NULL) {
  46800. return MA_INVALID_ARGS;
  46801. }
  46802. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  46803. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46804. /* Check that sizeInBytes is correct. It should never go beyond the end of the buffer. */
  46805. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + sizeInBytes);
  46806. if (newWriteOffsetInBytes > pRB->subbufferSizeInBytes) {
  46807. return MA_INVALID_ARGS; /* <-- sizeInBytes will cause the read offset to overflow. */
  46808. }
  46809. /* Move the read pointer back to the start if necessary. */
  46810. newWriteOffsetLoopFlag = writeOffsetLoopFlag;
  46811. if (newWriteOffsetInBytes == pRB->subbufferSizeInBytes) {
  46812. newWriteOffsetInBytes = 0;
  46813. newWriteOffsetLoopFlag ^= 0x80000000;
  46814. }
  46815. c89atomic_exchange_32(&pRB->encodedWriteOffset, ma_rb__construct_offset(newWriteOffsetLoopFlag, newWriteOffsetInBytes));
  46816. if (ma_rb_pointer_distance(pRB) == 0) {
  46817. return MA_AT_END;
  46818. } else {
  46819. return MA_SUCCESS;
  46820. }
  46821. }
  46822. MA_API ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes)
  46823. {
  46824. ma_uint32 readOffset;
  46825. ma_uint32 readOffsetInBytes;
  46826. ma_uint32 readOffsetLoopFlag;
  46827. ma_uint32 writeOffset;
  46828. ma_uint32 writeOffsetInBytes;
  46829. ma_uint32 writeOffsetLoopFlag;
  46830. ma_uint32 newReadOffsetInBytes;
  46831. ma_uint32 newReadOffsetLoopFlag;
  46832. if (pRB == NULL || offsetInBytes > pRB->subbufferSizeInBytes) {
  46833. return MA_INVALID_ARGS;
  46834. }
  46835. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  46836. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46837. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  46838. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46839. newReadOffsetLoopFlag = readOffsetLoopFlag;
  46840. /* We cannot go past the write buffer. */
  46841. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  46842. if ((readOffsetInBytes + offsetInBytes) > writeOffsetInBytes) {
  46843. newReadOffsetInBytes = writeOffsetInBytes;
  46844. } else {
  46845. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes);
  46846. }
  46847. } else {
  46848. /* May end up looping. */
  46849. if ((readOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) {
  46850. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes;
  46851. newReadOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */
  46852. } else {
  46853. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes);
  46854. }
  46855. }
  46856. c89atomic_exchange_32(&pRB->encodedReadOffset, ma_rb__construct_offset(newReadOffsetInBytes, newReadOffsetLoopFlag));
  46857. return MA_SUCCESS;
  46858. }
  46859. MA_API ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes)
  46860. {
  46861. ma_uint32 readOffset;
  46862. ma_uint32 readOffsetInBytes;
  46863. ma_uint32 readOffsetLoopFlag;
  46864. ma_uint32 writeOffset;
  46865. ma_uint32 writeOffsetInBytes;
  46866. ma_uint32 writeOffsetLoopFlag;
  46867. ma_uint32 newWriteOffsetInBytes;
  46868. ma_uint32 newWriteOffsetLoopFlag;
  46869. if (pRB == NULL) {
  46870. return MA_INVALID_ARGS;
  46871. }
  46872. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  46873. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46874. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  46875. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46876. newWriteOffsetLoopFlag = writeOffsetLoopFlag;
  46877. /* We cannot go past the write buffer. */
  46878. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  46879. /* May end up looping. */
  46880. if ((writeOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) {
  46881. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes;
  46882. newWriteOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */
  46883. } else {
  46884. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes);
  46885. }
  46886. } else {
  46887. if ((writeOffsetInBytes + offsetInBytes) > readOffsetInBytes) {
  46888. newWriteOffsetInBytes = readOffsetInBytes;
  46889. } else {
  46890. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes);
  46891. }
  46892. }
  46893. c89atomic_exchange_32(&pRB->encodedWriteOffset, ma_rb__construct_offset(newWriteOffsetInBytes, newWriteOffsetLoopFlag));
  46894. return MA_SUCCESS;
  46895. }
  46896. MA_API ma_int32 ma_rb_pointer_distance(ma_rb* pRB)
  46897. {
  46898. ma_uint32 readOffset;
  46899. ma_uint32 readOffsetInBytes;
  46900. ma_uint32 readOffsetLoopFlag;
  46901. ma_uint32 writeOffset;
  46902. ma_uint32 writeOffsetInBytes;
  46903. ma_uint32 writeOffsetLoopFlag;
  46904. if (pRB == NULL) {
  46905. return 0;
  46906. }
  46907. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  46908. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46909. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  46910. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46911. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  46912. return writeOffsetInBytes - readOffsetInBytes;
  46913. } else {
  46914. return writeOffsetInBytes + (pRB->subbufferSizeInBytes - readOffsetInBytes);
  46915. }
  46916. }
  46917. MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB)
  46918. {
  46919. ma_int32 dist;
  46920. if (pRB == NULL) {
  46921. return 0;
  46922. }
  46923. dist = ma_rb_pointer_distance(pRB);
  46924. if (dist < 0) {
  46925. return 0;
  46926. }
  46927. return dist;
  46928. }
  46929. MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB)
  46930. {
  46931. if (pRB == NULL) {
  46932. return 0;
  46933. }
  46934. return (ma_uint32)(ma_rb_get_subbuffer_size(pRB) - ma_rb_pointer_distance(pRB));
  46935. }
  46936. MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB)
  46937. {
  46938. if (pRB == NULL) {
  46939. return 0;
  46940. }
  46941. return pRB->subbufferSizeInBytes;
  46942. }
  46943. MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB)
  46944. {
  46945. if (pRB == NULL) {
  46946. return 0;
  46947. }
  46948. if (pRB->subbufferStrideInBytes == 0) {
  46949. return (size_t)pRB->subbufferSizeInBytes;
  46950. }
  46951. return (size_t)pRB->subbufferStrideInBytes;
  46952. }
  46953. MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex)
  46954. {
  46955. if (pRB == NULL) {
  46956. return 0;
  46957. }
  46958. return subbufferIndex * ma_rb_get_subbuffer_stride(pRB);
  46959. }
  46960. MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer)
  46961. {
  46962. if (pRB == NULL) {
  46963. return NULL;
  46964. }
  46965. return ma_offset_ptr(pBuffer, ma_rb_get_subbuffer_offset(pRB, subbufferIndex));
  46966. }
  46967. static ma_result ma_pcm_rb_data_source__on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  46968. {
  46969. /* Since there's no notion of an end, we don't ever want to return MA_AT_END here. But it is possible to return 0. */
  46970. ma_pcm_rb* pRB = (ma_pcm_rb*)pDataSource;
  46971. ma_result result;
  46972. ma_uint64 totalFramesRead;
  46973. MA_ASSERT(pRB != NULL);
  46974. /* We need to run this in a loop since the ring buffer itself may loop. */
  46975. totalFramesRead = 0;
  46976. while (totalFramesRead < frameCount) {
  46977. void* pMappedBuffer;
  46978. ma_uint32 mappedFrameCount;
  46979. ma_uint64 framesToRead = frameCount - totalFramesRead;
  46980. if (framesToRead > 0xFFFFFFFF) {
  46981. framesToRead = 0xFFFFFFFF;
  46982. }
  46983. mappedFrameCount = (ma_uint32)framesToRead;
  46984. result = ma_pcm_rb_acquire_read(pRB, &mappedFrameCount, &pMappedBuffer);
  46985. if (result != MA_SUCCESS) {
  46986. break;
  46987. }
  46988. if (mappedFrameCount == 0) {
  46989. break; /* <-- End of ring buffer. */
  46990. }
  46991. ma_copy_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, pRB->format, pRB->channels), pMappedBuffer, mappedFrameCount, pRB->format, pRB->channels);
  46992. result = ma_pcm_rb_commit_read(pRB, mappedFrameCount);
  46993. if (result != MA_SUCCESS) {
  46994. break;
  46995. }
  46996. totalFramesRead += mappedFrameCount;
  46997. }
  46998. *pFramesRead = totalFramesRead;
  46999. return MA_SUCCESS;
  47000. }
  47001. static ma_result ma_pcm_rb_data_source__on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  47002. {
  47003. ma_pcm_rb* pRB = (ma_pcm_rb*)pDataSource;
  47004. MA_ASSERT(pRB != NULL);
  47005. if (pFormat != NULL) {
  47006. *pFormat = pRB->format;
  47007. }
  47008. if (pChannels != NULL) {
  47009. *pChannels = pRB->channels;
  47010. }
  47011. if (pSampleRate != NULL) {
  47012. *pSampleRate = pRB->sampleRate;
  47013. }
  47014. /* Just assume the default channel map. */
  47015. if (pChannelMap != NULL) {
  47016. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pRB->channels);
  47017. }
  47018. return MA_SUCCESS;
  47019. }
  47020. static ma_data_source_vtable ma_gRBDataSourceVTable =
  47021. {
  47022. ma_pcm_rb_data_source__on_read,
  47023. NULL, /* onSeek */
  47024. ma_pcm_rb_data_source__on_get_data_format,
  47025. NULL, /* onGetCursor */
  47026. NULL, /* onGetLength */
  47027. NULL, /* onSetLooping */
  47028. 0
  47029. };
  47030. static MA_INLINE ma_uint32 ma_pcm_rb_get_bpf(ma_pcm_rb* pRB)
  47031. {
  47032. MA_ASSERT(pRB != NULL);
  47033. return ma_get_bytes_per_frame(pRB->format, pRB->channels);
  47034. }
  47035. MA_API ma_result ma_pcm_rb_init_ex(ma_format format, ma_uint32 channels, ma_uint32 subbufferSizeInFrames, ma_uint32 subbufferCount, ma_uint32 subbufferStrideInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB)
  47036. {
  47037. ma_uint32 bpf;
  47038. ma_result result;
  47039. if (pRB == NULL) {
  47040. return MA_INVALID_ARGS;
  47041. }
  47042. MA_ZERO_OBJECT(pRB);
  47043. bpf = ma_get_bytes_per_frame(format, channels);
  47044. if (bpf == 0) {
  47045. return MA_INVALID_ARGS;
  47046. }
  47047. result = ma_rb_init_ex(subbufferSizeInFrames*bpf, subbufferCount, subbufferStrideInFrames*bpf, pOptionalPreallocatedBuffer, pAllocationCallbacks, &pRB->rb);
  47048. if (result != MA_SUCCESS) {
  47049. return result;
  47050. }
  47051. pRB->format = format;
  47052. pRB->channels = channels;
  47053. pRB->sampleRate = 0; /* The sample rate is not passed in as a parameter. */
  47054. /* The PCM ring buffer is a data source. We need to get that set up as well. */
  47055. {
  47056. ma_data_source_config dataSourceConfig = ma_data_source_config_init();
  47057. dataSourceConfig.vtable = &ma_gRBDataSourceVTable;
  47058. result = ma_data_source_init(&dataSourceConfig, &pRB->ds);
  47059. if (result != MA_SUCCESS) {
  47060. ma_rb_uninit(&pRB->rb);
  47061. return result;
  47062. }
  47063. }
  47064. return MA_SUCCESS;
  47065. }
  47066. MA_API ma_result ma_pcm_rb_init(ma_format format, ma_uint32 channels, ma_uint32 bufferSizeInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB)
  47067. {
  47068. return ma_pcm_rb_init_ex(format, channels, bufferSizeInFrames, 1, 0, pOptionalPreallocatedBuffer, pAllocationCallbacks, pRB);
  47069. }
  47070. MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB)
  47071. {
  47072. if (pRB == NULL) {
  47073. return;
  47074. }
  47075. ma_data_source_uninit(&pRB->ds);
  47076. ma_rb_uninit(&pRB->rb);
  47077. }
  47078. MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB)
  47079. {
  47080. if (pRB == NULL) {
  47081. return;
  47082. }
  47083. ma_rb_reset(&pRB->rb);
  47084. }
  47085. MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut)
  47086. {
  47087. size_t sizeInBytes;
  47088. ma_result result;
  47089. if (pRB == NULL || pSizeInFrames == NULL) {
  47090. return MA_INVALID_ARGS;
  47091. }
  47092. sizeInBytes = *pSizeInFrames * ma_pcm_rb_get_bpf(pRB);
  47093. result = ma_rb_acquire_read(&pRB->rb, &sizeInBytes, ppBufferOut);
  47094. if (result != MA_SUCCESS) {
  47095. return result;
  47096. }
  47097. *pSizeInFrames = (ma_uint32)(sizeInBytes / (size_t)ma_pcm_rb_get_bpf(pRB));
  47098. return MA_SUCCESS;
  47099. }
  47100. MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames)
  47101. {
  47102. if (pRB == NULL) {
  47103. return MA_INVALID_ARGS;
  47104. }
  47105. return ma_rb_commit_read(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB));
  47106. }
  47107. MA_API ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut)
  47108. {
  47109. size_t sizeInBytes;
  47110. ma_result result;
  47111. if (pRB == NULL) {
  47112. return MA_INVALID_ARGS;
  47113. }
  47114. sizeInBytes = *pSizeInFrames * ma_pcm_rb_get_bpf(pRB);
  47115. result = ma_rb_acquire_write(&pRB->rb, &sizeInBytes, ppBufferOut);
  47116. if (result != MA_SUCCESS) {
  47117. return result;
  47118. }
  47119. *pSizeInFrames = (ma_uint32)(sizeInBytes / ma_pcm_rb_get_bpf(pRB));
  47120. return MA_SUCCESS;
  47121. }
  47122. MA_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames)
  47123. {
  47124. if (pRB == NULL) {
  47125. return MA_INVALID_ARGS;
  47126. }
  47127. return ma_rb_commit_write(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB));
  47128. }
  47129. MA_API ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames)
  47130. {
  47131. if (pRB == NULL) {
  47132. return MA_INVALID_ARGS;
  47133. }
  47134. return ma_rb_seek_read(&pRB->rb, offsetInFrames * ma_pcm_rb_get_bpf(pRB));
  47135. }
  47136. MA_API ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames)
  47137. {
  47138. if (pRB == NULL) {
  47139. return MA_INVALID_ARGS;
  47140. }
  47141. return ma_rb_seek_write(&pRB->rb, offsetInFrames * ma_pcm_rb_get_bpf(pRB));
  47142. }
  47143. MA_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB)
  47144. {
  47145. if (pRB == NULL) {
  47146. return 0;
  47147. }
  47148. return ma_rb_pointer_distance(&pRB->rb) / ma_pcm_rb_get_bpf(pRB);
  47149. }
  47150. MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB)
  47151. {
  47152. if (pRB == NULL) {
  47153. return 0;
  47154. }
  47155. return ma_rb_available_read(&pRB->rb) / ma_pcm_rb_get_bpf(pRB);
  47156. }
  47157. MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB)
  47158. {
  47159. if (pRB == NULL) {
  47160. return 0;
  47161. }
  47162. return ma_rb_available_write(&pRB->rb) / ma_pcm_rb_get_bpf(pRB);
  47163. }
  47164. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB)
  47165. {
  47166. if (pRB == NULL) {
  47167. return 0;
  47168. }
  47169. return (ma_uint32)(ma_rb_get_subbuffer_size(&pRB->rb) / ma_pcm_rb_get_bpf(pRB));
  47170. }
  47171. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB)
  47172. {
  47173. if (pRB == NULL) {
  47174. return 0;
  47175. }
  47176. return (ma_uint32)(ma_rb_get_subbuffer_stride(&pRB->rb) / ma_pcm_rb_get_bpf(pRB));
  47177. }
  47178. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex)
  47179. {
  47180. if (pRB == NULL) {
  47181. return 0;
  47182. }
  47183. return (ma_uint32)(ma_rb_get_subbuffer_offset(&pRB->rb, subbufferIndex) / ma_pcm_rb_get_bpf(pRB));
  47184. }
  47185. MA_API void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer)
  47186. {
  47187. if (pRB == NULL) {
  47188. return NULL;
  47189. }
  47190. return ma_rb_get_subbuffer_ptr(&pRB->rb, subbufferIndex, pBuffer);
  47191. }
  47192. MA_API ma_format ma_pcm_rb_get_format(const ma_pcm_rb* pRB)
  47193. {
  47194. if (pRB == NULL) {
  47195. return ma_format_unknown;
  47196. }
  47197. return pRB->format;
  47198. }
  47199. MA_API ma_uint32 ma_pcm_rb_get_channels(const ma_pcm_rb* pRB)
  47200. {
  47201. if (pRB == NULL) {
  47202. return 0;
  47203. }
  47204. return pRB->channels;
  47205. }
  47206. MA_API ma_uint32 ma_pcm_rb_get_sample_rate(const ma_pcm_rb* pRB)
  47207. {
  47208. if (pRB == NULL) {
  47209. return 0;
  47210. }
  47211. return pRB->sampleRate;
  47212. }
  47213. MA_API void ma_pcm_rb_set_sample_rate(ma_pcm_rb* pRB, ma_uint32 sampleRate)
  47214. {
  47215. if (pRB == NULL) {
  47216. return;
  47217. }
  47218. pRB->sampleRate = sampleRate;
  47219. }
  47220. MA_API ma_result ma_duplex_rb_init(ma_format captureFormat, ma_uint32 captureChannels, ma_uint32 sampleRate, ma_uint32 captureInternalSampleRate, ma_uint32 captureInternalPeriodSizeInFrames, const ma_allocation_callbacks* pAllocationCallbacks, ma_duplex_rb* pRB)
  47221. {
  47222. ma_result result;
  47223. ma_uint32 sizeInFrames;
  47224. sizeInFrames = (ma_uint32)ma_calculate_frame_count_after_resampling(sampleRate, captureInternalSampleRate, captureInternalPeriodSizeInFrames * 5);
  47225. if (sizeInFrames == 0) {
  47226. return MA_INVALID_ARGS;
  47227. }
  47228. result = ma_pcm_rb_init(captureFormat, captureChannels, sizeInFrames, NULL, pAllocationCallbacks, &pRB->rb);
  47229. if (result != MA_SUCCESS) {
  47230. return result;
  47231. }
  47232. /* Seek forward a bit so we have a bit of a buffer in case of desyncs. */
  47233. ma_pcm_rb_seek_write((ma_pcm_rb*)pRB, captureInternalPeriodSizeInFrames * 2);
  47234. return MA_SUCCESS;
  47235. }
  47236. MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB)
  47237. {
  47238. ma_pcm_rb_uninit((ma_pcm_rb*)pRB);
  47239. return MA_SUCCESS;
  47240. }
  47241. /**************************************************************************************************************************************************************
  47242. Miscellaneous Helpers
  47243. **************************************************************************************************************************************************************/
  47244. MA_API const char* ma_result_description(ma_result result)
  47245. {
  47246. switch (result)
  47247. {
  47248. case MA_SUCCESS: return "No error";
  47249. case MA_ERROR: return "Unknown error";
  47250. case MA_INVALID_ARGS: return "Invalid argument";
  47251. case MA_INVALID_OPERATION: return "Invalid operation";
  47252. case MA_OUT_OF_MEMORY: return "Out of memory";
  47253. case MA_OUT_OF_RANGE: return "Out of range";
  47254. case MA_ACCESS_DENIED: return "Permission denied";
  47255. case MA_DOES_NOT_EXIST: return "Resource does not exist";
  47256. case MA_ALREADY_EXISTS: return "Resource already exists";
  47257. case MA_TOO_MANY_OPEN_FILES: return "Too many open files";
  47258. case MA_INVALID_FILE: return "Invalid file";
  47259. case MA_TOO_BIG: return "Too large";
  47260. case MA_PATH_TOO_LONG: return "Path too long";
  47261. case MA_NAME_TOO_LONG: return "Name too long";
  47262. case MA_NOT_DIRECTORY: return "Not a directory";
  47263. case MA_IS_DIRECTORY: return "Is a directory";
  47264. case MA_DIRECTORY_NOT_EMPTY: return "Directory not empty";
  47265. case MA_AT_END: return "At end";
  47266. case MA_NO_SPACE: return "No space available";
  47267. case MA_BUSY: return "Device or resource busy";
  47268. case MA_IO_ERROR: return "Input/output error";
  47269. case MA_INTERRUPT: return "Interrupted";
  47270. case MA_UNAVAILABLE: return "Resource unavailable";
  47271. case MA_ALREADY_IN_USE: return "Resource already in use";
  47272. case MA_BAD_ADDRESS: return "Bad address";
  47273. case MA_BAD_SEEK: return "Illegal seek";
  47274. case MA_BAD_PIPE: return "Broken pipe";
  47275. case MA_DEADLOCK: return "Deadlock";
  47276. case MA_TOO_MANY_LINKS: return "Too many links";
  47277. case MA_NOT_IMPLEMENTED: return "Not implemented";
  47278. case MA_NO_MESSAGE: return "No message of desired type";
  47279. case MA_BAD_MESSAGE: return "Invalid message";
  47280. case MA_NO_DATA_AVAILABLE: return "No data available";
  47281. case MA_INVALID_DATA: return "Invalid data";
  47282. case MA_TIMEOUT: return "Timeout";
  47283. case MA_NO_NETWORK: return "Network unavailable";
  47284. case MA_NOT_UNIQUE: return "Not unique";
  47285. case MA_NOT_SOCKET: return "Socket operation on non-socket";
  47286. case MA_NO_ADDRESS: return "Destination address required";
  47287. case MA_BAD_PROTOCOL: return "Protocol wrong type for socket";
  47288. case MA_PROTOCOL_UNAVAILABLE: return "Protocol not available";
  47289. case MA_PROTOCOL_NOT_SUPPORTED: return "Protocol not supported";
  47290. case MA_PROTOCOL_FAMILY_NOT_SUPPORTED: return "Protocol family not supported";
  47291. case MA_ADDRESS_FAMILY_NOT_SUPPORTED: return "Address family not supported";
  47292. case MA_SOCKET_NOT_SUPPORTED: return "Socket type not supported";
  47293. case MA_CONNECTION_RESET: return "Connection reset";
  47294. case MA_ALREADY_CONNECTED: return "Already connected";
  47295. case MA_NOT_CONNECTED: return "Not connected";
  47296. case MA_CONNECTION_REFUSED: return "Connection refused";
  47297. case MA_NO_HOST: return "No host";
  47298. case MA_IN_PROGRESS: return "Operation in progress";
  47299. case MA_CANCELLED: return "Operation cancelled";
  47300. case MA_MEMORY_ALREADY_MAPPED: return "Memory already mapped";
  47301. case MA_FORMAT_NOT_SUPPORTED: return "Format not supported";
  47302. case MA_DEVICE_TYPE_NOT_SUPPORTED: return "Device type not supported";
  47303. case MA_SHARE_MODE_NOT_SUPPORTED: return "Share mode not supported";
  47304. case MA_NO_BACKEND: return "No backend";
  47305. case MA_NO_DEVICE: return "No device";
  47306. case MA_API_NOT_FOUND: return "API not found";
  47307. case MA_INVALID_DEVICE_CONFIG: return "Invalid device config";
  47308. case MA_DEVICE_NOT_INITIALIZED: return "Device not initialized";
  47309. case MA_DEVICE_NOT_STARTED: return "Device not started";
  47310. case MA_FAILED_TO_INIT_BACKEND: return "Failed to initialize backend";
  47311. case MA_FAILED_TO_OPEN_BACKEND_DEVICE: return "Failed to open backend device";
  47312. case MA_FAILED_TO_START_BACKEND_DEVICE: return "Failed to start backend device";
  47313. case MA_FAILED_TO_STOP_BACKEND_DEVICE: return "Failed to stop backend device";
  47314. default: return "Unknown error";
  47315. }
  47316. }
  47317. MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  47318. {
  47319. if (pAllocationCallbacks != NULL) {
  47320. if (pAllocationCallbacks->onMalloc != NULL) {
  47321. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  47322. } else {
  47323. return NULL; /* Do not fall back to the default implementation. */
  47324. }
  47325. } else {
  47326. return ma__malloc_default(sz, NULL);
  47327. }
  47328. }
  47329. MA_API void* ma_calloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  47330. {
  47331. void* p = ma_malloc(sz, pAllocationCallbacks);
  47332. if (p != NULL) {
  47333. MA_ZERO_MEMORY(p, sz);
  47334. }
  47335. return p;
  47336. }
  47337. MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  47338. {
  47339. if (pAllocationCallbacks != NULL) {
  47340. if (pAllocationCallbacks->onRealloc != NULL) {
  47341. return pAllocationCallbacks->onRealloc(p, sz, pAllocationCallbacks->pUserData);
  47342. } else {
  47343. return NULL; /* Do not fall back to the default implementation. */
  47344. }
  47345. } else {
  47346. return ma__realloc_default(p, sz, NULL);
  47347. }
  47348. }
  47349. MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  47350. {
  47351. if (p == NULL) {
  47352. return;
  47353. }
  47354. if (pAllocationCallbacks != NULL) {
  47355. if (pAllocationCallbacks->onFree != NULL) {
  47356. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  47357. } else {
  47358. return; /* Do no fall back to the default implementation. */
  47359. }
  47360. } else {
  47361. ma__free_default(p, NULL);
  47362. }
  47363. }
  47364. MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks)
  47365. {
  47366. size_t extraBytes;
  47367. void* pUnaligned;
  47368. void* pAligned;
  47369. if (alignment == 0) {
  47370. return 0;
  47371. }
  47372. extraBytes = alignment-1 + sizeof(void*);
  47373. pUnaligned = ma_malloc(sz + extraBytes, pAllocationCallbacks);
  47374. if (pUnaligned == NULL) {
  47375. return NULL;
  47376. }
  47377. pAligned = (void*)(((ma_uintptr)pUnaligned + extraBytes) & ~((ma_uintptr)(alignment-1)));
  47378. ((void**)pAligned)[-1] = pUnaligned;
  47379. return pAligned;
  47380. }
  47381. MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  47382. {
  47383. ma_free(((void**)p)[-1], pAllocationCallbacks);
  47384. }
  47385. MA_API const char* ma_get_format_name(ma_format format)
  47386. {
  47387. switch (format)
  47388. {
  47389. case ma_format_unknown: return "Unknown";
  47390. case ma_format_u8: return "8-bit Unsigned Integer";
  47391. case ma_format_s16: return "16-bit Signed Integer";
  47392. case ma_format_s24: return "24-bit Signed Integer (Tightly Packed)";
  47393. case ma_format_s32: return "32-bit Signed Integer";
  47394. case ma_format_f32: return "32-bit IEEE Floating Point";
  47395. default: return "Invalid";
  47396. }
  47397. }
  47398. MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels)
  47399. {
  47400. ma_uint32 i;
  47401. for (i = 0; i < channels; ++i) {
  47402. pOut[i] = ma_mix_f32(pInA[i], pInB[i], factor);
  47403. }
  47404. }
  47405. MA_API ma_uint32 ma_get_bytes_per_sample(ma_format format)
  47406. {
  47407. ma_uint32 sizes[] = {
  47408. 0, /* unknown */
  47409. 1, /* u8 */
  47410. 2, /* s16 */
  47411. 3, /* s24 */
  47412. 4, /* s32 */
  47413. 4, /* f32 */
  47414. };
  47415. return sizes[format];
  47416. }
  47417. #define MA_DATA_SOURCE_DEFAULT_RANGE_BEG 0
  47418. #define MA_DATA_SOURCE_DEFAULT_RANGE_END ~((ma_uint64)0)
  47419. #define MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG 0
  47420. #define MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END ~((ma_uint64)0)
  47421. MA_API ma_data_source_config ma_data_source_config_init(void)
  47422. {
  47423. ma_data_source_config config;
  47424. MA_ZERO_OBJECT(&config);
  47425. return config;
  47426. }
  47427. MA_API ma_result ma_data_source_init(const ma_data_source_config* pConfig, ma_data_source* pDataSource)
  47428. {
  47429. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47430. if (pDataSource == NULL) {
  47431. return MA_INVALID_ARGS;
  47432. }
  47433. MA_ZERO_OBJECT(pDataSourceBase);
  47434. if (pConfig == NULL) {
  47435. return MA_INVALID_ARGS;
  47436. }
  47437. pDataSourceBase->vtable = pConfig->vtable;
  47438. pDataSourceBase->rangeBegInFrames = MA_DATA_SOURCE_DEFAULT_RANGE_BEG;
  47439. pDataSourceBase->rangeEndInFrames = MA_DATA_SOURCE_DEFAULT_RANGE_END;
  47440. pDataSourceBase->loopBegInFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG;
  47441. pDataSourceBase->loopEndInFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END;
  47442. pDataSourceBase->pCurrent = pDataSource; /* Always read from ourself by default. */
  47443. pDataSourceBase->pNext = NULL;
  47444. pDataSourceBase->onGetNext = NULL;
  47445. return MA_SUCCESS;
  47446. }
  47447. MA_API void ma_data_source_uninit(ma_data_source* pDataSource)
  47448. {
  47449. if (pDataSource == NULL) {
  47450. return;
  47451. }
  47452. /*
  47453. This is placeholder in case we need this later. Data sources need to call this in their
  47454. uninitialization routine to ensure things work later on if something is added here.
  47455. */
  47456. }
  47457. static ma_result ma_data_source_resolve_current(ma_data_source* pDataSource, ma_data_source** ppCurrentDataSource)
  47458. {
  47459. ma_data_source_base* pCurrentDataSource = (ma_data_source_base*)pDataSource;
  47460. MA_ASSERT(pDataSource != NULL);
  47461. MA_ASSERT(ppCurrentDataSource != NULL);
  47462. if (pCurrentDataSource->pCurrent == NULL) {
  47463. /*
  47464. The current data source is NULL. If we're using this in the context of a chain we need to return NULL
  47465. here so that we don't end up looping. Otherwise we just return the data source itself.
  47466. */
  47467. if (pCurrentDataSource->pNext != NULL || pCurrentDataSource->onGetNext != NULL) {
  47468. pCurrentDataSource = NULL;
  47469. } else {
  47470. pCurrentDataSource = (ma_data_source_base*)pDataSource; /* Not being used in a chain. Make sure we just always read from the data source itself at all times. */
  47471. }
  47472. } else {
  47473. pCurrentDataSource = (ma_data_source_base*)pCurrentDataSource->pCurrent;
  47474. }
  47475. *ppCurrentDataSource = pCurrentDataSource;
  47476. return MA_SUCCESS;
  47477. }
  47478. static ma_result ma_data_source_read_pcm_frames_within_range(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  47479. {
  47480. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47481. ma_result result;
  47482. ma_uint64 framesRead = 0;
  47483. ma_bool32 loop = ma_data_source_is_looping(pDataSource);
  47484. if (pDataSourceBase == NULL) {
  47485. return MA_AT_END;
  47486. }
  47487. if (frameCount == 0) {
  47488. return MA_INVALID_ARGS;
  47489. }
  47490. if ((pDataSourceBase->vtable->flags & MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT) != 0 || (pDataSourceBase->rangeEndInFrames == ~((ma_uint64)0) && (pDataSourceBase->loopEndInFrames == ~((ma_uint64)0) || loop == MA_FALSE))) {
  47491. /* Either the data source is self-managing the range, or no range is set - just read like normal. The data source itself will tell us when the end is reached. */
  47492. result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead);
  47493. } else {
  47494. /* Need to clamp to within the range. */
  47495. ma_uint64 relativeCursor;
  47496. ma_uint64 absoluteCursor;
  47497. result = ma_data_source_get_cursor_in_pcm_frames(pDataSourceBase, &relativeCursor);
  47498. if (result != MA_SUCCESS) {
  47499. /* Failed to retrieve the cursor. Cannot read within a range or loop points. Just read like normal - this may happen for things like noise data sources where it doesn't really matter. */
  47500. result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead);
  47501. } else {
  47502. ma_uint64 rangeBeg;
  47503. ma_uint64 rangeEnd;
  47504. /* We have the cursor. We need to make sure we don't read beyond our range. */
  47505. rangeBeg = pDataSourceBase->rangeBegInFrames;
  47506. rangeEnd = pDataSourceBase->rangeEndInFrames;
  47507. absoluteCursor = rangeBeg + relativeCursor;
  47508. /* If looping, make sure we're within range. */
  47509. if (loop) {
  47510. if (pDataSourceBase->loopEndInFrames != ~((ma_uint64)0)) {
  47511. rangeEnd = ma_min(rangeEnd, pDataSourceBase->rangeBegInFrames + pDataSourceBase->loopEndInFrames);
  47512. }
  47513. }
  47514. if (frameCount > (rangeEnd - absoluteCursor) && rangeEnd != ~((ma_uint64)0)) {
  47515. frameCount = (rangeEnd - absoluteCursor);
  47516. }
  47517. /*
  47518. If the cursor is sitting on the end of the range the frame count will be set to 0 which can
  47519. result in MA_INVALID_ARGS. In this case, we don't want to try reading, but instead return
  47520. MA_AT_END so the higher level function can know about it.
  47521. */
  47522. if (frameCount > 0) {
  47523. result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead);
  47524. } else {
  47525. result = MA_AT_END; /* The cursor is sitting on the end of the range which means we're at the end. */
  47526. }
  47527. }
  47528. }
  47529. if (pFramesRead != NULL) {
  47530. *pFramesRead = framesRead;
  47531. }
  47532. /* We need to make sure MA_AT_END is returned if we hit the end of the range. */
  47533. if (result == MA_SUCCESS && framesRead == 0) {
  47534. result = MA_AT_END;
  47535. }
  47536. return result;
  47537. }
  47538. MA_API ma_result ma_data_source_read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  47539. {
  47540. ma_result result = MA_SUCCESS;
  47541. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47542. ma_data_source_base* pCurrentDataSource;
  47543. void* pRunningFramesOut = pFramesOut;
  47544. ma_uint64 totalFramesProcessed = 0;
  47545. ma_format format;
  47546. ma_uint32 channels;
  47547. ma_uint32 emptyLoopCounter = 0; /* Keeps track of how many times 0 frames have been read. For infinite loop detection of sounds with no audio data. */
  47548. ma_bool32 loop;
  47549. if (pFramesRead != NULL) {
  47550. *pFramesRead = 0;
  47551. }
  47552. if (frameCount == 0) {
  47553. return MA_INVALID_ARGS;
  47554. }
  47555. if (pDataSourceBase == NULL) {
  47556. return MA_INVALID_ARGS;
  47557. }
  47558. loop = ma_data_source_is_looping(pDataSource);
  47559. /*
  47560. We need to know the data format so we can advance the output buffer as we read frames. If this
  47561. fails, chaining will not work and we'll just read as much as we can from the current source.
  47562. */
  47563. if (ma_data_source_get_data_format(pDataSource, &format, &channels, NULL, NULL, 0) != MA_SUCCESS) {
  47564. result = ma_data_source_resolve_current(pDataSource, (ma_data_source**)&pCurrentDataSource);
  47565. if (result != MA_SUCCESS) {
  47566. return result;
  47567. }
  47568. return ma_data_source_read_pcm_frames_within_range(pCurrentDataSource, pFramesOut, frameCount, pFramesRead);
  47569. }
  47570. /*
  47571. Looping is a bit of a special case. When the `loop` argument is true, chaining will not work and
  47572. only the current data source will be read from.
  47573. */
  47574. /* Keep reading until we've read as many frames as possible. */
  47575. while (totalFramesProcessed < frameCount) {
  47576. ma_uint64 framesProcessed;
  47577. ma_uint64 framesRemaining = frameCount - totalFramesProcessed;
  47578. /* We need to resolve the data source that we'll actually be reading from. */
  47579. result = ma_data_source_resolve_current(pDataSource, (ma_data_source**)&pCurrentDataSource);
  47580. if (result != MA_SUCCESS) {
  47581. break;
  47582. }
  47583. if (pCurrentDataSource == NULL) {
  47584. break;
  47585. }
  47586. result = ma_data_source_read_pcm_frames_within_range(pCurrentDataSource, pRunningFramesOut, framesRemaining, &framesProcessed);
  47587. totalFramesProcessed += framesProcessed;
  47588. /*
  47589. If we encounted an error from the read callback, make sure it's propagated to the caller. The caller may need to know whether or not MA_BUSY is returned which is
  47590. not necessarily considered an error.
  47591. */
  47592. if (result != MA_SUCCESS && result != MA_AT_END) {
  47593. break;
  47594. }
  47595. /*
  47596. We can determine if we've reached the end by checking if ma_data_source_read_pcm_frames_within_range() returned
  47597. MA_AT_END. To loop back to the start, all we need to do is seek back to the first frame.
  47598. */
  47599. if (result == MA_AT_END) {
  47600. /*
  47601. The result needs to be reset back to MA_SUCCESS (from MA_AT_END) so that we don't
  47602. accidentally return MA_AT_END when data has been read in prior loop iterations. at the
  47603. end of this function, the result will be checked for MA_SUCCESS, and if the total
  47604. number of frames processed is 0, will be explicitly set to MA_AT_END.
  47605. */
  47606. result = MA_SUCCESS;
  47607. /*
  47608. We reached the end. If we're looping, we just loop back to the start of the current
  47609. data source. If we're not looping we need to check if we have another in the chain, and
  47610. if so, switch to it.
  47611. */
  47612. if (loop) {
  47613. if (framesProcessed == 0) {
  47614. emptyLoopCounter += 1;
  47615. if (emptyLoopCounter > 1) {
  47616. break; /* Infinite loop detected. Get out. */
  47617. }
  47618. } else {
  47619. emptyLoopCounter = 0;
  47620. }
  47621. result = ma_data_source_seek_to_pcm_frame(pCurrentDataSource, pCurrentDataSource->loopBegInFrames);
  47622. if (result != MA_SUCCESS) {
  47623. break; /* Failed to loop. Abort. */
  47624. }
  47625. /* Don't return MA_AT_END for looping sounds. */
  47626. result = MA_SUCCESS;
  47627. } else {
  47628. if (pCurrentDataSource->pNext != NULL) {
  47629. pDataSourceBase->pCurrent = pCurrentDataSource->pNext;
  47630. } else if (pCurrentDataSource->onGetNext != NULL) {
  47631. pDataSourceBase->pCurrent = pCurrentDataSource->onGetNext(pCurrentDataSource);
  47632. if (pDataSourceBase->pCurrent == NULL) {
  47633. break; /* Our callback did not return a next data source. We're done. */
  47634. }
  47635. } else {
  47636. /* Reached the end of the chain. We're done. */
  47637. break;
  47638. }
  47639. /* The next data source needs to be rewound to ensure data is read in looping scenarios. */
  47640. result = ma_data_source_seek_to_pcm_frame(pDataSourceBase->pCurrent, 0);
  47641. if (result != MA_SUCCESS) {
  47642. break;
  47643. }
  47644. }
  47645. }
  47646. if (pRunningFramesOut != NULL) {
  47647. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesProcessed * ma_get_bytes_per_frame(format, channels));
  47648. }
  47649. }
  47650. if (pFramesRead != NULL) {
  47651. *pFramesRead = totalFramesProcessed;
  47652. }
  47653. MA_ASSERT(!(result == MA_AT_END && totalFramesProcessed > 0)); /* We should never be returning MA_AT_END if we read some data. */
  47654. if (result == MA_SUCCESS && totalFramesProcessed == 0) {
  47655. result = MA_AT_END;
  47656. }
  47657. return result;
  47658. }
  47659. MA_API ma_result ma_data_source_seek_pcm_frames(ma_data_source* pDataSource, ma_uint64 frameCount, ma_uint64* pFramesSeeked)
  47660. {
  47661. return ma_data_source_read_pcm_frames(pDataSource, NULL, frameCount, pFramesSeeked);
  47662. }
  47663. MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
  47664. {
  47665. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47666. if (pDataSourceBase == NULL) {
  47667. return MA_SUCCESS;
  47668. }
  47669. if (pDataSourceBase->vtable->onSeek == NULL) {
  47670. return MA_NOT_IMPLEMENTED;
  47671. }
  47672. if (frameIndex > pDataSourceBase->rangeEndInFrames) {
  47673. return MA_INVALID_OPERATION; /* Trying to seek to far forward. */
  47674. }
  47675. return pDataSourceBase->vtable->onSeek(pDataSource, pDataSourceBase->rangeBegInFrames + frameIndex);
  47676. }
  47677. MA_API ma_result ma_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  47678. {
  47679. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47680. ma_result result;
  47681. ma_format format;
  47682. ma_uint32 channels;
  47683. ma_uint32 sampleRate;
  47684. /* Initialize to defaults for safety just in case the data source does not implement this callback. */
  47685. if (pFormat != NULL) {
  47686. *pFormat = ma_format_unknown;
  47687. }
  47688. if (pChannels != NULL) {
  47689. *pChannels = 0;
  47690. }
  47691. if (pSampleRate != NULL) {
  47692. *pSampleRate = 0;
  47693. }
  47694. if (pChannelMap != NULL) {
  47695. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  47696. }
  47697. if (pDataSourceBase == NULL) {
  47698. return MA_INVALID_ARGS;
  47699. }
  47700. if (pDataSourceBase->vtable->onGetDataFormat == NULL) {
  47701. return MA_NOT_IMPLEMENTED;
  47702. }
  47703. result = pDataSourceBase->vtable->onGetDataFormat(pDataSource, &format, &channels, &sampleRate, pChannelMap, channelMapCap);
  47704. if (result != MA_SUCCESS) {
  47705. return result;
  47706. }
  47707. if (pFormat != NULL) {
  47708. *pFormat = format;
  47709. }
  47710. if (pChannels != NULL) {
  47711. *pChannels = channels;
  47712. }
  47713. if (pSampleRate != NULL) {
  47714. *pSampleRate = sampleRate;
  47715. }
  47716. /* Channel map was passed in directly to the callback. This is safe due to the channelMapCap parameter. */
  47717. return MA_SUCCESS;
  47718. }
  47719. MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
  47720. {
  47721. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47722. ma_result result;
  47723. ma_uint64 cursor;
  47724. if (pCursor == NULL) {
  47725. return MA_INVALID_ARGS;
  47726. }
  47727. *pCursor = 0;
  47728. if (pDataSourceBase == NULL) {
  47729. return MA_SUCCESS;
  47730. }
  47731. if (pDataSourceBase->vtable->onGetCursor == NULL) {
  47732. return MA_NOT_IMPLEMENTED;
  47733. }
  47734. result = pDataSourceBase->vtable->onGetCursor(pDataSourceBase, &cursor);
  47735. if (result != MA_SUCCESS) {
  47736. return result;
  47737. }
  47738. /* The cursor needs to be made relative to the start of the range. */
  47739. if (cursor < pDataSourceBase->rangeBegInFrames) { /* Safety check so we don't return some huge number. */
  47740. *pCursor = 0;
  47741. } else {
  47742. *pCursor = cursor - pDataSourceBase->rangeBegInFrames;
  47743. }
  47744. return MA_SUCCESS;
  47745. }
  47746. MA_API ma_result ma_data_source_get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
  47747. {
  47748. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47749. if (pLength == NULL) {
  47750. return MA_INVALID_ARGS;
  47751. }
  47752. *pLength = 0;
  47753. if (pDataSourceBase == NULL) {
  47754. return MA_INVALID_ARGS;
  47755. }
  47756. /*
  47757. If we have a range defined we'll use that to determine the length. This is one of rare times
  47758. where we'll actually trust the caller. If they've set the range, I think it's mostly safe to
  47759. assume they've set it based on some higher level knowledge of the structure of the sound bank.
  47760. */
  47761. if (pDataSourceBase->rangeEndInFrames != ~((ma_uint64)0)) {
  47762. *pLength = pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames;
  47763. return MA_SUCCESS;
  47764. }
  47765. /*
  47766. Getting here means a range is not defined so we'll need to get the data source itself to tell
  47767. us the length.
  47768. */
  47769. if (pDataSourceBase->vtable->onGetLength == NULL) {
  47770. return MA_NOT_IMPLEMENTED;
  47771. }
  47772. return pDataSourceBase->vtable->onGetLength(pDataSource, pLength);
  47773. }
  47774. MA_API ma_result ma_data_source_get_cursor_in_seconds(ma_data_source* pDataSource, float* pCursor)
  47775. {
  47776. ma_result result;
  47777. ma_uint64 cursorInPCMFrames;
  47778. ma_uint32 sampleRate;
  47779. if (pCursor == NULL) {
  47780. return MA_INVALID_ARGS;
  47781. }
  47782. *pCursor = 0;
  47783. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursorInPCMFrames);
  47784. if (result != MA_SUCCESS) {
  47785. return result;
  47786. }
  47787. result = ma_data_source_get_data_format(pDataSource, NULL, NULL, &sampleRate, NULL, 0);
  47788. if (result != MA_SUCCESS) {
  47789. return result;
  47790. }
  47791. /* VC6 does not support division of unsigned 64-bit integers with floating point numbers. Need to use a signed number. This shouldn't effect anything in practice. */
  47792. *pCursor = (ma_int64)cursorInPCMFrames / (float)sampleRate;
  47793. return MA_SUCCESS;
  47794. }
  47795. MA_API ma_result ma_data_source_get_length_in_seconds(ma_data_source* pDataSource, float* pLength)
  47796. {
  47797. ma_result result;
  47798. ma_uint64 lengthInPCMFrames;
  47799. ma_uint32 sampleRate;
  47800. if (pLength == NULL) {
  47801. return MA_INVALID_ARGS;
  47802. }
  47803. *pLength = 0;
  47804. result = ma_data_source_get_length_in_pcm_frames(pDataSource, &lengthInPCMFrames);
  47805. if (result != MA_SUCCESS) {
  47806. return result;
  47807. }
  47808. result = ma_data_source_get_data_format(pDataSource, NULL, NULL, &sampleRate, NULL, 0);
  47809. if (result != MA_SUCCESS) {
  47810. return result;
  47811. }
  47812. /* VC6 does not support division of unsigned 64-bit integers with floating point numbers. Need to use a signed number. This shouldn't effect anything in practice. */
  47813. *pLength = (ma_int64)lengthInPCMFrames / (float)sampleRate;
  47814. return MA_SUCCESS;
  47815. }
  47816. MA_API ma_result ma_data_source_set_looping(ma_data_source* pDataSource, ma_bool32 isLooping)
  47817. {
  47818. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47819. if (pDataSource == NULL) {
  47820. return MA_INVALID_ARGS;
  47821. }
  47822. c89atomic_exchange_32(&pDataSourceBase->isLooping, isLooping);
  47823. /* If there's no callback for this just treat it as a successful no-op. */
  47824. if (pDataSourceBase->vtable->onSetLooping == NULL) {
  47825. return MA_SUCCESS;
  47826. }
  47827. return pDataSourceBase->vtable->onSetLooping(pDataSource, isLooping);
  47828. }
  47829. MA_API ma_bool32 ma_data_source_is_looping(const ma_data_source* pDataSource)
  47830. {
  47831. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  47832. if (pDataSource == NULL) {
  47833. return MA_FALSE;
  47834. }
  47835. return c89atomic_load_32(&pDataSourceBase->isLooping);
  47836. }
  47837. MA_API ma_result ma_data_source_set_range_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 rangeBegInFrames, ma_uint64 rangeEndInFrames)
  47838. {
  47839. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47840. ma_result result;
  47841. ma_uint64 relativeCursor;
  47842. ma_uint64 absoluteCursor;
  47843. ma_bool32 doSeekAdjustment = MA_FALSE;
  47844. if (pDataSource == NULL) {
  47845. return MA_INVALID_ARGS;
  47846. }
  47847. if (rangeEndInFrames < rangeBegInFrames) {
  47848. return MA_INVALID_ARGS; /* The end of the range must come after the beginning. */
  47849. }
  47850. /*
  47851. We may need to adjust the position of the cursor to ensure it's clamped to the range. Grab it now
  47852. so we can calculate it's absolute position before we change the range.
  47853. */
  47854. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &relativeCursor);
  47855. if (result == MA_SUCCESS) {
  47856. doSeekAdjustment = MA_TRUE;
  47857. absoluteCursor = relativeCursor + pDataSourceBase->rangeBegInFrames;
  47858. } else {
  47859. /*
  47860. We couldn't get the position of the cursor. It probably means the data source has no notion
  47861. of a cursor. We'll just leave it at position 0. Don't treat this as an error.
  47862. */
  47863. doSeekAdjustment = MA_FALSE;
  47864. relativeCursor = 0;
  47865. absoluteCursor = 0;
  47866. }
  47867. pDataSourceBase->rangeBegInFrames = rangeBegInFrames;
  47868. pDataSourceBase->rangeEndInFrames = rangeEndInFrames;
  47869. /*
  47870. The commented out logic below was intended to maintain loop points in response to a change in the
  47871. range. However, this is not useful because it results in the sound breaking when you move the range
  47872. outside of the old loop points. I'm simplifying this by simply resetting the loop points. The
  47873. caller is expected to update their loop points if they change the range.
  47874. In practice this should be mostly a non-issue because the majority of the time the range will be
  47875. set once right after initialization.
  47876. */
  47877. pDataSourceBase->loopBegInFrames = 0;
  47878. pDataSourceBase->loopEndInFrames = ~((ma_uint64)0);
  47879. /*
  47880. Seek to within range. Note that our seek positions here are relative to the new range. We don't want
  47881. do do this if we failed to retrieve the cursor earlier on because it probably means the data source
  47882. has no notion of a cursor. In practice the seek would probably fail (which we silently ignore), but
  47883. I'm just not even going to attempt it.
  47884. */
  47885. if (doSeekAdjustment) {
  47886. if (absoluteCursor < rangeBegInFrames) {
  47887. ma_data_source_seek_to_pcm_frame(pDataSource, 0);
  47888. } else if (absoluteCursor > rangeEndInFrames) {
  47889. ma_data_source_seek_to_pcm_frame(pDataSource, rangeEndInFrames - rangeBegInFrames);
  47890. }
  47891. }
  47892. return MA_SUCCESS;
  47893. }
  47894. MA_API void ma_data_source_get_range_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pRangeBegInFrames, ma_uint64* pRangeEndInFrames)
  47895. {
  47896. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  47897. if (pDataSource == NULL) {
  47898. return;
  47899. }
  47900. if (pRangeBegInFrames != NULL) {
  47901. *pRangeBegInFrames = pDataSourceBase->rangeBegInFrames;
  47902. }
  47903. if (pRangeEndInFrames != NULL) {
  47904. *pRangeEndInFrames = pDataSourceBase->rangeEndInFrames;
  47905. }
  47906. }
  47907. MA_API ma_result ma_data_source_set_loop_point_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 loopBegInFrames, ma_uint64 loopEndInFrames)
  47908. {
  47909. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47910. if (pDataSource == NULL) {
  47911. return MA_INVALID_ARGS;
  47912. }
  47913. if (loopEndInFrames < loopBegInFrames) {
  47914. return MA_INVALID_ARGS; /* The end of the loop point must come after the beginning. */
  47915. }
  47916. if (loopEndInFrames > pDataSourceBase->rangeEndInFrames && loopEndInFrames != ~((ma_uint64)0)) {
  47917. return MA_INVALID_ARGS; /* The end of the loop point must not go beyond the range. */
  47918. }
  47919. pDataSourceBase->loopBegInFrames = loopBegInFrames;
  47920. pDataSourceBase->loopEndInFrames = loopEndInFrames;
  47921. /* The end cannot exceed the range. */
  47922. if (pDataSourceBase->loopEndInFrames > (pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames) && pDataSourceBase->loopEndInFrames != ~((ma_uint64)0)) {
  47923. pDataSourceBase->loopEndInFrames = (pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames);
  47924. }
  47925. return MA_SUCCESS;
  47926. }
  47927. MA_API void ma_data_source_get_loop_point_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pLoopBegInFrames, ma_uint64* pLoopEndInFrames)
  47928. {
  47929. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  47930. if (pDataSource == NULL) {
  47931. return;
  47932. }
  47933. if (pLoopBegInFrames != NULL) {
  47934. *pLoopBegInFrames = pDataSourceBase->loopBegInFrames;
  47935. }
  47936. if (pLoopEndInFrames != NULL) {
  47937. *pLoopEndInFrames = pDataSourceBase->loopEndInFrames;
  47938. }
  47939. }
  47940. MA_API ma_result ma_data_source_set_current(ma_data_source* pDataSource, ma_data_source* pCurrentDataSource)
  47941. {
  47942. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47943. if (pDataSource == NULL) {
  47944. return MA_INVALID_ARGS;
  47945. }
  47946. pDataSourceBase->pCurrent = pCurrentDataSource;
  47947. return MA_SUCCESS;
  47948. }
  47949. MA_API ma_data_source* ma_data_source_get_current(const ma_data_source* pDataSource)
  47950. {
  47951. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  47952. if (pDataSource == NULL) {
  47953. return NULL;
  47954. }
  47955. return pDataSourceBase->pCurrent;
  47956. }
  47957. MA_API ma_result ma_data_source_set_next(ma_data_source* pDataSource, ma_data_source* pNextDataSource)
  47958. {
  47959. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47960. if (pDataSource == NULL) {
  47961. return MA_INVALID_ARGS;
  47962. }
  47963. pDataSourceBase->pNext = pNextDataSource;
  47964. return MA_SUCCESS;
  47965. }
  47966. MA_API ma_data_source* ma_data_source_get_next(const ma_data_source* pDataSource)
  47967. {
  47968. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  47969. if (pDataSource == NULL) {
  47970. return NULL;
  47971. }
  47972. return pDataSourceBase->pNext;
  47973. }
  47974. MA_API ma_result ma_data_source_set_next_callback(ma_data_source* pDataSource, ma_data_source_get_next_proc onGetNext)
  47975. {
  47976. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47977. if (pDataSource == NULL) {
  47978. return MA_INVALID_ARGS;
  47979. }
  47980. pDataSourceBase->onGetNext = onGetNext;
  47981. return MA_SUCCESS;
  47982. }
  47983. MA_API ma_data_source_get_next_proc ma_data_source_get_next_callback(const ma_data_source* pDataSource)
  47984. {
  47985. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  47986. if (pDataSource == NULL) {
  47987. return NULL;
  47988. }
  47989. return pDataSourceBase->onGetNext;
  47990. }
  47991. static ma_result ma_audio_buffer_ref__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  47992. {
  47993. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  47994. ma_uint64 framesRead = ma_audio_buffer_ref_read_pcm_frames(pAudioBufferRef, pFramesOut, frameCount, MA_FALSE);
  47995. if (pFramesRead != NULL) {
  47996. *pFramesRead = framesRead;
  47997. }
  47998. if (framesRead < frameCount || framesRead == 0) {
  47999. return MA_AT_END;
  48000. }
  48001. return MA_SUCCESS;
  48002. }
  48003. static ma_result ma_audio_buffer_ref__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  48004. {
  48005. return ma_audio_buffer_ref_seek_to_pcm_frame((ma_audio_buffer_ref*)pDataSource, frameIndex);
  48006. }
  48007. static ma_result ma_audio_buffer_ref__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  48008. {
  48009. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  48010. *pFormat = pAudioBufferRef->format;
  48011. *pChannels = pAudioBufferRef->channels;
  48012. *pSampleRate = pAudioBufferRef->sampleRate;
  48013. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pAudioBufferRef->channels);
  48014. return MA_SUCCESS;
  48015. }
  48016. static ma_result ma_audio_buffer_ref__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  48017. {
  48018. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  48019. *pCursor = pAudioBufferRef->cursor;
  48020. return MA_SUCCESS;
  48021. }
  48022. static ma_result ma_audio_buffer_ref__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  48023. {
  48024. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  48025. *pLength = pAudioBufferRef->sizeInFrames;
  48026. return MA_SUCCESS;
  48027. }
  48028. static ma_data_source_vtable g_ma_audio_buffer_ref_data_source_vtable =
  48029. {
  48030. ma_audio_buffer_ref__data_source_on_read,
  48031. ma_audio_buffer_ref__data_source_on_seek,
  48032. ma_audio_buffer_ref__data_source_on_get_data_format,
  48033. ma_audio_buffer_ref__data_source_on_get_cursor,
  48034. ma_audio_buffer_ref__data_source_on_get_length,
  48035. NULL, /* onSetLooping */
  48036. 0
  48037. };
  48038. MA_API ma_result ma_audio_buffer_ref_init(ma_format format, ma_uint32 channels, const void* pData, ma_uint64 sizeInFrames, ma_audio_buffer_ref* pAudioBufferRef)
  48039. {
  48040. ma_result result;
  48041. ma_data_source_config dataSourceConfig;
  48042. if (pAudioBufferRef == NULL) {
  48043. return MA_INVALID_ARGS;
  48044. }
  48045. MA_ZERO_OBJECT(pAudioBufferRef);
  48046. dataSourceConfig = ma_data_source_config_init();
  48047. dataSourceConfig.vtable = &g_ma_audio_buffer_ref_data_source_vtable;
  48048. result = ma_data_source_init(&dataSourceConfig, &pAudioBufferRef->ds);
  48049. if (result != MA_SUCCESS) {
  48050. return result;
  48051. }
  48052. pAudioBufferRef->format = format;
  48053. pAudioBufferRef->channels = channels;
  48054. pAudioBufferRef->sampleRate = 0; /* TODO: Version 0.12. Set this to sampleRate. */
  48055. pAudioBufferRef->cursor = 0;
  48056. pAudioBufferRef->sizeInFrames = sizeInFrames;
  48057. pAudioBufferRef->pData = pData;
  48058. return MA_SUCCESS;
  48059. }
  48060. MA_API void ma_audio_buffer_ref_uninit(ma_audio_buffer_ref* pAudioBufferRef)
  48061. {
  48062. if (pAudioBufferRef == NULL) {
  48063. return;
  48064. }
  48065. ma_data_source_uninit(&pAudioBufferRef->ds);
  48066. }
  48067. MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames)
  48068. {
  48069. if (pAudioBufferRef == NULL) {
  48070. return MA_INVALID_ARGS;
  48071. }
  48072. pAudioBufferRef->cursor = 0;
  48073. pAudioBufferRef->sizeInFrames = sizeInFrames;
  48074. pAudioBufferRef->pData = pData;
  48075. return MA_SUCCESS;
  48076. }
  48077. MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop)
  48078. {
  48079. ma_uint64 totalFramesRead = 0;
  48080. if (pAudioBufferRef == NULL) {
  48081. return 0;
  48082. }
  48083. if (frameCount == 0) {
  48084. return 0;
  48085. }
  48086. while (totalFramesRead < frameCount) {
  48087. ma_uint64 framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  48088. ma_uint64 framesRemaining = frameCount - totalFramesRead;
  48089. ma_uint64 framesToRead;
  48090. framesToRead = framesRemaining;
  48091. if (framesToRead > framesAvailable) {
  48092. framesToRead = framesAvailable;
  48093. }
  48094. if (pFramesOut != NULL) {
  48095. ma_copy_pcm_frames(ma_offset_ptr(pFramesOut, totalFramesRead * ma_get_bytes_per_frame(pAudioBufferRef->format, pAudioBufferRef->channels)), ma_offset_ptr(pAudioBufferRef->pData, pAudioBufferRef->cursor * ma_get_bytes_per_frame(pAudioBufferRef->format, pAudioBufferRef->channels)), framesToRead, pAudioBufferRef->format, pAudioBufferRef->channels);
  48096. }
  48097. totalFramesRead += framesToRead;
  48098. pAudioBufferRef->cursor += framesToRead;
  48099. if (pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames) {
  48100. if (loop) {
  48101. pAudioBufferRef->cursor = 0;
  48102. } else {
  48103. break; /* We've reached the end and we're not looping. Done. */
  48104. }
  48105. }
  48106. MA_ASSERT(pAudioBufferRef->cursor < pAudioBufferRef->sizeInFrames);
  48107. }
  48108. return totalFramesRead;
  48109. }
  48110. MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex)
  48111. {
  48112. if (pAudioBufferRef == NULL) {
  48113. return MA_INVALID_ARGS;
  48114. }
  48115. if (frameIndex > pAudioBufferRef->sizeInFrames) {
  48116. return MA_INVALID_ARGS;
  48117. }
  48118. pAudioBufferRef->cursor = (size_t)frameIndex;
  48119. return MA_SUCCESS;
  48120. }
  48121. MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount)
  48122. {
  48123. ma_uint64 framesAvailable;
  48124. ma_uint64 frameCount = 0;
  48125. if (ppFramesOut != NULL) {
  48126. *ppFramesOut = NULL; /* Safety. */
  48127. }
  48128. if (pFrameCount != NULL) {
  48129. frameCount = *pFrameCount;
  48130. *pFrameCount = 0; /* Safety. */
  48131. }
  48132. if (pAudioBufferRef == NULL || ppFramesOut == NULL || pFrameCount == NULL) {
  48133. return MA_INVALID_ARGS;
  48134. }
  48135. framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  48136. if (frameCount > framesAvailable) {
  48137. frameCount = framesAvailable;
  48138. }
  48139. *ppFramesOut = ma_offset_ptr(pAudioBufferRef->pData, pAudioBufferRef->cursor * ma_get_bytes_per_frame(pAudioBufferRef->format, pAudioBufferRef->channels));
  48140. *pFrameCount = frameCount;
  48141. return MA_SUCCESS;
  48142. }
  48143. MA_API ma_result ma_audio_buffer_ref_unmap(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameCount)
  48144. {
  48145. ma_uint64 framesAvailable;
  48146. if (pAudioBufferRef == NULL) {
  48147. return MA_INVALID_ARGS;
  48148. }
  48149. framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  48150. if (frameCount > framesAvailable) {
  48151. return MA_INVALID_ARGS; /* The frame count was too big. This should never happen in an unmapping. Need to make sure the caller is aware of this. */
  48152. }
  48153. pAudioBufferRef->cursor += frameCount;
  48154. if (pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames) {
  48155. return MA_AT_END; /* Successful. Need to tell the caller that the end has been reached so that it can loop if desired. */
  48156. } else {
  48157. return MA_SUCCESS;
  48158. }
  48159. }
  48160. MA_API ma_bool32 ma_audio_buffer_ref_at_end(const ma_audio_buffer_ref* pAudioBufferRef)
  48161. {
  48162. if (pAudioBufferRef == NULL) {
  48163. return MA_FALSE;
  48164. }
  48165. return pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames;
  48166. }
  48167. MA_API ma_result ma_audio_buffer_ref_get_cursor_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pCursor)
  48168. {
  48169. if (pCursor == NULL) {
  48170. return MA_INVALID_ARGS;
  48171. }
  48172. *pCursor = 0;
  48173. if (pAudioBufferRef == NULL) {
  48174. return MA_INVALID_ARGS;
  48175. }
  48176. *pCursor = pAudioBufferRef->cursor;
  48177. return MA_SUCCESS;
  48178. }
  48179. MA_API ma_result ma_audio_buffer_ref_get_length_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pLength)
  48180. {
  48181. if (pLength == NULL) {
  48182. return MA_INVALID_ARGS;
  48183. }
  48184. *pLength = 0;
  48185. if (pAudioBufferRef == NULL) {
  48186. return MA_INVALID_ARGS;
  48187. }
  48188. *pLength = pAudioBufferRef->sizeInFrames;
  48189. return MA_SUCCESS;
  48190. }
  48191. MA_API ma_result ma_audio_buffer_ref_get_available_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames)
  48192. {
  48193. if (pAvailableFrames == NULL) {
  48194. return MA_INVALID_ARGS;
  48195. }
  48196. *pAvailableFrames = 0;
  48197. if (pAudioBufferRef == NULL) {
  48198. return MA_INVALID_ARGS;
  48199. }
  48200. if (pAudioBufferRef->sizeInFrames <= pAudioBufferRef->cursor) {
  48201. *pAvailableFrames = 0;
  48202. } else {
  48203. *pAvailableFrames = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  48204. }
  48205. return MA_SUCCESS;
  48206. }
  48207. MA_API ma_audio_buffer_config ma_audio_buffer_config_init(ma_format format, ma_uint32 channels, ma_uint64 sizeInFrames, const void* pData, const ma_allocation_callbacks* pAllocationCallbacks)
  48208. {
  48209. ma_audio_buffer_config config;
  48210. MA_ZERO_OBJECT(&config);
  48211. config.format = format;
  48212. config.channels = channels;
  48213. config.sampleRate = 0; /* TODO: Version 0.12. Set this to sampleRate. */
  48214. config.sizeInFrames = sizeInFrames;
  48215. config.pData = pData;
  48216. ma_allocation_callbacks_init_copy(&config.allocationCallbacks, pAllocationCallbacks);
  48217. return config;
  48218. }
  48219. static ma_result ma_audio_buffer_init_ex(const ma_audio_buffer_config* pConfig, ma_bool32 doCopy, ma_audio_buffer* pAudioBuffer)
  48220. {
  48221. ma_result result;
  48222. if (pAudioBuffer == NULL) {
  48223. return MA_INVALID_ARGS;
  48224. }
  48225. MA_ZERO_MEMORY(pAudioBuffer, sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData)); /* Safety. Don't overwrite the extra data. */
  48226. if (pConfig == NULL) {
  48227. return MA_INVALID_ARGS;
  48228. }
  48229. if (pConfig->sizeInFrames == 0) {
  48230. return MA_INVALID_ARGS; /* Not allowing buffer sizes of 0 frames. */
  48231. }
  48232. result = ma_audio_buffer_ref_init(pConfig->format, pConfig->channels, NULL, 0, &pAudioBuffer->ref);
  48233. if (result != MA_SUCCESS) {
  48234. return result;
  48235. }
  48236. /* TODO: Version 0.12. Set this in ma_audio_buffer_ref_init() instead of here. */
  48237. pAudioBuffer->ref.sampleRate = pConfig->sampleRate;
  48238. ma_allocation_callbacks_init_copy(&pAudioBuffer->allocationCallbacks, &pConfig->allocationCallbacks);
  48239. if (doCopy) {
  48240. ma_uint64 allocationSizeInBytes;
  48241. void* pData;
  48242. allocationSizeInBytes = pConfig->sizeInFrames * ma_get_bytes_per_frame(pConfig->format, pConfig->channels);
  48243. if (allocationSizeInBytes > MA_SIZE_MAX) {
  48244. return MA_OUT_OF_MEMORY; /* Too big. */
  48245. }
  48246. pData = ma_malloc((size_t)allocationSizeInBytes, &pAudioBuffer->allocationCallbacks); /* Safe cast to size_t. */
  48247. if (pData == NULL) {
  48248. return MA_OUT_OF_MEMORY;
  48249. }
  48250. if (pConfig->pData != NULL) {
  48251. ma_copy_pcm_frames(pData, pConfig->pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  48252. } else {
  48253. ma_silence_pcm_frames(pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  48254. }
  48255. ma_audio_buffer_ref_set_data(&pAudioBuffer->ref, pData, pConfig->sizeInFrames);
  48256. pAudioBuffer->ownsData = MA_TRUE;
  48257. } else {
  48258. ma_audio_buffer_ref_set_data(&pAudioBuffer->ref, pConfig->pData, pConfig->sizeInFrames);
  48259. pAudioBuffer->ownsData = MA_FALSE;
  48260. }
  48261. return MA_SUCCESS;
  48262. }
  48263. static void ma_audio_buffer_uninit_ex(ma_audio_buffer* pAudioBuffer, ma_bool32 doFree)
  48264. {
  48265. if (pAudioBuffer == NULL) {
  48266. return;
  48267. }
  48268. if (pAudioBuffer->ownsData && pAudioBuffer->ref.pData != &pAudioBuffer->_pExtraData[0]) {
  48269. ma_free((void*)pAudioBuffer->ref.pData, &pAudioBuffer->allocationCallbacks); /* Naugty const cast, but OK in this case since we've guarded it with the ownsData check. */
  48270. }
  48271. if (doFree) {
  48272. ma_free(pAudioBuffer, &pAudioBuffer->allocationCallbacks);
  48273. }
  48274. ma_audio_buffer_ref_uninit(&pAudioBuffer->ref);
  48275. }
  48276. MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer)
  48277. {
  48278. return ma_audio_buffer_init_ex(pConfig, MA_FALSE, pAudioBuffer);
  48279. }
  48280. MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer)
  48281. {
  48282. return ma_audio_buffer_init_ex(pConfig, MA_TRUE, pAudioBuffer);
  48283. }
  48284. MA_API ma_result ma_audio_buffer_alloc_and_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer** ppAudioBuffer)
  48285. {
  48286. ma_result result;
  48287. ma_audio_buffer* pAudioBuffer;
  48288. ma_audio_buffer_config innerConfig; /* We'll be making some changes to the config, so need to make a copy. */
  48289. ma_uint64 allocationSizeInBytes;
  48290. if (ppAudioBuffer == NULL) {
  48291. return MA_INVALID_ARGS;
  48292. }
  48293. *ppAudioBuffer = NULL; /* Safety. */
  48294. if (pConfig == NULL) {
  48295. return MA_INVALID_ARGS;
  48296. }
  48297. innerConfig = *pConfig;
  48298. ma_allocation_callbacks_init_copy(&innerConfig.allocationCallbacks, &pConfig->allocationCallbacks);
  48299. allocationSizeInBytes = sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData) + (pConfig->sizeInFrames * ma_get_bytes_per_frame(pConfig->format, pConfig->channels));
  48300. if (allocationSizeInBytes > MA_SIZE_MAX) {
  48301. return MA_OUT_OF_MEMORY; /* Too big. */
  48302. }
  48303. pAudioBuffer = (ma_audio_buffer*)ma_malloc((size_t)allocationSizeInBytes, &innerConfig.allocationCallbacks); /* Safe cast to size_t. */
  48304. if (pAudioBuffer == NULL) {
  48305. return MA_OUT_OF_MEMORY;
  48306. }
  48307. if (pConfig->pData != NULL) {
  48308. ma_copy_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  48309. } else {
  48310. ma_silence_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  48311. }
  48312. innerConfig.pData = &pAudioBuffer->_pExtraData[0];
  48313. result = ma_audio_buffer_init_ex(&innerConfig, MA_FALSE, pAudioBuffer);
  48314. if (result != MA_SUCCESS) {
  48315. ma_free(pAudioBuffer, &innerConfig.allocationCallbacks);
  48316. return result;
  48317. }
  48318. *ppAudioBuffer = pAudioBuffer;
  48319. return MA_SUCCESS;
  48320. }
  48321. MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer)
  48322. {
  48323. ma_audio_buffer_uninit_ex(pAudioBuffer, MA_FALSE);
  48324. }
  48325. MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer)
  48326. {
  48327. ma_audio_buffer_uninit_ex(pAudioBuffer, MA_TRUE);
  48328. }
  48329. MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop)
  48330. {
  48331. if (pAudioBuffer == NULL) {
  48332. return 0;
  48333. }
  48334. return ma_audio_buffer_ref_read_pcm_frames(&pAudioBuffer->ref, pFramesOut, frameCount, loop);
  48335. }
  48336. MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex)
  48337. {
  48338. if (pAudioBuffer == NULL) {
  48339. return MA_INVALID_ARGS;
  48340. }
  48341. return ma_audio_buffer_ref_seek_to_pcm_frame(&pAudioBuffer->ref, frameIndex);
  48342. }
  48343. MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount)
  48344. {
  48345. if (ppFramesOut != NULL) {
  48346. *ppFramesOut = NULL; /* Safety. */
  48347. }
  48348. if (pAudioBuffer == NULL) {
  48349. if (pFrameCount != NULL) {
  48350. *pFrameCount = 0;
  48351. }
  48352. return MA_INVALID_ARGS;
  48353. }
  48354. return ma_audio_buffer_ref_map(&pAudioBuffer->ref, ppFramesOut, pFrameCount);
  48355. }
  48356. MA_API ma_result ma_audio_buffer_unmap(ma_audio_buffer* pAudioBuffer, ma_uint64 frameCount)
  48357. {
  48358. if (pAudioBuffer == NULL) {
  48359. return MA_INVALID_ARGS;
  48360. }
  48361. return ma_audio_buffer_ref_unmap(&pAudioBuffer->ref, frameCount);
  48362. }
  48363. MA_API ma_bool32 ma_audio_buffer_at_end(const ma_audio_buffer* pAudioBuffer)
  48364. {
  48365. if (pAudioBuffer == NULL) {
  48366. return MA_FALSE;
  48367. }
  48368. return ma_audio_buffer_ref_at_end(&pAudioBuffer->ref);
  48369. }
  48370. MA_API ma_result ma_audio_buffer_get_cursor_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pCursor)
  48371. {
  48372. if (pAudioBuffer == NULL) {
  48373. return MA_INVALID_ARGS;
  48374. }
  48375. return ma_audio_buffer_ref_get_cursor_in_pcm_frames(&pAudioBuffer->ref, pCursor);
  48376. }
  48377. MA_API ma_result ma_audio_buffer_get_length_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pLength)
  48378. {
  48379. if (pAudioBuffer == NULL) {
  48380. return MA_INVALID_ARGS;
  48381. }
  48382. return ma_audio_buffer_ref_get_length_in_pcm_frames(&pAudioBuffer->ref, pLength);
  48383. }
  48384. MA_API ma_result ma_audio_buffer_get_available_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames)
  48385. {
  48386. if (pAvailableFrames == NULL) {
  48387. return MA_INVALID_ARGS;
  48388. }
  48389. *pAvailableFrames = 0;
  48390. if (pAudioBuffer == NULL) {
  48391. return MA_INVALID_ARGS;
  48392. }
  48393. return ma_audio_buffer_ref_get_available_frames(&pAudioBuffer->ref, pAvailableFrames);
  48394. }
  48395. MA_API ma_result ma_paged_audio_buffer_data_init(ma_format format, ma_uint32 channels, ma_paged_audio_buffer_data* pData)
  48396. {
  48397. if (pData == NULL) {
  48398. return MA_INVALID_ARGS;
  48399. }
  48400. MA_ZERO_OBJECT(pData);
  48401. pData->format = format;
  48402. pData->channels = channels;
  48403. pData->pTail = &pData->head;
  48404. return MA_SUCCESS;
  48405. }
  48406. MA_API void ma_paged_audio_buffer_data_uninit(ma_paged_audio_buffer_data* pData, const ma_allocation_callbacks* pAllocationCallbacks)
  48407. {
  48408. ma_paged_audio_buffer_page* pPage;
  48409. if (pData == NULL) {
  48410. return;
  48411. }
  48412. /* All pages need to be freed. */
  48413. pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pData->head.pNext);
  48414. while (pPage != NULL) {
  48415. ma_paged_audio_buffer_page* pNext = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pPage->pNext);
  48416. ma_free(pPage, pAllocationCallbacks);
  48417. pPage = pNext;
  48418. }
  48419. }
  48420. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_head(ma_paged_audio_buffer_data* pData)
  48421. {
  48422. if (pData == NULL) {
  48423. return NULL;
  48424. }
  48425. return &pData->head;
  48426. }
  48427. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_tail(ma_paged_audio_buffer_data* pData)
  48428. {
  48429. if (pData == NULL) {
  48430. return NULL;
  48431. }
  48432. return pData->pTail;
  48433. }
  48434. MA_API ma_result ma_paged_audio_buffer_data_get_length_in_pcm_frames(ma_paged_audio_buffer_data* pData, ma_uint64* pLength)
  48435. {
  48436. ma_paged_audio_buffer_page* pPage;
  48437. if (pLength == NULL) {
  48438. return MA_INVALID_ARGS;
  48439. }
  48440. *pLength = 0;
  48441. if (pData == NULL) {
  48442. return MA_INVALID_ARGS;
  48443. }
  48444. /* Calculate the length from the linked list. */
  48445. for (pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pData->head.pNext); pPage != NULL; pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pPage->pNext)) {
  48446. *pLength += pPage->sizeInFrames;
  48447. }
  48448. return MA_SUCCESS;
  48449. }
  48450. MA_API ma_result ma_paged_audio_buffer_data_allocate_page(ma_paged_audio_buffer_data* pData, ma_uint64 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks, ma_paged_audio_buffer_page** ppPage)
  48451. {
  48452. ma_paged_audio_buffer_page* pPage;
  48453. ma_uint64 allocationSize;
  48454. if (ppPage == NULL) {
  48455. return MA_INVALID_ARGS;
  48456. }
  48457. *ppPage = NULL;
  48458. if (pData == NULL) {
  48459. return MA_INVALID_ARGS;
  48460. }
  48461. allocationSize = sizeof(*pPage) + (pageSizeInFrames * ma_get_bytes_per_frame(pData->format, pData->channels));
  48462. if (allocationSize > MA_SIZE_MAX) {
  48463. return MA_OUT_OF_MEMORY; /* Too big. */
  48464. }
  48465. pPage = (ma_paged_audio_buffer_page*)ma_malloc((size_t)allocationSize, pAllocationCallbacks); /* Safe cast to size_t. */
  48466. if (pPage == NULL) {
  48467. return MA_OUT_OF_MEMORY;
  48468. }
  48469. pPage->pNext = NULL;
  48470. pPage->sizeInFrames = pageSizeInFrames;
  48471. if (pInitialData != NULL) {
  48472. ma_copy_pcm_frames(pPage->pAudioData, pInitialData, pageSizeInFrames, pData->format, pData->channels);
  48473. }
  48474. *ppPage = pPage;
  48475. return MA_SUCCESS;
  48476. }
  48477. MA_API ma_result ma_paged_audio_buffer_data_free_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage, const ma_allocation_callbacks* pAllocationCallbacks)
  48478. {
  48479. if (pData == NULL || pPage == NULL) {
  48480. return MA_INVALID_ARGS;
  48481. }
  48482. /* It's assumed the page is not attached to the list. */
  48483. ma_free(pPage, pAllocationCallbacks);
  48484. return MA_SUCCESS;
  48485. }
  48486. MA_API ma_result ma_paged_audio_buffer_data_append_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage)
  48487. {
  48488. if (pData == NULL || pPage == NULL) {
  48489. return MA_INVALID_ARGS;
  48490. }
  48491. /* This function assumes the page has been filled with audio data by this point. As soon as we append, the page will be available for reading. */
  48492. /* First thing to do is update the tail. */
  48493. for (;;) {
  48494. ma_paged_audio_buffer_page* pOldTail = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pData->pTail);
  48495. ma_paged_audio_buffer_page* pNewTail = pPage;
  48496. if (c89atomic_compare_exchange_weak_ptr((volatile void**)&pData->pTail, (void**)&pOldTail, pNewTail)) {
  48497. /* Here is where we append the page to the list. After this, the page is attached to the list and ready to be read from. */
  48498. c89atomic_exchange_ptr(&pOldTail->pNext, pPage);
  48499. break; /* Done. */
  48500. }
  48501. }
  48502. return MA_SUCCESS;
  48503. }
  48504. MA_API ma_result ma_paged_audio_buffer_data_allocate_and_append_page(ma_paged_audio_buffer_data* pData, ma_uint32 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks)
  48505. {
  48506. ma_result result;
  48507. ma_paged_audio_buffer_page* pPage;
  48508. result = ma_paged_audio_buffer_data_allocate_page(pData, pageSizeInFrames, pInitialData, pAllocationCallbacks, &pPage);
  48509. if (result != MA_SUCCESS) {
  48510. return result;
  48511. }
  48512. return ma_paged_audio_buffer_data_append_page(pData, pPage); /* <-- Should never fail. */
  48513. }
  48514. MA_API ma_paged_audio_buffer_config ma_paged_audio_buffer_config_init(ma_paged_audio_buffer_data* pData)
  48515. {
  48516. ma_paged_audio_buffer_config config;
  48517. MA_ZERO_OBJECT(&config);
  48518. config.pData = pData;
  48519. return config;
  48520. }
  48521. static ma_result ma_paged_audio_buffer__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  48522. {
  48523. return ma_paged_audio_buffer_read_pcm_frames((ma_paged_audio_buffer*)pDataSource, pFramesOut, frameCount, pFramesRead);
  48524. }
  48525. static ma_result ma_paged_audio_buffer__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  48526. {
  48527. return ma_paged_audio_buffer_seek_to_pcm_frame((ma_paged_audio_buffer*)pDataSource, frameIndex);
  48528. }
  48529. static ma_result ma_paged_audio_buffer__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  48530. {
  48531. ma_paged_audio_buffer* pPagedAudioBuffer = (ma_paged_audio_buffer*)pDataSource;
  48532. *pFormat = pPagedAudioBuffer->pData->format;
  48533. *pChannels = pPagedAudioBuffer->pData->channels;
  48534. *pSampleRate = 0; /* There is no notion of a sample rate with audio buffers. */
  48535. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pPagedAudioBuffer->pData->channels);
  48536. return MA_SUCCESS;
  48537. }
  48538. static ma_result ma_paged_audio_buffer__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  48539. {
  48540. return ma_paged_audio_buffer_get_cursor_in_pcm_frames((ma_paged_audio_buffer*)pDataSource, pCursor);
  48541. }
  48542. static ma_result ma_paged_audio_buffer__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  48543. {
  48544. return ma_paged_audio_buffer_get_length_in_pcm_frames((ma_paged_audio_buffer*)pDataSource, pLength);
  48545. }
  48546. static ma_data_source_vtable g_ma_paged_audio_buffer_data_source_vtable =
  48547. {
  48548. ma_paged_audio_buffer__data_source_on_read,
  48549. ma_paged_audio_buffer__data_source_on_seek,
  48550. ma_paged_audio_buffer__data_source_on_get_data_format,
  48551. ma_paged_audio_buffer__data_source_on_get_cursor,
  48552. ma_paged_audio_buffer__data_source_on_get_length,
  48553. NULL, /* onSetLooping */
  48554. 0
  48555. };
  48556. MA_API ma_result ma_paged_audio_buffer_init(const ma_paged_audio_buffer_config* pConfig, ma_paged_audio_buffer* pPagedAudioBuffer)
  48557. {
  48558. ma_result result;
  48559. ma_data_source_config dataSourceConfig;
  48560. if (pPagedAudioBuffer == NULL) {
  48561. return MA_INVALID_ARGS;
  48562. }
  48563. MA_ZERO_OBJECT(pPagedAudioBuffer);
  48564. /* A config is required for the format and channel count. */
  48565. if (pConfig == NULL) {
  48566. return MA_INVALID_ARGS;
  48567. }
  48568. if (pConfig->pData == NULL) {
  48569. return MA_INVALID_ARGS; /* No underlying data specified. */
  48570. }
  48571. dataSourceConfig = ma_data_source_config_init();
  48572. dataSourceConfig.vtable = &g_ma_paged_audio_buffer_data_source_vtable;
  48573. result = ma_data_source_init(&dataSourceConfig, &pPagedAudioBuffer->ds);
  48574. if (result != MA_SUCCESS) {
  48575. return result;
  48576. }
  48577. pPagedAudioBuffer->pData = pConfig->pData;
  48578. pPagedAudioBuffer->pCurrent = ma_paged_audio_buffer_data_get_head(pConfig->pData);
  48579. pPagedAudioBuffer->relativeCursor = 0;
  48580. pPagedAudioBuffer->absoluteCursor = 0;
  48581. return MA_SUCCESS;
  48582. }
  48583. MA_API void ma_paged_audio_buffer_uninit(ma_paged_audio_buffer* pPagedAudioBuffer)
  48584. {
  48585. if (pPagedAudioBuffer == NULL) {
  48586. return;
  48587. }
  48588. /* Nothing to do. The data needs to be deleted separately. */
  48589. }
  48590. MA_API ma_result ma_paged_audio_buffer_read_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  48591. {
  48592. ma_result result = MA_SUCCESS;
  48593. ma_uint64 totalFramesRead = 0;
  48594. ma_format format;
  48595. ma_uint32 channels;
  48596. if (pPagedAudioBuffer == NULL) {
  48597. return MA_INVALID_ARGS;
  48598. }
  48599. format = pPagedAudioBuffer->pData->format;
  48600. channels = pPagedAudioBuffer->pData->channels;
  48601. while (totalFramesRead < frameCount) {
  48602. /* Read from the current page. The buffer should never be in a state where this is NULL. */
  48603. ma_uint64 framesRemainingInCurrentPage;
  48604. ma_uint64 framesRemainingToRead = frameCount - totalFramesRead;
  48605. ma_uint64 framesToReadThisIteration;
  48606. MA_ASSERT(pPagedAudioBuffer->pCurrent != NULL);
  48607. framesRemainingInCurrentPage = pPagedAudioBuffer->pCurrent->sizeInFrames - pPagedAudioBuffer->relativeCursor;
  48608. framesToReadThisIteration = ma_min(framesRemainingInCurrentPage, framesRemainingToRead);
  48609. ma_copy_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, format, channels), ma_offset_pcm_frames_ptr(pPagedAudioBuffer->pCurrent->pAudioData, pPagedAudioBuffer->relativeCursor, format, channels), framesToReadThisIteration, format, channels);
  48610. totalFramesRead += framesToReadThisIteration;
  48611. pPagedAudioBuffer->absoluteCursor += framesToReadThisIteration;
  48612. pPagedAudioBuffer->relativeCursor += framesToReadThisIteration;
  48613. /* Move to the next page if necessary. If there's no more pages, we need to return MA_AT_END. */
  48614. MA_ASSERT(pPagedAudioBuffer->relativeCursor <= pPagedAudioBuffer->pCurrent->sizeInFrames);
  48615. if (pPagedAudioBuffer->relativeCursor == pPagedAudioBuffer->pCurrent->sizeInFrames) {
  48616. /* We reached the end of the page. Need to move to the next. If there's no more pages, we're done. */
  48617. ma_paged_audio_buffer_page* pNext = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pPagedAudioBuffer->pCurrent->pNext);
  48618. if (pNext == NULL) {
  48619. result = MA_AT_END;
  48620. break; /* We've reached the end. */
  48621. } else {
  48622. pPagedAudioBuffer->pCurrent = pNext;
  48623. pPagedAudioBuffer->relativeCursor = 0;
  48624. }
  48625. }
  48626. }
  48627. if (pFramesRead != NULL) {
  48628. *pFramesRead = totalFramesRead;
  48629. }
  48630. return result;
  48631. }
  48632. MA_API ma_result ma_paged_audio_buffer_seek_to_pcm_frame(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64 frameIndex)
  48633. {
  48634. if (pPagedAudioBuffer == NULL) {
  48635. return MA_INVALID_ARGS;
  48636. }
  48637. if (frameIndex == pPagedAudioBuffer->absoluteCursor) {
  48638. return MA_SUCCESS; /* Nothing to do. */
  48639. }
  48640. if (frameIndex < pPagedAudioBuffer->absoluteCursor) {
  48641. /* Moving backwards. Need to move the cursor back to the start, and then move forward. */
  48642. pPagedAudioBuffer->pCurrent = ma_paged_audio_buffer_data_get_head(pPagedAudioBuffer->pData);
  48643. pPagedAudioBuffer->absoluteCursor = 0;
  48644. pPagedAudioBuffer->relativeCursor = 0;
  48645. /* Fall through to the forward seeking section below. */
  48646. }
  48647. if (frameIndex > pPagedAudioBuffer->absoluteCursor) {
  48648. /* Moving forward. */
  48649. ma_paged_audio_buffer_page* pPage;
  48650. ma_uint64 runningCursor = 0;
  48651. for (pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&ma_paged_audio_buffer_data_get_head(pPagedAudioBuffer->pData)->pNext); pPage != NULL; pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pPage->pNext)) {
  48652. ma_uint64 pageRangeBeg = runningCursor;
  48653. ma_uint64 pageRangeEnd = pageRangeBeg + pPage->sizeInFrames;
  48654. if (frameIndex >= pageRangeBeg) {
  48655. if (frameIndex < pageRangeEnd || (frameIndex == pageRangeEnd && pPage == (ma_paged_audio_buffer_page*)c89atomic_load_ptr(ma_paged_audio_buffer_data_get_tail(pPagedAudioBuffer->pData)))) { /* A small edge case - allow seeking to the very end of the buffer. */
  48656. /* We found the page. */
  48657. pPagedAudioBuffer->pCurrent = pPage;
  48658. pPagedAudioBuffer->absoluteCursor = frameIndex;
  48659. pPagedAudioBuffer->relativeCursor = frameIndex - pageRangeBeg;
  48660. return MA_SUCCESS;
  48661. }
  48662. }
  48663. runningCursor = pageRangeEnd;
  48664. }
  48665. /* Getting here means we tried seeking too far forward. Don't change any state. */
  48666. return MA_BAD_SEEK;
  48667. }
  48668. return MA_SUCCESS;
  48669. }
  48670. MA_API ma_result ma_paged_audio_buffer_get_cursor_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pCursor)
  48671. {
  48672. if (pCursor == NULL) {
  48673. return MA_INVALID_ARGS;
  48674. }
  48675. *pCursor = 0; /* Safety. */
  48676. if (pPagedAudioBuffer == NULL) {
  48677. return MA_INVALID_ARGS;
  48678. }
  48679. *pCursor = pPagedAudioBuffer->absoluteCursor;
  48680. return MA_SUCCESS;
  48681. }
  48682. MA_API ma_result ma_paged_audio_buffer_get_length_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pLength)
  48683. {
  48684. return ma_paged_audio_buffer_data_get_length_in_pcm_frames(pPagedAudioBuffer->pData, pLength);
  48685. }
  48686. /**************************************************************************************************************************************************************
  48687. VFS
  48688. **************************************************************************************************************************************************************/
  48689. MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  48690. {
  48691. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48692. if (pFile == NULL) {
  48693. return MA_INVALID_ARGS;
  48694. }
  48695. *pFile = NULL;
  48696. if (pVFS == NULL || pFilePath == NULL || openMode == 0) {
  48697. return MA_INVALID_ARGS;
  48698. }
  48699. if (pCallbacks->onOpen == NULL) {
  48700. return MA_NOT_IMPLEMENTED;
  48701. }
  48702. return pCallbacks->onOpen(pVFS, pFilePath, openMode, pFile);
  48703. }
  48704. MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  48705. {
  48706. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48707. if (pFile == NULL) {
  48708. return MA_INVALID_ARGS;
  48709. }
  48710. *pFile = NULL;
  48711. if (pVFS == NULL || pFilePath == NULL || openMode == 0) {
  48712. return MA_INVALID_ARGS;
  48713. }
  48714. if (pCallbacks->onOpenW == NULL) {
  48715. return MA_NOT_IMPLEMENTED;
  48716. }
  48717. return pCallbacks->onOpenW(pVFS, pFilePath, openMode, pFile);
  48718. }
  48719. MA_API ma_result ma_vfs_close(ma_vfs* pVFS, ma_vfs_file file)
  48720. {
  48721. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48722. if (pVFS == NULL || file == NULL) {
  48723. return MA_INVALID_ARGS;
  48724. }
  48725. if (pCallbacks->onClose == NULL) {
  48726. return MA_NOT_IMPLEMENTED;
  48727. }
  48728. return pCallbacks->onClose(pVFS, file);
  48729. }
  48730. MA_API ma_result ma_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  48731. {
  48732. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48733. ma_result result;
  48734. size_t bytesRead = 0;
  48735. if (pBytesRead != NULL) {
  48736. *pBytesRead = 0;
  48737. }
  48738. if (pVFS == NULL || file == NULL || pDst == NULL) {
  48739. return MA_INVALID_ARGS;
  48740. }
  48741. if (pCallbacks->onRead == NULL) {
  48742. return MA_NOT_IMPLEMENTED;
  48743. }
  48744. result = pCallbacks->onRead(pVFS, file, pDst, sizeInBytes, &bytesRead);
  48745. if (pBytesRead != NULL) {
  48746. *pBytesRead = bytesRead;
  48747. }
  48748. if (result == MA_SUCCESS && bytesRead == 0 && sizeInBytes > 0) {
  48749. result = MA_AT_END;
  48750. }
  48751. return result;
  48752. }
  48753. MA_API ma_result ma_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  48754. {
  48755. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48756. if (pBytesWritten != NULL) {
  48757. *pBytesWritten = 0;
  48758. }
  48759. if (pVFS == NULL || file == NULL || pSrc == NULL) {
  48760. return MA_INVALID_ARGS;
  48761. }
  48762. if (pCallbacks->onWrite == NULL) {
  48763. return MA_NOT_IMPLEMENTED;
  48764. }
  48765. return pCallbacks->onWrite(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  48766. }
  48767. MA_API ma_result ma_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  48768. {
  48769. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48770. if (pVFS == NULL || file == NULL) {
  48771. return MA_INVALID_ARGS;
  48772. }
  48773. if (pCallbacks->onSeek == NULL) {
  48774. return MA_NOT_IMPLEMENTED;
  48775. }
  48776. return pCallbacks->onSeek(pVFS, file, offset, origin);
  48777. }
  48778. MA_API ma_result ma_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  48779. {
  48780. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48781. if (pCursor == NULL) {
  48782. return MA_INVALID_ARGS;
  48783. }
  48784. *pCursor = 0;
  48785. if (pVFS == NULL || file == NULL) {
  48786. return MA_INVALID_ARGS;
  48787. }
  48788. if (pCallbacks->onTell == NULL) {
  48789. return MA_NOT_IMPLEMENTED;
  48790. }
  48791. return pCallbacks->onTell(pVFS, file, pCursor);
  48792. }
  48793. MA_API ma_result ma_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  48794. {
  48795. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48796. if (pInfo == NULL) {
  48797. return MA_INVALID_ARGS;
  48798. }
  48799. MA_ZERO_OBJECT(pInfo);
  48800. if (pVFS == NULL || file == NULL) {
  48801. return MA_INVALID_ARGS;
  48802. }
  48803. if (pCallbacks->onInfo == NULL) {
  48804. return MA_NOT_IMPLEMENTED;
  48805. }
  48806. return pCallbacks->onInfo(pVFS, file, pInfo);
  48807. }
  48808. static ma_result ma_vfs_open_and_read_file_ex(ma_vfs* pVFS, const char* pFilePath, const wchar_t* pFilePathW, void** ppData, size_t* pSize, const ma_allocation_callbacks* pAllocationCallbacks)
  48809. {
  48810. ma_result result;
  48811. ma_vfs_file file;
  48812. ma_file_info info;
  48813. void* pData;
  48814. size_t bytesRead;
  48815. if (ppData != NULL) {
  48816. *ppData = NULL;
  48817. }
  48818. if (pSize != NULL) {
  48819. *pSize = 0;
  48820. }
  48821. if (ppData == NULL) {
  48822. return MA_INVALID_ARGS;
  48823. }
  48824. if (pFilePath != NULL) {
  48825. result = ma_vfs_open(pVFS, pFilePath, MA_OPEN_MODE_READ, &file);
  48826. } else {
  48827. result = ma_vfs_open_w(pVFS, pFilePathW, MA_OPEN_MODE_READ, &file);
  48828. }
  48829. if (result != MA_SUCCESS) {
  48830. return result;
  48831. }
  48832. result = ma_vfs_info(pVFS, file, &info);
  48833. if (result != MA_SUCCESS) {
  48834. ma_vfs_close(pVFS, file);
  48835. return result;
  48836. }
  48837. if (info.sizeInBytes > MA_SIZE_MAX) {
  48838. ma_vfs_close(pVFS, file);
  48839. return MA_TOO_BIG;
  48840. }
  48841. pData = ma_malloc((size_t)info.sizeInBytes, pAllocationCallbacks); /* Safe cast. */
  48842. if (pData == NULL) {
  48843. ma_vfs_close(pVFS, file);
  48844. return result;
  48845. }
  48846. result = ma_vfs_read(pVFS, file, pData, (size_t)info.sizeInBytes, &bytesRead); /* Safe cast. */
  48847. ma_vfs_close(pVFS, file);
  48848. if (result != MA_SUCCESS) {
  48849. ma_free(pData, pAllocationCallbacks);
  48850. return result;
  48851. }
  48852. if (pSize != NULL) {
  48853. *pSize = bytesRead;
  48854. }
  48855. MA_ASSERT(ppData != NULL);
  48856. *ppData = pData;
  48857. return MA_SUCCESS;
  48858. }
  48859. MA_API ma_result ma_vfs_open_and_read_file(ma_vfs* pVFS, const char* pFilePath, void** ppData, size_t* pSize, const ma_allocation_callbacks* pAllocationCallbacks)
  48860. {
  48861. return ma_vfs_open_and_read_file_ex(pVFS, pFilePath, NULL, ppData, pSize, pAllocationCallbacks);
  48862. }
  48863. MA_API ma_result ma_vfs_open_and_read_file_w(ma_vfs* pVFS, const wchar_t* pFilePath, void** ppData, size_t* pSize, const ma_allocation_callbacks* pAllocationCallbacks)
  48864. {
  48865. return ma_vfs_open_and_read_file_ex(pVFS, NULL, pFilePath, ppData, pSize, pAllocationCallbacks);
  48866. }
  48867. #if !defined(MA_USE_WIN32_FILEIO) && (defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO) && !defined(MA_POSIX))
  48868. #define MA_USE_WIN32_FILEIO
  48869. #endif
  48870. #if defined(MA_USE_WIN32_FILEIO)
  48871. static void ma_default_vfs__get_open_settings_win32(ma_uint32 openMode, DWORD* pDesiredAccess, DWORD* pShareMode, DWORD* pCreationDisposition)
  48872. {
  48873. *pDesiredAccess = 0;
  48874. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  48875. *pDesiredAccess |= GENERIC_READ;
  48876. }
  48877. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  48878. *pDesiredAccess |= GENERIC_WRITE;
  48879. }
  48880. *pShareMode = 0;
  48881. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  48882. *pShareMode |= FILE_SHARE_READ;
  48883. }
  48884. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  48885. *pCreationDisposition = CREATE_ALWAYS; /* Opening in write mode. Truncate. */
  48886. } else {
  48887. *pCreationDisposition = OPEN_EXISTING; /* Opening in read mode. File must exist. */
  48888. }
  48889. }
  48890. static ma_result ma_default_vfs_open__win32(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  48891. {
  48892. HANDLE hFile;
  48893. DWORD dwDesiredAccess;
  48894. DWORD dwShareMode;
  48895. DWORD dwCreationDisposition;
  48896. (void)pVFS;
  48897. ma_default_vfs__get_open_settings_win32(openMode, &dwDesiredAccess, &dwShareMode, &dwCreationDisposition);
  48898. hFile = CreateFileA(pFilePath, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
  48899. if (hFile == INVALID_HANDLE_VALUE) {
  48900. return ma_result_from_GetLastError(GetLastError());
  48901. }
  48902. *pFile = hFile;
  48903. return MA_SUCCESS;
  48904. }
  48905. static ma_result ma_default_vfs_open_w__win32(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  48906. {
  48907. HANDLE hFile;
  48908. DWORD dwDesiredAccess;
  48909. DWORD dwShareMode;
  48910. DWORD dwCreationDisposition;
  48911. (void)pVFS;
  48912. ma_default_vfs__get_open_settings_win32(openMode, &dwDesiredAccess, &dwShareMode, &dwCreationDisposition);
  48913. hFile = CreateFileW(pFilePath, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
  48914. if (hFile == INVALID_HANDLE_VALUE) {
  48915. return ma_result_from_GetLastError(GetLastError());
  48916. }
  48917. *pFile = hFile;
  48918. return MA_SUCCESS;
  48919. }
  48920. static ma_result ma_default_vfs_close__win32(ma_vfs* pVFS, ma_vfs_file file)
  48921. {
  48922. (void)pVFS;
  48923. if (CloseHandle((HANDLE)file) == 0) {
  48924. return ma_result_from_GetLastError(GetLastError());
  48925. }
  48926. return MA_SUCCESS;
  48927. }
  48928. static ma_result ma_default_vfs_read__win32(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  48929. {
  48930. ma_result result = MA_SUCCESS;
  48931. size_t totalBytesRead;
  48932. (void)pVFS;
  48933. totalBytesRead = 0;
  48934. while (totalBytesRead < sizeInBytes) {
  48935. size_t bytesRemaining;
  48936. DWORD bytesToRead;
  48937. DWORD bytesRead;
  48938. BOOL readResult;
  48939. bytesRemaining = sizeInBytes - totalBytesRead;
  48940. if (bytesRemaining >= 0xFFFFFFFF) {
  48941. bytesToRead = 0xFFFFFFFF;
  48942. } else {
  48943. bytesToRead = (DWORD)bytesRemaining;
  48944. }
  48945. readResult = ReadFile((HANDLE)file, ma_offset_ptr(pDst, totalBytesRead), bytesToRead, &bytesRead, NULL);
  48946. if (readResult == 1 && bytesRead == 0) {
  48947. result = MA_AT_END;
  48948. break; /* EOF */
  48949. }
  48950. totalBytesRead += bytesRead;
  48951. if (bytesRead < bytesToRead) {
  48952. break; /* EOF */
  48953. }
  48954. if (readResult == 0) {
  48955. result = ma_result_from_GetLastError(GetLastError());
  48956. break;
  48957. }
  48958. }
  48959. if (pBytesRead != NULL) {
  48960. *pBytesRead = totalBytesRead;
  48961. }
  48962. return result;
  48963. }
  48964. static ma_result ma_default_vfs_write__win32(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  48965. {
  48966. ma_result result = MA_SUCCESS;
  48967. size_t totalBytesWritten;
  48968. (void)pVFS;
  48969. totalBytesWritten = 0;
  48970. while (totalBytesWritten < sizeInBytes) {
  48971. size_t bytesRemaining;
  48972. DWORD bytesToWrite;
  48973. DWORD bytesWritten;
  48974. BOOL writeResult;
  48975. bytesRemaining = sizeInBytes - totalBytesWritten;
  48976. if (bytesRemaining >= 0xFFFFFFFF) {
  48977. bytesToWrite = 0xFFFFFFFF;
  48978. } else {
  48979. bytesToWrite = (DWORD)bytesRemaining;
  48980. }
  48981. writeResult = WriteFile((HANDLE)file, ma_offset_ptr(pSrc, totalBytesWritten), bytesToWrite, &bytesWritten, NULL);
  48982. totalBytesWritten += bytesWritten;
  48983. if (writeResult == 0) {
  48984. result = ma_result_from_GetLastError(GetLastError());
  48985. break;
  48986. }
  48987. }
  48988. if (pBytesWritten != NULL) {
  48989. *pBytesWritten = totalBytesWritten;
  48990. }
  48991. return result;
  48992. }
  48993. static ma_result ma_default_vfs_seek__win32(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  48994. {
  48995. LARGE_INTEGER liDistanceToMove;
  48996. DWORD dwMoveMethod;
  48997. BOOL result;
  48998. (void)pVFS;
  48999. liDistanceToMove.QuadPart = offset;
  49000. /* */ if (origin == ma_seek_origin_current) {
  49001. dwMoveMethod = FILE_CURRENT;
  49002. } else if (origin == ma_seek_origin_end) {
  49003. dwMoveMethod = FILE_END;
  49004. } else {
  49005. dwMoveMethod = FILE_BEGIN;
  49006. }
  49007. #if (defined(_MSC_VER) && _MSC_VER <= 1200) || defined(__DMC__)
  49008. /* No SetFilePointerEx() so restrict to 31 bits. */
  49009. if (origin > 0x7FFFFFFF) {
  49010. return MA_OUT_OF_RANGE;
  49011. }
  49012. result = SetFilePointer((HANDLE)file, (LONG)liDistanceToMove.QuadPart, NULL, dwMoveMethod);
  49013. #else
  49014. result = SetFilePointerEx((HANDLE)file, liDistanceToMove, NULL, dwMoveMethod);
  49015. #endif
  49016. if (result == 0) {
  49017. return ma_result_from_GetLastError(GetLastError());
  49018. }
  49019. return MA_SUCCESS;
  49020. }
  49021. static ma_result ma_default_vfs_tell__win32(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  49022. {
  49023. LARGE_INTEGER liZero;
  49024. LARGE_INTEGER liTell;
  49025. BOOL result;
  49026. #if (defined(_MSC_VER) && _MSC_VER <= 1200) || defined(__DMC__)
  49027. LONG tell;
  49028. #endif
  49029. (void)pVFS;
  49030. liZero.QuadPart = 0;
  49031. #if (defined(_MSC_VER) && _MSC_VER <= 1200) || defined(__DMC__)
  49032. result = SetFilePointer((HANDLE)file, (LONG)liZero.QuadPart, &tell, FILE_CURRENT);
  49033. liTell.QuadPart = tell;
  49034. #else
  49035. result = SetFilePointerEx((HANDLE)file, liZero, &liTell, FILE_CURRENT);
  49036. #endif
  49037. if (result == 0) {
  49038. return ma_result_from_GetLastError(GetLastError());
  49039. }
  49040. if (pCursor != NULL) {
  49041. *pCursor = liTell.QuadPart;
  49042. }
  49043. return MA_SUCCESS;
  49044. }
  49045. static ma_result ma_default_vfs_info__win32(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  49046. {
  49047. BY_HANDLE_FILE_INFORMATION fi;
  49048. BOOL result;
  49049. (void)pVFS;
  49050. result = GetFileInformationByHandle((HANDLE)file, &fi);
  49051. if (result == 0) {
  49052. return ma_result_from_GetLastError(GetLastError());
  49053. }
  49054. pInfo->sizeInBytes = ((ma_uint64)fi.nFileSizeHigh << 32) | ((ma_uint64)fi.nFileSizeLow);
  49055. return MA_SUCCESS;
  49056. }
  49057. #else
  49058. static ma_result ma_default_vfs_open__stdio(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49059. {
  49060. ma_result result;
  49061. FILE* pFileStd;
  49062. const char* pOpenModeStr;
  49063. MA_ASSERT(pFilePath != NULL);
  49064. MA_ASSERT(openMode != 0);
  49065. MA_ASSERT(pFile != NULL);
  49066. (void)pVFS;
  49067. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  49068. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  49069. pOpenModeStr = "r+";
  49070. } else {
  49071. pOpenModeStr = "rb";
  49072. }
  49073. } else {
  49074. pOpenModeStr = "wb";
  49075. }
  49076. result = ma_fopen(&pFileStd, pFilePath, pOpenModeStr);
  49077. if (result != MA_SUCCESS) {
  49078. return result;
  49079. }
  49080. *pFile = pFileStd;
  49081. return MA_SUCCESS;
  49082. }
  49083. static ma_result ma_default_vfs_open_w__stdio(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49084. {
  49085. ma_result result;
  49086. FILE* pFileStd;
  49087. const wchar_t* pOpenModeStr;
  49088. MA_ASSERT(pFilePath != NULL);
  49089. MA_ASSERT(openMode != 0);
  49090. MA_ASSERT(pFile != NULL);
  49091. (void)pVFS;
  49092. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  49093. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  49094. pOpenModeStr = L"r+";
  49095. } else {
  49096. pOpenModeStr = L"rb";
  49097. }
  49098. } else {
  49099. pOpenModeStr = L"wb";
  49100. }
  49101. result = ma_wfopen(&pFileStd, pFilePath, pOpenModeStr, (pVFS != NULL) ? &((ma_default_vfs*)pVFS)->allocationCallbacks : NULL);
  49102. if (result != MA_SUCCESS) {
  49103. return result;
  49104. }
  49105. *pFile = pFileStd;
  49106. return MA_SUCCESS;
  49107. }
  49108. static ma_result ma_default_vfs_close__stdio(ma_vfs* pVFS, ma_vfs_file file)
  49109. {
  49110. MA_ASSERT(file != NULL);
  49111. (void)pVFS;
  49112. fclose((FILE*)file);
  49113. return MA_SUCCESS;
  49114. }
  49115. static ma_result ma_default_vfs_read__stdio(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  49116. {
  49117. size_t result;
  49118. MA_ASSERT(file != NULL);
  49119. MA_ASSERT(pDst != NULL);
  49120. (void)pVFS;
  49121. result = fread(pDst, 1, sizeInBytes, (FILE*)file);
  49122. if (pBytesRead != NULL) {
  49123. *pBytesRead = result;
  49124. }
  49125. if (result != sizeInBytes) {
  49126. if (result == 0 && feof((FILE*)file)) {
  49127. return MA_AT_END;
  49128. } else {
  49129. return ma_result_from_errno(ferror((FILE*)file));
  49130. }
  49131. }
  49132. return MA_SUCCESS;
  49133. }
  49134. static ma_result ma_default_vfs_write__stdio(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  49135. {
  49136. size_t result;
  49137. MA_ASSERT(file != NULL);
  49138. MA_ASSERT(pSrc != NULL);
  49139. (void)pVFS;
  49140. result = fwrite(pSrc, 1, sizeInBytes, (FILE*)file);
  49141. if (pBytesWritten != NULL) {
  49142. *pBytesWritten = result;
  49143. }
  49144. if (result != sizeInBytes) {
  49145. return ma_result_from_errno(ferror((FILE*)file));
  49146. }
  49147. return MA_SUCCESS;
  49148. }
  49149. static ma_result ma_default_vfs_seek__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  49150. {
  49151. int result;
  49152. int whence;
  49153. MA_ASSERT(file != NULL);
  49154. (void)pVFS;
  49155. if (origin == ma_seek_origin_start) {
  49156. whence = SEEK_SET;
  49157. } else if (origin == ma_seek_origin_end) {
  49158. whence = SEEK_END;
  49159. } else {
  49160. whence = SEEK_CUR;
  49161. }
  49162. #if defined(_WIN32)
  49163. #if defined(_MSC_VER) && _MSC_VER > 1200
  49164. result = _fseeki64((FILE*)file, offset, whence);
  49165. #else
  49166. /* No _fseeki64() so restrict to 31 bits. */
  49167. if (origin > 0x7FFFFFFF) {
  49168. return MA_OUT_OF_RANGE;
  49169. }
  49170. result = fseek((FILE*)file, (int)offset, whence);
  49171. #endif
  49172. #else
  49173. result = fseek((FILE*)file, (long int)offset, whence);
  49174. #endif
  49175. if (result != 0) {
  49176. return MA_ERROR;
  49177. }
  49178. return MA_SUCCESS;
  49179. }
  49180. static ma_result ma_default_vfs_tell__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  49181. {
  49182. ma_int64 result;
  49183. MA_ASSERT(file != NULL);
  49184. MA_ASSERT(pCursor != NULL);
  49185. (void)pVFS;
  49186. #if defined(_WIN32)
  49187. #if defined(_MSC_VER) && _MSC_VER > 1200
  49188. result = _ftelli64((FILE*)file);
  49189. #else
  49190. result = ftell((FILE*)file);
  49191. #endif
  49192. #else
  49193. result = ftell((FILE*)file);
  49194. #endif
  49195. *pCursor = result;
  49196. return MA_SUCCESS;
  49197. }
  49198. #if !defined(_MSC_VER) && !((defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 1) || defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE)) && !defined(MA_BSD)
  49199. int fileno(FILE *stream);
  49200. #endif
  49201. static ma_result ma_default_vfs_info__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  49202. {
  49203. int fd;
  49204. struct stat info;
  49205. MA_ASSERT(file != NULL);
  49206. MA_ASSERT(pInfo != NULL);
  49207. (void)pVFS;
  49208. #if defined(_MSC_VER)
  49209. fd = _fileno((FILE*)file);
  49210. #else
  49211. fd = fileno((FILE*)file);
  49212. #endif
  49213. if (fstat(fd, &info) != 0) {
  49214. return ma_result_from_errno(errno);
  49215. }
  49216. pInfo->sizeInBytes = info.st_size;
  49217. return MA_SUCCESS;
  49218. }
  49219. #endif
  49220. static ma_result ma_default_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49221. {
  49222. if (pFile == NULL) {
  49223. return MA_INVALID_ARGS;
  49224. }
  49225. *pFile = NULL;
  49226. if (pFilePath == NULL || openMode == 0) {
  49227. return MA_INVALID_ARGS;
  49228. }
  49229. #if defined(MA_USE_WIN32_FILEIO)
  49230. return ma_default_vfs_open__win32(pVFS, pFilePath, openMode, pFile);
  49231. #else
  49232. return ma_default_vfs_open__stdio(pVFS, pFilePath, openMode, pFile);
  49233. #endif
  49234. }
  49235. static ma_result ma_default_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49236. {
  49237. if (pFile == NULL) {
  49238. return MA_INVALID_ARGS;
  49239. }
  49240. *pFile = NULL;
  49241. if (pFilePath == NULL || openMode == 0) {
  49242. return MA_INVALID_ARGS;
  49243. }
  49244. #if defined(MA_USE_WIN32_FILEIO)
  49245. return ma_default_vfs_open_w__win32(pVFS, pFilePath, openMode, pFile);
  49246. #else
  49247. return ma_default_vfs_open_w__stdio(pVFS, pFilePath, openMode, pFile);
  49248. #endif
  49249. }
  49250. static ma_result ma_default_vfs_close(ma_vfs* pVFS, ma_vfs_file file)
  49251. {
  49252. if (file == NULL) {
  49253. return MA_INVALID_ARGS;
  49254. }
  49255. #if defined(MA_USE_WIN32_FILEIO)
  49256. return ma_default_vfs_close__win32(pVFS, file);
  49257. #else
  49258. return ma_default_vfs_close__stdio(pVFS, file);
  49259. #endif
  49260. }
  49261. static ma_result ma_default_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  49262. {
  49263. if (pBytesRead != NULL) {
  49264. *pBytesRead = 0;
  49265. }
  49266. if (file == NULL || pDst == NULL) {
  49267. return MA_INVALID_ARGS;
  49268. }
  49269. #if defined(MA_USE_WIN32_FILEIO)
  49270. return ma_default_vfs_read__win32(pVFS, file, pDst, sizeInBytes, pBytesRead);
  49271. #else
  49272. return ma_default_vfs_read__stdio(pVFS, file, pDst, sizeInBytes, pBytesRead);
  49273. #endif
  49274. }
  49275. static ma_result ma_default_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  49276. {
  49277. if (pBytesWritten != NULL) {
  49278. *pBytesWritten = 0;
  49279. }
  49280. if (file == NULL || pSrc == NULL) {
  49281. return MA_INVALID_ARGS;
  49282. }
  49283. #if defined(MA_USE_WIN32_FILEIO)
  49284. return ma_default_vfs_write__win32(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  49285. #else
  49286. return ma_default_vfs_write__stdio(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  49287. #endif
  49288. }
  49289. static ma_result ma_default_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  49290. {
  49291. if (file == NULL) {
  49292. return MA_INVALID_ARGS;
  49293. }
  49294. #if defined(MA_USE_WIN32_FILEIO)
  49295. return ma_default_vfs_seek__win32(pVFS, file, offset, origin);
  49296. #else
  49297. return ma_default_vfs_seek__stdio(pVFS, file, offset, origin);
  49298. #endif
  49299. }
  49300. static ma_result ma_default_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  49301. {
  49302. if (pCursor == NULL) {
  49303. return MA_INVALID_ARGS;
  49304. }
  49305. *pCursor = 0;
  49306. if (file == NULL) {
  49307. return MA_INVALID_ARGS;
  49308. }
  49309. #if defined(MA_USE_WIN32_FILEIO)
  49310. return ma_default_vfs_tell__win32(pVFS, file, pCursor);
  49311. #else
  49312. return ma_default_vfs_tell__stdio(pVFS, file, pCursor);
  49313. #endif
  49314. }
  49315. static ma_result ma_default_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  49316. {
  49317. if (pInfo == NULL) {
  49318. return MA_INVALID_ARGS;
  49319. }
  49320. MA_ZERO_OBJECT(pInfo);
  49321. if (file == NULL) {
  49322. return MA_INVALID_ARGS;
  49323. }
  49324. #if defined(MA_USE_WIN32_FILEIO)
  49325. return ma_default_vfs_info__win32(pVFS, file, pInfo);
  49326. #else
  49327. return ma_default_vfs_info__stdio(pVFS, file, pInfo);
  49328. #endif
  49329. }
  49330. MA_API ma_result ma_default_vfs_init(ma_default_vfs* pVFS, const ma_allocation_callbacks* pAllocationCallbacks)
  49331. {
  49332. if (pVFS == NULL) {
  49333. return MA_INVALID_ARGS;
  49334. }
  49335. pVFS->cb.onOpen = ma_default_vfs_open;
  49336. pVFS->cb.onOpenW = ma_default_vfs_open_w;
  49337. pVFS->cb.onClose = ma_default_vfs_close;
  49338. pVFS->cb.onRead = ma_default_vfs_read;
  49339. pVFS->cb.onWrite = ma_default_vfs_write;
  49340. pVFS->cb.onSeek = ma_default_vfs_seek;
  49341. pVFS->cb.onTell = ma_default_vfs_tell;
  49342. pVFS->cb.onInfo = ma_default_vfs_info;
  49343. ma_allocation_callbacks_init_copy(&pVFS->allocationCallbacks, pAllocationCallbacks);
  49344. return MA_SUCCESS;
  49345. }
  49346. MA_API ma_result ma_vfs_or_default_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49347. {
  49348. if (pVFS != NULL) {
  49349. return ma_vfs_open(pVFS, pFilePath, openMode, pFile);
  49350. } else {
  49351. return ma_default_vfs_open(pVFS, pFilePath, openMode, pFile);
  49352. }
  49353. }
  49354. MA_API ma_result ma_vfs_or_default_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49355. {
  49356. if (pVFS != NULL) {
  49357. return ma_vfs_open_w(pVFS, pFilePath, openMode, pFile);
  49358. } else {
  49359. return ma_default_vfs_open_w(pVFS, pFilePath, openMode, pFile);
  49360. }
  49361. }
  49362. MA_API ma_result ma_vfs_or_default_close(ma_vfs* pVFS, ma_vfs_file file)
  49363. {
  49364. if (pVFS != NULL) {
  49365. return ma_vfs_close(pVFS, file);
  49366. } else {
  49367. return ma_default_vfs_close(pVFS, file);
  49368. }
  49369. }
  49370. MA_API ma_result ma_vfs_or_default_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  49371. {
  49372. if (pVFS != NULL) {
  49373. return ma_vfs_read(pVFS, file, pDst, sizeInBytes, pBytesRead);
  49374. } else {
  49375. return ma_default_vfs_read(pVFS, file, pDst, sizeInBytes, pBytesRead);
  49376. }
  49377. }
  49378. MA_API ma_result ma_vfs_or_default_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  49379. {
  49380. if (pVFS != NULL) {
  49381. return ma_vfs_write(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  49382. } else {
  49383. return ma_default_vfs_write(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  49384. }
  49385. }
  49386. MA_API ma_result ma_vfs_or_default_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  49387. {
  49388. if (pVFS != NULL) {
  49389. return ma_vfs_seek(pVFS, file, offset, origin);
  49390. } else {
  49391. return ma_default_vfs_seek(pVFS, file, offset, origin);
  49392. }
  49393. }
  49394. MA_API ma_result ma_vfs_or_default_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  49395. {
  49396. if (pVFS != NULL) {
  49397. return ma_vfs_tell(pVFS, file, pCursor);
  49398. } else {
  49399. return ma_default_vfs_tell(pVFS, file, pCursor);
  49400. }
  49401. }
  49402. MA_API ma_result ma_vfs_or_default_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  49403. {
  49404. if (pVFS != NULL) {
  49405. return ma_vfs_info(pVFS, file, pInfo);
  49406. } else {
  49407. return ma_default_vfs_info(pVFS, file, pInfo);
  49408. }
  49409. }
  49410. /**************************************************************************************************************************************************************
  49411. Decoding and Encoding Headers. These are auto-generated from a tool.
  49412. **************************************************************************************************************************************************************/
  49413. #if !defined(MA_NO_WAV) && (!defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING))
  49414. /* dr_wav_h begin */
  49415. #ifndef dr_wav_h
  49416. #define dr_wav_h
  49417. #ifdef __cplusplus
  49418. extern "C" {
  49419. #endif
  49420. #define DRWAV_STRINGIFY(x) #x
  49421. #define DRWAV_XSTRINGIFY(x) DRWAV_STRINGIFY(x)
  49422. #define DRWAV_VERSION_MAJOR 0
  49423. #define DRWAV_VERSION_MINOR 13
  49424. #define DRWAV_VERSION_REVISION 8
  49425. #define DRWAV_VERSION_STRING DRWAV_XSTRINGIFY(DRWAV_VERSION_MAJOR) "." DRWAV_XSTRINGIFY(DRWAV_VERSION_MINOR) "." DRWAV_XSTRINGIFY(DRWAV_VERSION_REVISION)
  49426. #include <stddef.h>
  49427. typedef signed char drwav_int8;
  49428. typedef unsigned char drwav_uint8;
  49429. typedef signed short drwav_int16;
  49430. typedef unsigned short drwav_uint16;
  49431. typedef signed int drwav_int32;
  49432. typedef unsigned int drwav_uint32;
  49433. #if defined(_MSC_VER) && !defined(__clang__)
  49434. typedef signed __int64 drwav_int64;
  49435. typedef unsigned __int64 drwav_uint64;
  49436. #else
  49437. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  49438. #pragma GCC diagnostic push
  49439. #pragma GCC diagnostic ignored "-Wlong-long"
  49440. #if defined(__clang__)
  49441. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  49442. #endif
  49443. #endif
  49444. typedef signed long long drwav_int64;
  49445. typedef unsigned long long drwav_uint64;
  49446. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  49447. #pragma GCC diagnostic pop
  49448. #endif
  49449. #endif
  49450. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__)
  49451. typedef drwav_uint64 drwav_uintptr;
  49452. #else
  49453. typedef drwav_uint32 drwav_uintptr;
  49454. #endif
  49455. typedef drwav_uint8 drwav_bool8;
  49456. typedef drwav_uint32 drwav_bool32;
  49457. #define DRWAV_TRUE 1
  49458. #define DRWAV_FALSE 0
  49459. #if !defined(DRWAV_API)
  49460. #if defined(DRWAV_DLL)
  49461. #if defined(_WIN32)
  49462. #define DRWAV_DLL_IMPORT __declspec(dllimport)
  49463. #define DRWAV_DLL_EXPORT __declspec(dllexport)
  49464. #define DRWAV_DLL_PRIVATE static
  49465. #else
  49466. #if defined(__GNUC__) && __GNUC__ >= 4
  49467. #define DRWAV_DLL_IMPORT __attribute__((visibility("default")))
  49468. #define DRWAV_DLL_EXPORT __attribute__((visibility("default")))
  49469. #define DRWAV_DLL_PRIVATE __attribute__((visibility("hidden")))
  49470. #else
  49471. #define DRWAV_DLL_IMPORT
  49472. #define DRWAV_DLL_EXPORT
  49473. #define DRWAV_DLL_PRIVATE static
  49474. #endif
  49475. #endif
  49476. #if defined(DR_WAV_IMPLEMENTATION) || defined(DRWAV_IMPLEMENTATION)
  49477. #define DRWAV_API DRWAV_DLL_EXPORT
  49478. #else
  49479. #define DRWAV_API DRWAV_DLL_IMPORT
  49480. #endif
  49481. #define DRWAV_PRIVATE DRWAV_DLL_PRIVATE
  49482. #else
  49483. #define DRWAV_API extern
  49484. #define DRWAV_PRIVATE static
  49485. #endif
  49486. #endif
  49487. typedef drwav_int32 drwav_result;
  49488. #define DRWAV_SUCCESS 0
  49489. #define DRWAV_ERROR -1
  49490. #define DRWAV_INVALID_ARGS -2
  49491. #define DRWAV_INVALID_OPERATION -3
  49492. #define DRWAV_OUT_OF_MEMORY -4
  49493. #define DRWAV_OUT_OF_RANGE -5
  49494. #define DRWAV_ACCESS_DENIED -6
  49495. #define DRWAV_DOES_NOT_EXIST -7
  49496. #define DRWAV_ALREADY_EXISTS -8
  49497. #define DRWAV_TOO_MANY_OPEN_FILES -9
  49498. #define DRWAV_INVALID_FILE -10
  49499. #define DRWAV_TOO_BIG -11
  49500. #define DRWAV_PATH_TOO_LONG -12
  49501. #define DRWAV_NAME_TOO_LONG -13
  49502. #define DRWAV_NOT_DIRECTORY -14
  49503. #define DRWAV_IS_DIRECTORY -15
  49504. #define DRWAV_DIRECTORY_NOT_EMPTY -16
  49505. #define DRWAV_END_OF_FILE -17
  49506. #define DRWAV_NO_SPACE -18
  49507. #define DRWAV_BUSY -19
  49508. #define DRWAV_IO_ERROR -20
  49509. #define DRWAV_INTERRUPT -21
  49510. #define DRWAV_UNAVAILABLE -22
  49511. #define DRWAV_ALREADY_IN_USE -23
  49512. #define DRWAV_BAD_ADDRESS -24
  49513. #define DRWAV_BAD_SEEK -25
  49514. #define DRWAV_BAD_PIPE -26
  49515. #define DRWAV_DEADLOCK -27
  49516. #define DRWAV_TOO_MANY_LINKS -28
  49517. #define DRWAV_NOT_IMPLEMENTED -29
  49518. #define DRWAV_NO_MESSAGE -30
  49519. #define DRWAV_BAD_MESSAGE -31
  49520. #define DRWAV_NO_DATA_AVAILABLE -32
  49521. #define DRWAV_INVALID_DATA -33
  49522. #define DRWAV_TIMEOUT -34
  49523. #define DRWAV_NO_NETWORK -35
  49524. #define DRWAV_NOT_UNIQUE -36
  49525. #define DRWAV_NOT_SOCKET -37
  49526. #define DRWAV_NO_ADDRESS -38
  49527. #define DRWAV_BAD_PROTOCOL -39
  49528. #define DRWAV_PROTOCOL_UNAVAILABLE -40
  49529. #define DRWAV_PROTOCOL_NOT_SUPPORTED -41
  49530. #define DRWAV_PROTOCOL_FAMILY_NOT_SUPPORTED -42
  49531. #define DRWAV_ADDRESS_FAMILY_NOT_SUPPORTED -43
  49532. #define DRWAV_SOCKET_NOT_SUPPORTED -44
  49533. #define DRWAV_CONNECTION_RESET -45
  49534. #define DRWAV_ALREADY_CONNECTED -46
  49535. #define DRWAV_NOT_CONNECTED -47
  49536. #define DRWAV_CONNECTION_REFUSED -48
  49537. #define DRWAV_NO_HOST -49
  49538. #define DRWAV_IN_PROGRESS -50
  49539. #define DRWAV_CANCELLED -51
  49540. #define DRWAV_MEMORY_ALREADY_MAPPED -52
  49541. #define DRWAV_AT_END -53
  49542. #define DR_WAVE_FORMAT_PCM 0x1
  49543. #define DR_WAVE_FORMAT_ADPCM 0x2
  49544. #define DR_WAVE_FORMAT_IEEE_FLOAT 0x3
  49545. #define DR_WAVE_FORMAT_ALAW 0x6
  49546. #define DR_WAVE_FORMAT_MULAW 0x7
  49547. #define DR_WAVE_FORMAT_DVI_ADPCM 0x11
  49548. #define DR_WAVE_FORMAT_EXTENSIBLE 0xFFFE
  49549. #define DRWAV_SEQUENTIAL 0x00000001
  49550. DRWAV_API void drwav_version(drwav_uint32* pMajor, drwav_uint32* pMinor, drwav_uint32* pRevision);
  49551. DRWAV_API const char* drwav_version_string(void);
  49552. typedef enum
  49553. {
  49554. drwav_seek_origin_start,
  49555. drwav_seek_origin_current
  49556. } drwav_seek_origin;
  49557. typedef enum
  49558. {
  49559. drwav_container_riff,
  49560. drwav_container_w64,
  49561. drwav_container_rf64
  49562. } drwav_container;
  49563. typedef struct
  49564. {
  49565. union
  49566. {
  49567. drwav_uint8 fourcc[4];
  49568. drwav_uint8 guid[16];
  49569. } id;
  49570. drwav_uint64 sizeInBytes;
  49571. unsigned int paddingSize;
  49572. } drwav_chunk_header;
  49573. typedef struct
  49574. {
  49575. drwav_uint16 formatTag;
  49576. drwav_uint16 channels;
  49577. drwav_uint32 sampleRate;
  49578. drwav_uint32 avgBytesPerSec;
  49579. drwav_uint16 blockAlign;
  49580. drwav_uint16 bitsPerSample;
  49581. drwav_uint16 extendedSize;
  49582. drwav_uint16 validBitsPerSample;
  49583. drwav_uint32 channelMask;
  49584. drwav_uint8 subFormat[16];
  49585. } drwav_fmt;
  49586. DRWAV_API drwav_uint16 drwav_fmt_get_format(const drwav_fmt* pFMT);
  49587. typedef size_t (* drwav_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  49588. typedef size_t (* drwav_write_proc)(void* pUserData, const void* pData, size_t bytesToWrite);
  49589. typedef drwav_bool32 (* drwav_seek_proc)(void* pUserData, int offset, drwav_seek_origin origin);
  49590. typedef drwav_uint64 (* drwav_chunk_proc)(void* pChunkUserData, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pReadSeekUserData, const drwav_chunk_header* pChunkHeader, drwav_container container, const drwav_fmt* pFMT);
  49591. typedef struct
  49592. {
  49593. void* pUserData;
  49594. void* (* onMalloc)(size_t sz, void* pUserData);
  49595. void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  49596. void (* onFree)(void* p, void* pUserData);
  49597. } drwav_allocation_callbacks;
  49598. typedef struct
  49599. {
  49600. const drwav_uint8* data;
  49601. size_t dataSize;
  49602. size_t currentReadPos;
  49603. } drwav__memory_stream;
  49604. typedef struct
  49605. {
  49606. void** ppData;
  49607. size_t* pDataSize;
  49608. size_t dataSize;
  49609. size_t dataCapacity;
  49610. size_t currentWritePos;
  49611. } drwav__memory_stream_write;
  49612. typedef struct
  49613. {
  49614. drwav_container container;
  49615. drwav_uint32 format;
  49616. drwav_uint32 channels;
  49617. drwav_uint32 sampleRate;
  49618. drwav_uint32 bitsPerSample;
  49619. } drwav_data_format;
  49620. typedef enum
  49621. {
  49622. drwav_metadata_type_none = 0,
  49623. drwav_metadata_type_unknown = 1 << 0,
  49624. drwav_metadata_type_smpl = 1 << 1,
  49625. drwav_metadata_type_inst = 1 << 2,
  49626. drwav_metadata_type_cue = 1 << 3,
  49627. drwav_metadata_type_acid = 1 << 4,
  49628. drwav_metadata_type_bext = 1 << 5,
  49629. drwav_metadata_type_list_label = 1 << 6,
  49630. drwav_metadata_type_list_note = 1 << 7,
  49631. drwav_metadata_type_list_labelled_cue_region = 1 << 8,
  49632. drwav_metadata_type_list_info_software = 1 << 9,
  49633. drwav_metadata_type_list_info_copyright = 1 << 10,
  49634. drwav_metadata_type_list_info_title = 1 << 11,
  49635. drwav_metadata_type_list_info_artist = 1 << 12,
  49636. drwav_metadata_type_list_info_comment = 1 << 13,
  49637. drwav_metadata_type_list_info_date = 1 << 14,
  49638. drwav_metadata_type_list_info_genre = 1 << 15,
  49639. drwav_metadata_type_list_info_album = 1 << 16,
  49640. drwav_metadata_type_list_info_tracknumber = 1 << 17,
  49641. drwav_metadata_type_list_all_info_strings = drwav_metadata_type_list_info_software
  49642. | drwav_metadata_type_list_info_copyright
  49643. | drwav_metadata_type_list_info_title
  49644. | drwav_metadata_type_list_info_artist
  49645. | drwav_metadata_type_list_info_comment
  49646. | drwav_metadata_type_list_info_date
  49647. | drwav_metadata_type_list_info_genre
  49648. | drwav_metadata_type_list_info_album
  49649. | drwav_metadata_type_list_info_tracknumber,
  49650. drwav_metadata_type_list_all_adtl = drwav_metadata_type_list_label
  49651. | drwav_metadata_type_list_note
  49652. | drwav_metadata_type_list_labelled_cue_region,
  49653. drwav_metadata_type_all = -2,
  49654. drwav_metadata_type_all_including_unknown = -1
  49655. } drwav_metadata_type;
  49656. typedef enum
  49657. {
  49658. drwav_smpl_loop_type_forward = 0,
  49659. drwav_smpl_loop_type_pingpong = 1,
  49660. drwav_smpl_loop_type_backward = 2
  49661. } drwav_smpl_loop_type;
  49662. typedef struct
  49663. {
  49664. drwav_uint32 cuePointId;
  49665. drwav_uint32 type;
  49666. drwav_uint32 firstSampleByteOffset;
  49667. drwav_uint32 lastSampleByteOffset;
  49668. drwav_uint32 sampleFraction;
  49669. drwav_uint32 playCount;
  49670. } drwav_smpl_loop;
  49671. typedef struct
  49672. {
  49673. drwav_uint32 manufacturerId;
  49674. drwav_uint32 productId;
  49675. drwav_uint32 samplePeriodNanoseconds;
  49676. drwav_uint32 midiUnityNote;
  49677. drwav_uint32 midiPitchFraction;
  49678. drwav_uint32 smpteFormat;
  49679. drwav_uint32 smpteOffset;
  49680. drwav_uint32 sampleLoopCount;
  49681. drwav_uint32 samplerSpecificDataSizeInBytes;
  49682. drwav_smpl_loop* pLoops;
  49683. drwav_uint8* pSamplerSpecificData;
  49684. } drwav_smpl;
  49685. typedef struct
  49686. {
  49687. drwav_int8 midiUnityNote;
  49688. drwav_int8 fineTuneCents;
  49689. drwav_int8 gainDecibels;
  49690. drwav_int8 lowNote;
  49691. drwav_int8 highNote;
  49692. drwav_int8 lowVelocity;
  49693. drwav_int8 highVelocity;
  49694. } drwav_inst;
  49695. typedef struct
  49696. {
  49697. drwav_uint32 id;
  49698. drwav_uint32 playOrderPosition;
  49699. drwav_uint8 dataChunkId[4];
  49700. drwav_uint32 chunkStart;
  49701. drwav_uint32 blockStart;
  49702. drwav_uint32 sampleByteOffset;
  49703. } drwav_cue_point;
  49704. typedef struct
  49705. {
  49706. drwav_uint32 cuePointCount;
  49707. drwav_cue_point *pCuePoints;
  49708. } drwav_cue;
  49709. typedef enum
  49710. {
  49711. drwav_acid_flag_one_shot = 1,
  49712. drwav_acid_flag_root_note_set = 2,
  49713. drwav_acid_flag_stretch = 4,
  49714. drwav_acid_flag_disk_based = 8,
  49715. drwav_acid_flag_acidizer = 16
  49716. } drwav_acid_flag;
  49717. typedef struct
  49718. {
  49719. drwav_uint32 flags;
  49720. drwav_uint16 midiUnityNote;
  49721. drwav_uint16 reserved1;
  49722. float reserved2;
  49723. drwav_uint32 numBeats;
  49724. drwav_uint16 meterDenominator;
  49725. drwav_uint16 meterNumerator;
  49726. float tempo;
  49727. } drwav_acid;
  49728. typedef struct
  49729. {
  49730. drwav_uint32 cuePointId;
  49731. drwav_uint32 stringLength;
  49732. char* pString;
  49733. } drwav_list_label_or_note;
  49734. typedef struct
  49735. {
  49736. char* pDescription;
  49737. char* pOriginatorName;
  49738. char* pOriginatorReference;
  49739. char pOriginationDate[10];
  49740. char pOriginationTime[8];
  49741. drwav_uint64 timeReference;
  49742. drwav_uint16 version;
  49743. char* pCodingHistory;
  49744. drwav_uint32 codingHistorySize;
  49745. drwav_uint8* pUMID;
  49746. drwav_uint16 loudnessValue;
  49747. drwav_uint16 loudnessRange;
  49748. drwav_uint16 maxTruePeakLevel;
  49749. drwav_uint16 maxMomentaryLoudness;
  49750. drwav_uint16 maxShortTermLoudness;
  49751. } drwav_bext;
  49752. typedef struct
  49753. {
  49754. drwav_uint32 stringLength;
  49755. char* pString;
  49756. } drwav_list_info_text;
  49757. typedef struct
  49758. {
  49759. drwav_uint32 cuePointId;
  49760. drwav_uint32 sampleLength;
  49761. drwav_uint8 purposeId[4];
  49762. drwav_uint16 country;
  49763. drwav_uint16 language;
  49764. drwav_uint16 dialect;
  49765. drwav_uint16 codePage;
  49766. drwav_uint32 stringLength;
  49767. char* pString;
  49768. } drwav_list_labelled_cue_region;
  49769. typedef enum
  49770. {
  49771. drwav_metadata_location_invalid,
  49772. drwav_metadata_location_top_level,
  49773. drwav_metadata_location_inside_info_list,
  49774. drwav_metadata_location_inside_adtl_list
  49775. } drwav_metadata_location;
  49776. typedef struct
  49777. {
  49778. drwav_uint8 id[4];
  49779. drwav_metadata_location chunkLocation;
  49780. drwav_uint32 dataSizeInBytes;
  49781. drwav_uint8* pData;
  49782. } drwav_unknown_metadata;
  49783. typedef struct
  49784. {
  49785. drwav_metadata_type type;
  49786. union
  49787. {
  49788. drwav_cue cue;
  49789. drwav_smpl smpl;
  49790. drwav_acid acid;
  49791. drwav_inst inst;
  49792. drwav_bext bext;
  49793. drwav_list_label_or_note labelOrNote;
  49794. drwav_list_labelled_cue_region labelledCueRegion;
  49795. drwav_list_info_text infoText;
  49796. drwav_unknown_metadata unknown;
  49797. } data;
  49798. } drwav_metadata;
  49799. typedef struct
  49800. {
  49801. drwav_read_proc onRead;
  49802. drwav_write_proc onWrite;
  49803. drwav_seek_proc onSeek;
  49804. void* pUserData;
  49805. drwav_allocation_callbacks allocationCallbacks;
  49806. drwav_container container;
  49807. drwav_fmt fmt;
  49808. drwav_uint32 sampleRate;
  49809. drwav_uint16 channels;
  49810. drwav_uint16 bitsPerSample;
  49811. drwav_uint16 translatedFormatTag;
  49812. drwav_uint64 totalPCMFrameCount;
  49813. drwav_uint64 dataChunkDataSize;
  49814. drwav_uint64 dataChunkDataPos;
  49815. drwav_uint64 bytesRemaining;
  49816. drwav_uint64 readCursorInPCMFrames;
  49817. drwav_uint64 dataChunkDataSizeTargetWrite;
  49818. drwav_bool32 isSequentialWrite;
  49819. drwav_metadata_type allowedMetadataTypes;
  49820. drwav_metadata* pMetadata;
  49821. drwav_uint32 metadataCount;
  49822. drwav__memory_stream memoryStream;
  49823. drwav__memory_stream_write memoryStreamWrite;
  49824. struct
  49825. {
  49826. drwav_uint32 bytesRemainingInBlock;
  49827. drwav_uint16 predictor[2];
  49828. drwav_int32 delta[2];
  49829. drwav_int32 cachedFrames[4];
  49830. drwav_uint32 cachedFrameCount;
  49831. drwav_int32 prevFrames[2][2];
  49832. } msadpcm;
  49833. struct
  49834. {
  49835. drwav_uint32 bytesRemainingInBlock;
  49836. drwav_int32 predictor[2];
  49837. drwav_int32 stepIndex[2];
  49838. drwav_int32 cachedFrames[16];
  49839. drwav_uint32 cachedFrameCount;
  49840. } ima;
  49841. } drwav;
  49842. DRWAV_API drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
  49843. DRWAV_API drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  49844. DRWAV_API drwav_bool32 drwav_init_with_metadata(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  49845. DRWAV_API drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
  49846. DRWAV_API drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
  49847. DRWAV_API drwav_bool32 drwav_init_write_sequential_pcm_frames(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
  49848. DRWAV_API drwav_bool32 drwav_init_write_with_metadata(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks, drwav_metadata* pMetadata, drwav_uint32 metadataCount);
  49849. DRWAV_API drwav_uint64 drwav_target_write_size_bytes(const drwav_data_format* pFormat, drwav_uint64 totalFrameCount, drwav_metadata* pMetadata, drwav_uint32 metadataCount);
  49850. DRWAV_API drwav_metadata* drwav_take_ownership_of_metadata(drwav* pWav);
  49851. DRWAV_API drwav_result drwav_uninit(drwav* pWav);
  49852. DRWAV_API size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut);
  49853. DRWAV_API drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
  49854. DRWAV_API drwav_uint64 drwav_read_pcm_frames_le(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
  49855. DRWAV_API drwav_uint64 drwav_read_pcm_frames_be(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
  49856. DRWAV_API drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex);
  49857. DRWAV_API drwav_result drwav_get_cursor_in_pcm_frames(drwav* pWav, drwav_uint64* pCursor);
  49858. DRWAV_API drwav_result drwav_get_length_in_pcm_frames(drwav* pWav, drwav_uint64* pLength);
  49859. DRWAV_API size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData);
  49860. DRWAV_API drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
  49861. DRWAV_API drwav_uint64 drwav_write_pcm_frames_le(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
  49862. DRWAV_API drwav_uint64 drwav_write_pcm_frames_be(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
  49863. #ifndef DR_WAV_NO_CONVERSION_API
  49864. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
  49865. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16le(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
  49866. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16be(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
  49867. DRWAV_API void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49868. DRWAV_API void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49869. DRWAV_API void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount);
  49870. DRWAV_API void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount);
  49871. DRWAV_API void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount);
  49872. DRWAV_API void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49873. DRWAV_API void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49874. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
  49875. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32le(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
  49876. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32be(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
  49877. DRWAV_API void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49878. DRWAV_API void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount);
  49879. DRWAV_API void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49880. DRWAV_API void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount);
  49881. DRWAV_API void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount);
  49882. DRWAV_API void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49883. DRWAV_API void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49884. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
  49885. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32le(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
  49886. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32be(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
  49887. DRWAV_API void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49888. DRWAV_API void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount);
  49889. DRWAV_API void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49890. DRWAV_API void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount);
  49891. DRWAV_API void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount);
  49892. DRWAV_API void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49893. DRWAV_API void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  49894. #endif
  49895. #ifndef DR_WAV_NO_STDIO
  49896. DRWAV_API drwav_bool32 drwav_init_file(drwav* pWav, const char* filename, const drwav_allocation_callbacks* pAllocationCallbacks);
  49897. DRWAV_API drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  49898. DRWAV_API drwav_bool32 drwav_init_file_w(drwav* pWav, const wchar_t* filename, const drwav_allocation_callbacks* pAllocationCallbacks);
  49899. DRWAV_API drwav_bool32 drwav_init_file_ex_w(drwav* pWav, const wchar_t* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  49900. DRWAV_API drwav_bool32 drwav_init_file_with_metadata(drwav* pWav, const char* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  49901. DRWAV_API drwav_bool32 drwav_init_file_with_metadata_w(drwav* pWav, const wchar_t* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  49902. DRWAV_API drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
  49903. DRWAV_API drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  49904. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  49905. DRWAV_API drwav_bool32 drwav_init_file_write_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
  49906. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  49907. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  49908. #endif
  49909. DRWAV_API drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize, const drwav_allocation_callbacks* pAllocationCallbacks);
  49910. DRWAV_API drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  49911. DRWAV_API drwav_bool32 drwav_init_memory_with_metadata(drwav* pWav, const void* data, size_t dataSize, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  49912. DRWAV_API drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
  49913. DRWAV_API drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  49914. DRWAV_API drwav_bool32 drwav_init_memory_write_sequential_pcm_frames(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  49915. #ifndef DR_WAV_NO_CONVERSION_API
  49916. DRWAV_API drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49917. DRWAV_API float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49918. DRWAV_API drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49919. #ifndef DR_WAV_NO_STDIO
  49920. DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49921. DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49922. DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49923. DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49924. DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49925. DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49926. #endif
  49927. DRWAV_API drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49928. DRWAV_API float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49929. DRWAV_API drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  49930. #endif
  49931. DRWAV_API void drwav_free(void* p, const drwav_allocation_callbacks* pAllocationCallbacks);
  49932. DRWAV_API drwav_uint16 drwav_bytes_to_u16(const drwav_uint8* data);
  49933. DRWAV_API drwav_int16 drwav_bytes_to_s16(const drwav_uint8* data);
  49934. DRWAV_API drwav_uint32 drwav_bytes_to_u32(const drwav_uint8* data);
  49935. DRWAV_API drwav_int32 drwav_bytes_to_s32(const drwav_uint8* data);
  49936. DRWAV_API drwav_uint64 drwav_bytes_to_u64(const drwav_uint8* data);
  49937. DRWAV_API drwav_int64 drwav_bytes_to_s64(const drwav_uint8* data);
  49938. DRWAV_API float drwav_bytes_to_f32(const drwav_uint8* data);
  49939. DRWAV_API drwav_bool32 drwav_guid_equal(const drwav_uint8 a[16], const drwav_uint8 b[16]);
  49940. DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b);
  49941. #ifdef __cplusplus
  49942. }
  49943. #endif
  49944. #endif
  49945. /* dr_wav_h end */
  49946. #endif /* MA_NO_WAV */
  49947. #if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING)
  49948. /* dr_flac_h begin */
  49949. #ifndef dr_flac_h
  49950. #define dr_flac_h
  49951. #ifdef __cplusplus
  49952. extern "C" {
  49953. #endif
  49954. #define DRFLAC_STRINGIFY(x) #x
  49955. #define DRFLAC_XSTRINGIFY(x) DRFLAC_STRINGIFY(x)
  49956. #define DRFLAC_VERSION_MAJOR 0
  49957. #define DRFLAC_VERSION_MINOR 12
  49958. #define DRFLAC_VERSION_REVISION 39
  49959. #define DRFLAC_VERSION_STRING DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MAJOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MINOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_REVISION)
  49960. #include <stddef.h>
  49961. typedef signed char drflac_int8;
  49962. typedef unsigned char drflac_uint8;
  49963. typedef signed short drflac_int16;
  49964. typedef unsigned short drflac_uint16;
  49965. typedef signed int drflac_int32;
  49966. typedef unsigned int drflac_uint32;
  49967. #if defined(_MSC_VER) && !defined(__clang__)
  49968. typedef signed __int64 drflac_int64;
  49969. typedef unsigned __int64 drflac_uint64;
  49970. #else
  49971. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  49972. #pragma GCC diagnostic push
  49973. #pragma GCC diagnostic ignored "-Wlong-long"
  49974. #if defined(__clang__)
  49975. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  49976. #endif
  49977. #endif
  49978. typedef signed long long drflac_int64;
  49979. typedef unsigned long long drflac_uint64;
  49980. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  49981. #pragma GCC diagnostic pop
  49982. #endif
  49983. #endif
  49984. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined(_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__)
  49985. typedef drflac_uint64 drflac_uintptr;
  49986. #else
  49987. typedef drflac_uint32 drflac_uintptr;
  49988. #endif
  49989. typedef drflac_uint8 drflac_bool8;
  49990. typedef drflac_uint32 drflac_bool32;
  49991. #define DRFLAC_TRUE 1
  49992. #define DRFLAC_FALSE 0
  49993. #if !defined(DRFLAC_API)
  49994. #if defined(DRFLAC_DLL)
  49995. #if defined(_WIN32)
  49996. #define DRFLAC_DLL_IMPORT __declspec(dllimport)
  49997. #define DRFLAC_DLL_EXPORT __declspec(dllexport)
  49998. #define DRFLAC_DLL_PRIVATE static
  49999. #else
  50000. #if defined(__GNUC__) && __GNUC__ >= 4
  50001. #define DRFLAC_DLL_IMPORT __attribute__((visibility("default")))
  50002. #define DRFLAC_DLL_EXPORT __attribute__((visibility("default")))
  50003. #define DRFLAC_DLL_PRIVATE __attribute__((visibility("hidden")))
  50004. #else
  50005. #define DRFLAC_DLL_IMPORT
  50006. #define DRFLAC_DLL_EXPORT
  50007. #define DRFLAC_DLL_PRIVATE static
  50008. #endif
  50009. #endif
  50010. #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
  50011. #define DRFLAC_API DRFLAC_DLL_EXPORT
  50012. #else
  50013. #define DRFLAC_API DRFLAC_DLL_IMPORT
  50014. #endif
  50015. #define DRFLAC_PRIVATE DRFLAC_DLL_PRIVATE
  50016. #else
  50017. #define DRFLAC_API extern
  50018. #define DRFLAC_PRIVATE static
  50019. #endif
  50020. #endif
  50021. #if defined(_MSC_VER) && _MSC_VER >= 1700
  50022. #define DRFLAC_DEPRECATED __declspec(deprecated)
  50023. #elif (defined(__GNUC__) && __GNUC__ >= 4)
  50024. #define DRFLAC_DEPRECATED __attribute__((deprecated))
  50025. #elif defined(__has_feature)
  50026. #if __has_feature(attribute_deprecated)
  50027. #define DRFLAC_DEPRECATED __attribute__((deprecated))
  50028. #else
  50029. #define DRFLAC_DEPRECATED
  50030. #endif
  50031. #else
  50032. #define DRFLAC_DEPRECATED
  50033. #endif
  50034. DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision);
  50035. DRFLAC_API const char* drflac_version_string(void);
  50036. #ifndef DR_FLAC_BUFFER_SIZE
  50037. #define DR_FLAC_BUFFER_SIZE 4096
  50038. #endif
  50039. #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
  50040. #define DRFLAC_64BIT
  50041. #endif
  50042. #ifdef DRFLAC_64BIT
  50043. typedef drflac_uint64 drflac_cache_t;
  50044. #else
  50045. typedef drflac_uint32 drflac_cache_t;
  50046. #endif
  50047. #define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO 0
  50048. #define DRFLAC_METADATA_BLOCK_TYPE_PADDING 1
  50049. #define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION 2
  50050. #define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3
  50051. #define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4
  50052. #define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET 5
  50053. #define DRFLAC_METADATA_BLOCK_TYPE_PICTURE 6
  50054. #define DRFLAC_METADATA_BLOCK_TYPE_INVALID 127
  50055. #define DRFLAC_PICTURE_TYPE_OTHER 0
  50056. #define DRFLAC_PICTURE_TYPE_FILE_ICON 1
  50057. #define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON 2
  50058. #define DRFLAC_PICTURE_TYPE_COVER_FRONT 3
  50059. #define DRFLAC_PICTURE_TYPE_COVER_BACK 4
  50060. #define DRFLAC_PICTURE_TYPE_LEAFLET_PAGE 5
  50061. #define DRFLAC_PICTURE_TYPE_MEDIA 6
  50062. #define DRFLAC_PICTURE_TYPE_LEAD_ARTIST 7
  50063. #define DRFLAC_PICTURE_TYPE_ARTIST 8
  50064. #define DRFLAC_PICTURE_TYPE_CONDUCTOR 9
  50065. #define DRFLAC_PICTURE_TYPE_BAND 10
  50066. #define DRFLAC_PICTURE_TYPE_COMPOSER 11
  50067. #define DRFLAC_PICTURE_TYPE_LYRICIST 12
  50068. #define DRFLAC_PICTURE_TYPE_RECORDING_LOCATION 13
  50069. #define DRFLAC_PICTURE_TYPE_DURING_RECORDING 14
  50070. #define DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE 15
  50071. #define DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE 16
  50072. #define DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17
  50073. #define DRFLAC_PICTURE_TYPE_ILLUSTRATION 18
  50074. #define DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE 19
  50075. #define DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20
  50076. typedef enum
  50077. {
  50078. drflac_container_native,
  50079. drflac_container_ogg,
  50080. drflac_container_unknown
  50081. } drflac_container;
  50082. typedef enum
  50083. {
  50084. drflac_seek_origin_start,
  50085. drflac_seek_origin_current
  50086. } drflac_seek_origin;
  50087. typedef struct
  50088. {
  50089. drflac_uint64 firstPCMFrame;
  50090. drflac_uint64 flacFrameOffset;
  50091. drflac_uint16 pcmFrameCount;
  50092. } drflac_seekpoint;
  50093. typedef struct
  50094. {
  50095. drflac_uint16 minBlockSizeInPCMFrames;
  50096. drflac_uint16 maxBlockSizeInPCMFrames;
  50097. drflac_uint32 minFrameSizeInPCMFrames;
  50098. drflac_uint32 maxFrameSizeInPCMFrames;
  50099. drflac_uint32 sampleRate;
  50100. drflac_uint8 channels;
  50101. drflac_uint8 bitsPerSample;
  50102. drflac_uint64 totalPCMFrameCount;
  50103. drflac_uint8 md5[16];
  50104. } drflac_streaminfo;
  50105. typedef struct
  50106. {
  50107. drflac_uint32 type;
  50108. const void* pRawData;
  50109. drflac_uint32 rawDataSize;
  50110. union
  50111. {
  50112. drflac_streaminfo streaminfo;
  50113. struct
  50114. {
  50115. int unused;
  50116. } padding;
  50117. struct
  50118. {
  50119. drflac_uint32 id;
  50120. const void* pData;
  50121. drflac_uint32 dataSize;
  50122. } application;
  50123. struct
  50124. {
  50125. drflac_uint32 seekpointCount;
  50126. const drflac_seekpoint* pSeekpoints;
  50127. } seektable;
  50128. struct
  50129. {
  50130. drflac_uint32 vendorLength;
  50131. const char* vendor;
  50132. drflac_uint32 commentCount;
  50133. const void* pComments;
  50134. } vorbis_comment;
  50135. struct
  50136. {
  50137. char catalog[128];
  50138. drflac_uint64 leadInSampleCount;
  50139. drflac_bool32 isCD;
  50140. drflac_uint8 trackCount;
  50141. const void* pTrackData;
  50142. } cuesheet;
  50143. struct
  50144. {
  50145. drflac_uint32 type;
  50146. drflac_uint32 mimeLength;
  50147. const char* mime;
  50148. drflac_uint32 descriptionLength;
  50149. const char* description;
  50150. drflac_uint32 width;
  50151. drflac_uint32 height;
  50152. drflac_uint32 colorDepth;
  50153. drflac_uint32 indexColorCount;
  50154. drflac_uint32 pictureDataSize;
  50155. const drflac_uint8* pPictureData;
  50156. } picture;
  50157. } data;
  50158. } drflac_metadata;
  50159. typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  50160. typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin);
  50161. typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata);
  50162. typedef struct
  50163. {
  50164. void* pUserData;
  50165. void* (* onMalloc)(size_t sz, void* pUserData);
  50166. void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  50167. void (* onFree)(void* p, void* pUserData);
  50168. } drflac_allocation_callbacks;
  50169. typedef struct
  50170. {
  50171. const drflac_uint8* data;
  50172. size_t dataSize;
  50173. size_t currentReadPos;
  50174. } drflac__memory_stream;
  50175. typedef struct
  50176. {
  50177. drflac_read_proc onRead;
  50178. drflac_seek_proc onSeek;
  50179. void* pUserData;
  50180. size_t unalignedByteCount;
  50181. drflac_cache_t unalignedCache;
  50182. drflac_uint32 nextL2Line;
  50183. drflac_uint32 consumedBits;
  50184. drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)];
  50185. drflac_cache_t cache;
  50186. drflac_uint16 crc16;
  50187. drflac_cache_t crc16Cache;
  50188. drflac_uint32 crc16CacheIgnoredBytes;
  50189. } drflac_bs;
  50190. typedef struct
  50191. {
  50192. drflac_uint8 subframeType;
  50193. drflac_uint8 wastedBitsPerSample;
  50194. drflac_uint8 lpcOrder;
  50195. drflac_int32* pSamplesS32;
  50196. } drflac_subframe;
  50197. typedef struct
  50198. {
  50199. drflac_uint64 pcmFrameNumber;
  50200. drflac_uint32 flacFrameNumber;
  50201. drflac_uint32 sampleRate;
  50202. drflac_uint16 blockSizeInPCMFrames;
  50203. drflac_uint8 channelAssignment;
  50204. drflac_uint8 bitsPerSample;
  50205. drflac_uint8 crc8;
  50206. } drflac_frame_header;
  50207. typedef struct
  50208. {
  50209. drflac_frame_header header;
  50210. drflac_uint32 pcmFramesRemaining;
  50211. drflac_subframe subframes[8];
  50212. } drflac_frame;
  50213. typedef struct
  50214. {
  50215. drflac_meta_proc onMeta;
  50216. void* pUserDataMD;
  50217. drflac_allocation_callbacks allocationCallbacks;
  50218. drflac_uint32 sampleRate;
  50219. drflac_uint8 channels;
  50220. drflac_uint8 bitsPerSample;
  50221. drflac_uint16 maxBlockSizeInPCMFrames;
  50222. drflac_uint64 totalPCMFrameCount;
  50223. drflac_container container;
  50224. drflac_uint32 seekpointCount;
  50225. drflac_frame currentFLACFrame;
  50226. drflac_uint64 currentPCMFrame;
  50227. drflac_uint64 firstFLACFramePosInBytes;
  50228. drflac__memory_stream memoryStream;
  50229. drflac_int32* pDecodedSamples;
  50230. drflac_seekpoint* pSeekpoints;
  50231. void* _oggbs;
  50232. drflac_bool32 _noSeekTableSeek : 1;
  50233. drflac_bool32 _noBinarySearchSeek : 1;
  50234. drflac_bool32 _noBruteForceSeek : 1;
  50235. drflac_bs bs;
  50236. drflac_uint8 pExtraData[1];
  50237. } drflac;
  50238. DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  50239. DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  50240. DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  50241. DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  50242. DRFLAC_API void drflac_close(drflac* pFlac);
  50243. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut);
  50244. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut);
  50245. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut);
  50246. DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex);
  50247. #ifndef DR_FLAC_NO_STDIO
  50248. DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
  50249. DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
  50250. DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  50251. DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  50252. #endif
  50253. DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks);
  50254. DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  50255. DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  50256. DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  50257. DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  50258. #ifndef DR_FLAC_NO_STDIO
  50259. DRFLAC_API drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  50260. DRFLAC_API drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  50261. DRFLAC_API float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  50262. #endif
  50263. DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  50264. DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  50265. DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  50266. DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks);
  50267. typedef struct
  50268. {
  50269. drflac_uint32 countRemaining;
  50270. const char* pRunningData;
  50271. } drflac_vorbis_comment_iterator;
  50272. DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments);
  50273. DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut);
  50274. typedef struct
  50275. {
  50276. drflac_uint32 countRemaining;
  50277. const char* pRunningData;
  50278. } drflac_cuesheet_track_iterator;
  50279. typedef struct
  50280. {
  50281. drflac_uint64 offset;
  50282. drflac_uint8 index;
  50283. drflac_uint8 reserved[3];
  50284. } drflac_cuesheet_track_index;
  50285. typedef struct
  50286. {
  50287. drflac_uint64 offset;
  50288. drflac_uint8 trackNumber;
  50289. char ISRC[12];
  50290. drflac_bool8 isAudio;
  50291. drflac_bool8 preEmphasis;
  50292. drflac_uint8 indexCount;
  50293. const drflac_cuesheet_track_index* pIndexPoints;
  50294. } drflac_cuesheet_track;
  50295. DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData);
  50296. DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack);
  50297. #ifdef __cplusplus
  50298. }
  50299. #endif
  50300. #endif
  50301. /* dr_flac_h end */
  50302. #endif /* MA_NO_FLAC */
  50303. #if !defined(MA_NO_MP3) && !defined(MA_NO_DECODING)
  50304. /* dr_mp3_h begin */
  50305. #ifndef dr_mp3_h
  50306. #define dr_mp3_h
  50307. #ifdef __cplusplus
  50308. extern "C" {
  50309. #endif
  50310. #define DRMP3_STRINGIFY(x) #x
  50311. #define DRMP3_XSTRINGIFY(x) DRMP3_STRINGIFY(x)
  50312. #define DRMP3_VERSION_MAJOR 0
  50313. #define DRMP3_VERSION_MINOR 6
  50314. #define DRMP3_VERSION_REVISION 34
  50315. #define DRMP3_VERSION_STRING DRMP3_XSTRINGIFY(DRMP3_VERSION_MAJOR) "." DRMP3_XSTRINGIFY(DRMP3_VERSION_MINOR) "." DRMP3_XSTRINGIFY(DRMP3_VERSION_REVISION)
  50316. #include <stddef.h>
  50317. typedef signed char drmp3_int8;
  50318. typedef unsigned char drmp3_uint8;
  50319. typedef signed short drmp3_int16;
  50320. typedef unsigned short drmp3_uint16;
  50321. typedef signed int drmp3_int32;
  50322. typedef unsigned int drmp3_uint32;
  50323. #if defined(_MSC_VER) && !defined(__clang__)
  50324. typedef signed __int64 drmp3_int64;
  50325. typedef unsigned __int64 drmp3_uint64;
  50326. #else
  50327. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  50328. #pragma GCC diagnostic push
  50329. #pragma GCC diagnostic ignored "-Wlong-long"
  50330. #if defined(__clang__)
  50331. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  50332. #endif
  50333. #endif
  50334. typedef signed long long drmp3_int64;
  50335. typedef unsigned long long drmp3_uint64;
  50336. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  50337. #pragma GCC diagnostic pop
  50338. #endif
  50339. #endif
  50340. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__)
  50341. typedef drmp3_uint64 drmp3_uintptr;
  50342. #else
  50343. typedef drmp3_uint32 drmp3_uintptr;
  50344. #endif
  50345. typedef drmp3_uint8 drmp3_bool8;
  50346. typedef drmp3_uint32 drmp3_bool32;
  50347. #define DRMP3_TRUE 1
  50348. #define DRMP3_FALSE 0
  50349. #if !defined(DRMP3_API)
  50350. #if defined(DRMP3_DLL)
  50351. #if defined(_WIN32)
  50352. #define DRMP3_DLL_IMPORT __declspec(dllimport)
  50353. #define DRMP3_DLL_EXPORT __declspec(dllexport)
  50354. #define DRMP3_DLL_PRIVATE static
  50355. #else
  50356. #if defined(__GNUC__) && __GNUC__ >= 4
  50357. #define DRMP3_DLL_IMPORT __attribute__((visibility("default")))
  50358. #define DRMP3_DLL_EXPORT __attribute__((visibility("default")))
  50359. #define DRMP3_DLL_PRIVATE __attribute__((visibility("hidden")))
  50360. #else
  50361. #define DRMP3_DLL_IMPORT
  50362. #define DRMP3_DLL_EXPORT
  50363. #define DRMP3_DLL_PRIVATE static
  50364. #endif
  50365. #endif
  50366. #if defined(DR_MP3_IMPLEMENTATION) || defined(DRMP3_IMPLEMENTATION)
  50367. #define DRMP3_API DRMP3_DLL_EXPORT
  50368. #else
  50369. #define DRMP3_API DRMP3_DLL_IMPORT
  50370. #endif
  50371. #define DRMP3_PRIVATE DRMP3_DLL_PRIVATE
  50372. #else
  50373. #define DRMP3_API extern
  50374. #define DRMP3_PRIVATE static
  50375. #endif
  50376. #endif
  50377. typedef drmp3_int32 drmp3_result;
  50378. #define DRMP3_SUCCESS 0
  50379. #define DRMP3_ERROR -1
  50380. #define DRMP3_INVALID_ARGS -2
  50381. #define DRMP3_INVALID_OPERATION -3
  50382. #define DRMP3_OUT_OF_MEMORY -4
  50383. #define DRMP3_OUT_OF_RANGE -5
  50384. #define DRMP3_ACCESS_DENIED -6
  50385. #define DRMP3_DOES_NOT_EXIST -7
  50386. #define DRMP3_ALREADY_EXISTS -8
  50387. #define DRMP3_TOO_MANY_OPEN_FILES -9
  50388. #define DRMP3_INVALID_FILE -10
  50389. #define DRMP3_TOO_BIG -11
  50390. #define DRMP3_PATH_TOO_LONG -12
  50391. #define DRMP3_NAME_TOO_LONG -13
  50392. #define DRMP3_NOT_DIRECTORY -14
  50393. #define DRMP3_IS_DIRECTORY -15
  50394. #define DRMP3_DIRECTORY_NOT_EMPTY -16
  50395. #define DRMP3_END_OF_FILE -17
  50396. #define DRMP3_NO_SPACE -18
  50397. #define DRMP3_BUSY -19
  50398. #define DRMP3_IO_ERROR -20
  50399. #define DRMP3_INTERRUPT -21
  50400. #define DRMP3_UNAVAILABLE -22
  50401. #define DRMP3_ALREADY_IN_USE -23
  50402. #define DRMP3_BAD_ADDRESS -24
  50403. #define DRMP3_BAD_SEEK -25
  50404. #define DRMP3_BAD_PIPE -26
  50405. #define DRMP3_DEADLOCK -27
  50406. #define DRMP3_TOO_MANY_LINKS -28
  50407. #define DRMP3_NOT_IMPLEMENTED -29
  50408. #define DRMP3_NO_MESSAGE -30
  50409. #define DRMP3_BAD_MESSAGE -31
  50410. #define DRMP3_NO_DATA_AVAILABLE -32
  50411. #define DRMP3_INVALID_DATA -33
  50412. #define DRMP3_TIMEOUT -34
  50413. #define DRMP3_NO_NETWORK -35
  50414. #define DRMP3_NOT_UNIQUE -36
  50415. #define DRMP3_NOT_SOCKET -37
  50416. #define DRMP3_NO_ADDRESS -38
  50417. #define DRMP3_BAD_PROTOCOL -39
  50418. #define DRMP3_PROTOCOL_UNAVAILABLE -40
  50419. #define DRMP3_PROTOCOL_NOT_SUPPORTED -41
  50420. #define DRMP3_PROTOCOL_FAMILY_NOT_SUPPORTED -42
  50421. #define DRMP3_ADDRESS_FAMILY_NOT_SUPPORTED -43
  50422. #define DRMP3_SOCKET_NOT_SUPPORTED -44
  50423. #define DRMP3_CONNECTION_RESET -45
  50424. #define DRMP3_ALREADY_CONNECTED -46
  50425. #define DRMP3_NOT_CONNECTED -47
  50426. #define DRMP3_CONNECTION_REFUSED -48
  50427. #define DRMP3_NO_HOST -49
  50428. #define DRMP3_IN_PROGRESS -50
  50429. #define DRMP3_CANCELLED -51
  50430. #define DRMP3_MEMORY_ALREADY_MAPPED -52
  50431. #define DRMP3_AT_END -53
  50432. #define DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME 1152
  50433. #define DRMP3_MAX_SAMPLES_PER_FRAME (DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME*2)
  50434. #ifdef _MSC_VER
  50435. #define DRMP3_INLINE __forceinline
  50436. #elif defined(__GNUC__)
  50437. #if defined(__STRICT_ANSI__)
  50438. #define DRMP3_GNUC_INLINE_HINT __inline__
  50439. #else
  50440. #define DRMP3_GNUC_INLINE_HINT inline
  50441. #endif
  50442. #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
  50443. #define DRMP3_INLINE DRMP3_GNUC_INLINE_HINT __attribute__((always_inline))
  50444. #else
  50445. #define DRMP3_INLINE DRMP3_GNUC_INLINE_HINT
  50446. #endif
  50447. #elif defined(__WATCOMC__)
  50448. #define DRMP3_INLINE __inline
  50449. #else
  50450. #define DRMP3_INLINE
  50451. #endif
  50452. DRMP3_API void drmp3_version(drmp3_uint32* pMajor, drmp3_uint32* pMinor, drmp3_uint32* pRevision);
  50453. DRMP3_API const char* drmp3_version_string(void);
  50454. typedef struct
  50455. {
  50456. int frame_bytes, channels, hz, layer, bitrate_kbps;
  50457. } drmp3dec_frame_info;
  50458. typedef struct
  50459. {
  50460. float mdct_overlap[2][9*32], qmf_state[15*2*32];
  50461. int reserv, free_format_bytes;
  50462. drmp3_uint8 header[4], reserv_buf[511];
  50463. } drmp3dec;
  50464. DRMP3_API void drmp3dec_init(drmp3dec *dec);
  50465. DRMP3_API int drmp3dec_decode_frame(drmp3dec *dec, const drmp3_uint8 *mp3, int mp3_bytes, void *pcm, drmp3dec_frame_info *info);
  50466. DRMP3_API void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, size_t num_samples);
  50467. typedef enum
  50468. {
  50469. drmp3_seek_origin_start,
  50470. drmp3_seek_origin_current
  50471. } drmp3_seek_origin;
  50472. typedef struct
  50473. {
  50474. drmp3_uint64 seekPosInBytes;
  50475. drmp3_uint64 pcmFrameIndex;
  50476. drmp3_uint16 mp3FramesToDiscard;
  50477. drmp3_uint16 pcmFramesToDiscard;
  50478. } drmp3_seek_point;
  50479. typedef size_t (* drmp3_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  50480. typedef drmp3_bool32 (* drmp3_seek_proc)(void* pUserData, int offset, drmp3_seek_origin origin);
  50481. typedef struct
  50482. {
  50483. void* pUserData;
  50484. void* (* onMalloc)(size_t sz, void* pUserData);
  50485. void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  50486. void (* onFree)(void* p, void* pUserData);
  50487. } drmp3_allocation_callbacks;
  50488. typedef struct
  50489. {
  50490. drmp3_uint32 channels;
  50491. drmp3_uint32 sampleRate;
  50492. } drmp3_config;
  50493. typedef struct
  50494. {
  50495. drmp3dec decoder;
  50496. drmp3_uint32 channels;
  50497. drmp3_uint32 sampleRate;
  50498. drmp3_read_proc onRead;
  50499. drmp3_seek_proc onSeek;
  50500. void* pUserData;
  50501. drmp3_allocation_callbacks allocationCallbacks;
  50502. drmp3_uint32 mp3FrameChannels;
  50503. drmp3_uint32 mp3FrameSampleRate;
  50504. drmp3_uint32 pcmFramesConsumedInMP3Frame;
  50505. drmp3_uint32 pcmFramesRemainingInMP3Frame;
  50506. drmp3_uint8 pcmFrames[sizeof(float)*DRMP3_MAX_SAMPLES_PER_FRAME];
  50507. drmp3_uint64 currentPCMFrame;
  50508. drmp3_uint64 streamCursor;
  50509. drmp3_seek_point* pSeekPoints;
  50510. drmp3_uint32 seekPointCount;
  50511. size_t dataSize;
  50512. size_t dataCapacity;
  50513. size_t dataConsumed;
  50514. drmp3_uint8* pData;
  50515. drmp3_bool32 atEnd : 1;
  50516. struct
  50517. {
  50518. const drmp3_uint8* pData;
  50519. size_t dataSize;
  50520. size_t currentReadPos;
  50521. } memory;
  50522. } drmp3;
  50523. DRMP3_API drmp3_bool32 drmp3_init(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50524. DRMP3_API drmp3_bool32 drmp3_init_memory(drmp3* pMP3, const void* pData, size_t dataSize, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50525. #ifndef DR_MP3_NO_STDIO
  50526. DRMP3_API drmp3_bool32 drmp3_init_file(drmp3* pMP3, const char* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50527. DRMP3_API drmp3_bool32 drmp3_init_file_w(drmp3* pMP3, const wchar_t* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50528. #endif
  50529. DRMP3_API void drmp3_uninit(drmp3* pMP3);
  50530. DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, float* pBufferOut);
  50531. DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_s16(drmp3* pMP3, drmp3_uint64 framesToRead, drmp3_int16* pBufferOut);
  50532. DRMP3_API drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex);
  50533. DRMP3_API drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3);
  50534. DRMP3_API drmp3_uint64 drmp3_get_mp3_frame_count(drmp3* pMP3);
  50535. DRMP3_API drmp3_bool32 drmp3_get_mp3_and_pcm_frame_count(drmp3* pMP3, drmp3_uint64* pMP3FrameCount, drmp3_uint64* pPCMFrameCount);
  50536. DRMP3_API drmp3_bool32 drmp3_calculate_seek_points(drmp3* pMP3, drmp3_uint32* pSeekPointCount, drmp3_seek_point* pSeekPoints);
  50537. DRMP3_API drmp3_bool32 drmp3_bind_seek_table(drmp3* pMP3, drmp3_uint32 seekPointCount, drmp3_seek_point* pSeekPoints);
  50538. DRMP3_API float* drmp3_open_and_read_pcm_frames_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50539. DRMP3_API drmp3_int16* drmp3_open_and_read_pcm_frames_s16(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50540. DRMP3_API float* drmp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50541. DRMP3_API drmp3_int16* drmp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50542. #ifndef DR_MP3_NO_STDIO
  50543. DRMP3_API float* drmp3_open_file_and_read_pcm_frames_f32(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50544. DRMP3_API drmp3_int16* drmp3_open_file_and_read_pcm_frames_s16(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50545. #endif
  50546. DRMP3_API void* drmp3_malloc(size_t sz, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50547. DRMP3_API void drmp3_free(void* p, const drmp3_allocation_callbacks* pAllocationCallbacks);
  50548. #ifdef __cplusplus
  50549. }
  50550. #endif
  50551. #endif
  50552. /* dr_mp3_h end */
  50553. #endif /* MA_NO_MP3 */
  50554. /**************************************************************************************************************************************************************
  50555. Decoding
  50556. **************************************************************************************************************************************************************/
  50557. #ifndef MA_NO_DECODING
  50558. static ma_result ma_decoder_read_bytes(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  50559. {
  50560. MA_ASSERT(pDecoder != NULL);
  50561. return pDecoder->onRead(pDecoder, pBufferOut, bytesToRead, pBytesRead);
  50562. }
  50563. static ma_result ma_decoder_seek_bytes(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin)
  50564. {
  50565. MA_ASSERT(pDecoder != NULL);
  50566. return pDecoder->onSeek(pDecoder, byteOffset, origin);
  50567. }
  50568. static ma_result ma_decoder_tell_bytes(ma_decoder* pDecoder, ma_int64* pCursor)
  50569. {
  50570. MA_ASSERT(pDecoder != NULL);
  50571. if (pDecoder->onTell == NULL) {
  50572. return MA_NOT_IMPLEMENTED;
  50573. }
  50574. return pDecoder->onTell(pDecoder, pCursor);
  50575. }
  50576. MA_API ma_decoding_backend_config ma_decoding_backend_config_init(ma_format preferredFormat, ma_uint32 seekPointCount)
  50577. {
  50578. ma_decoding_backend_config config;
  50579. MA_ZERO_OBJECT(&config);
  50580. config.preferredFormat = preferredFormat;
  50581. config.seekPointCount = seekPointCount;
  50582. return config;
  50583. }
  50584. MA_API ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate)
  50585. {
  50586. ma_decoder_config config;
  50587. MA_ZERO_OBJECT(&config);
  50588. config.format = outputFormat;
  50589. config.channels = outputChannels;
  50590. config.sampleRate = outputSampleRate;
  50591. config.resampling = ma_resampler_config_init(ma_format_unknown, 0, 0, 0, ma_resample_algorithm_linear); /* Format/channels/rate doesn't matter here. */
  50592. config.encodingFormat = ma_encoding_format_unknown;
  50593. /* Note that we are intentionally leaving the channel map empty here which will cause the default channel map to be used. */
  50594. return config;
  50595. }
  50596. MA_API ma_decoder_config ma_decoder_config_init_default()
  50597. {
  50598. return ma_decoder_config_init(ma_format_unknown, 0, 0);
  50599. }
  50600. MA_API ma_decoder_config ma_decoder_config_init_copy(const ma_decoder_config* pConfig)
  50601. {
  50602. ma_decoder_config config;
  50603. if (pConfig != NULL) {
  50604. config = *pConfig;
  50605. } else {
  50606. MA_ZERO_OBJECT(&config);
  50607. }
  50608. return config;
  50609. }
  50610. static ma_result ma_decoder__init_data_converter(ma_decoder* pDecoder, const ma_decoder_config* pConfig)
  50611. {
  50612. ma_result result;
  50613. ma_data_converter_config converterConfig;
  50614. ma_format internalFormat;
  50615. ma_uint32 internalChannels;
  50616. ma_uint32 internalSampleRate;
  50617. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  50618. MA_ASSERT(pDecoder != NULL);
  50619. MA_ASSERT(pConfig != NULL);
  50620. result = ma_data_source_get_data_format(pDecoder->pBackend, &internalFormat, &internalChannels, &internalSampleRate, internalChannelMap, ma_countof(internalChannelMap));
  50621. if (result != MA_SUCCESS) {
  50622. return result; /* Failed to retrieve the internal data format. */
  50623. }
  50624. /* Make sure we're not asking for too many channels. */
  50625. if (pConfig->channels > MA_MAX_CHANNELS) {
  50626. return MA_INVALID_ARGS;
  50627. }
  50628. /* The internal channels should have already been validated at a higher level, but we'll do it again explicitly here for safety. */
  50629. if (internalChannels > MA_MAX_CHANNELS) {
  50630. return MA_INVALID_ARGS;
  50631. }
  50632. /* Output format. */
  50633. if (pConfig->format == ma_format_unknown) {
  50634. pDecoder->outputFormat = internalFormat;
  50635. } else {
  50636. pDecoder->outputFormat = pConfig->format;
  50637. }
  50638. if (pConfig->channels == 0) {
  50639. pDecoder->outputChannels = internalChannels;
  50640. } else {
  50641. pDecoder->outputChannels = pConfig->channels;
  50642. }
  50643. if (pConfig->sampleRate == 0) {
  50644. pDecoder->outputSampleRate = internalSampleRate;
  50645. } else {
  50646. pDecoder->outputSampleRate = pConfig->sampleRate;
  50647. }
  50648. converterConfig = ma_data_converter_config_init(
  50649. internalFormat, pDecoder->outputFormat,
  50650. internalChannels, pDecoder->outputChannels,
  50651. internalSampleRate, pDecoder->outputSampleRate
  50652. );
  50653. converterConfig.pChannelMapIn = internalChannelMap;
  50654. converterConfig.pChannelMapOut = pConfig->pChannelMap;
  50655. converterConfig.channelMixMode = pConfig->channelMixMode;
  50656. converterConfig.ditherMode = pConfig->ditherMode;
  50657. converterConfig.allowDynamicSampleRate = MA_FALSE; /* Never allow dynamic sample rate conversion. Setting this to true will disable passthrough optimizations. */
  50658. converterConfig.resampling = pConfig->resampling;
  50659. result = ma_data_converter_init(&converterConfig, &pDecoder->allocationCallbacks, &pDecoder->converter);
  50660. if (result != MA_SUCCESS) {
  50661. return result;
  50662. }
  50663. /*
  50664. Now that we have the decoder we need to determine whether or not we need a heap-allocated cache. We'll
  50665. need this if the data converter does not support calculation of the required input frame count. To
  50666. determine support for this we'll just run a test.
  50667. */
  50668. {
  50669. ma_uint64 unused;
  50670. result = ma_data_converter_get_required_input_frame_count(&pDecoder->converter, 1, &unused);
  50671. if (result != MA_SUCCESS) {
  50672. /*
  50673. We were unable to calculate the required input frame count which means we'll need to use
  50674. a heap-allocated cache.
  50675. */
  50676. ma_uint64 inputCacheCapSizeInBytes;
  50677. pDecoder->inputCacheCap = MA_DATA_CONVERTER_STACK_BUFFER_SIZE / ma_get_bytes_per_frame(internalFormat, internalChannels);
  50678. /* Not strictly necessary, but keeping here for safety in case we change the default value of pDecoder->inputCacheCap. */
  50679. inputCacheCapSizeInBytes = pDecoder->inputCacheCap * ma_get_bytes_per_frame(internalFormat, internalChannels);
  50680. if (inputCacheCapSizeInBytes > MA_SIZE_MAX) {
  50681. ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks);
  50682. return MA_OUT_OF_MEMORY;
  50683. }
  50684. pDecoder->pInputCache = ma_malloc((size_t)inputCacheCapSizeInBytes, &pDecoder->allocationCallbacks); /* Safe cast to size_t. */
  50685. if (pDecoder->pInputCache == NULL) {
  50686. ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks);
  50687. return MA_OUT_OF_MEMORY;
  50688. }
  50689. }
  50690. }
  50691. return MA_SUCCESS;
  50692. }
  50693. static ma_result ma_decoder_internal_on_read__custom(void* pUserData, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  50694. {
  50695. ma_decoder* pDecoder = (ma_decoder*)pUserData;
  50696. MA_ASSERT(pDecoder != NULL);
  50697. return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead, pBytesRead);
  50698. }
  50699. static ma_result ma_decoder_internal_on_seek__custom(void* pUserData, ma_int64 offset, ma_seek_origin origin)
  50700. {
  50701. ma_decoder* pDecoder = (ma_decoder*)pUserData;
  50702. MA_ASSERT(pDecoder != NULL);
  50703. return ma_decoder_seek_bytes(pDecoder, offset, origin);
  50704. }
  50705. static ma_result ma_decoder_internal_on_tell__custom(void* pUserData, ma_int64* pCursor)
  50706. {
  50707. ma_decoder* pDecoder = (ma_decoder*)pUserData;
  50708. MA_ASSERT(pDecoder != NULL);
  50709. return ma_decoder_tell_bytes(pDecoder, pCursor);
  50710. }
  50711. static ma_result ma_decoder_init_from_vtable(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50712. {
  50713. ma_result result;
  50714. ma_decoding_backend_config backendConfig;
  50715. ma_data_source* pBackend;
  50716. MA_ASSERT(pVTable != NULL);
  50717. MA_ASSERT(pConfig != NULL);
  50718. MA_ASSERT(pDecoder != NULL);
  50719. if (pVTable->onInit == NULL) {
  50720. return MA_NOT_IMPLEMENTED;
  50721. }
  50722. backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount);
  50723. result = pVTable->onInit(pVTableUserData, ma_decoder_internal_on_read__custom, ma_decoder_internal_on_seek__custom, ma_decoder_internal_on_tell__custom, pDecoder, &backendConfig, &pDecoder->allocationCallbacks, &pBackend);
  50724. if (result != MA_SUCCESS) {
  50725. return result; /* Failed to initialize the backend from this vtable. */
  50726. }
  50727. /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */
  50728. pDecoder->pBackend = pBackend;
  50729. pDecoder->pBackendVTable = pVTable;
  50730. pDecoder->pBackendUserData = pConfig->pCustomBackendUserData;
  50731. return MA_SUCCESS;
  50732. }
  50733. static ma_result ma_decoder_init_custom__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50734. {
  50735. ma_result result = MA_NO_BACKEND;
  50736. size_t ivtable;
  50737. MA_ASSERT(pConfig != NULL);
  50738. MA_ASSERT(pDecoder != NULL);
  50739. if (pConfig->ppCustomBackendVTables == NULL) {
  50740. return MA_NO_BACKEND;
  50741. }
  50742. /* The order each backend is listed is what defines the priority. */
  50743. for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) {
  50744. const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable];
  50745. if (pVTable != NULL && pVTable->onInit != NULL) {
  50746. result = ma_decoder_init_from_vtable(pVTable, pConfig->pCustomBackendUserData, pConfig, pDecoder);
  50747. if (result == MA_SUCCESS) {
  50748. return MA_SUCCESS;
  50749. } else {
  50750. /* Initialization failed. Move on to the next one, but seek back to the start first so the next vtable starts from the first byte of the file. */
  50751. result = ma_decoder_seek_bytes(pDecoder, 0, ma_seek_origin_start);
  50752. if (result != MA_SUCCESS) {
  50753. return result; /* Failed to seek back to the start. */
  50754. }
  50755. }
  50756. } else {
  50757. /* No vtable. */
  50758. }
  50759. }
  50760. /* Getting here means we couldn't find a backend. */
  50761. return MA_NO_BACKEND;
  50762. }
  50763. /* WAV */
  50764. #ifdef dr_wav_h
  50765. #define MA_HAS_WAV
  50766. typedef struct
  50767. {
  50768. ma_data_source_base ds;
  50769. ma_read_proc onRead;
  50770. ma_seek_proc onSeek;
  50771. ma_tell_proc onTell;
  50772. void* pReadSeekTellUserData;
  50773. ma_format format; /* Can be f32, s16 or s32. */
  50774. #if !defined(MA_NO_WAV)
  50775. drwav dr;
  50776. #endif
  50777. } ma_wav;
  50778. MA_API ma_result ma_wav_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav);
  50779. MA_API ma_result ma_wav_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav);
  50780. MA_API ma_result ma_wav_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav);
  50781. MA_API ma_result ma_wav_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav);
  50782. MA_API void ma_wav_uninit(ma_wav* pWav, const ma_allocation_callbacks* pAllocationCallbacks);
  50783. MA_API ma_result ma_wav_read_pcm_frames(ma_wav* pWav, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  50784. MA_API ma_result ma_wav_seek_to_pcm_frame(ma_wav* pWav, ma_uint64 frameIndex);
  50785. MA_API ma_result ma_wav_get_data_format(ma_wav* pWav, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  50786. MA_API ma_result ma_wav_get_cursor_in_pcm_frames(ma_wav* pWav, ma_uint64* pCursor);
  50787. MA_API ma_result ma_wav_get_length_in_pcm_frames(ma_wav* pWav, ma_uint64* pLength);
  50788. static ma_result ma_wav_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  50789. {
  50790. return ma_wav_read_pcm_frames((ma_wav*)pDataSource, pFramesOut, frameCount, pFramesRead);
  50791. }
  50792. static ma_result ma_wav_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  50793. {
  50794. return ma_wav_seek_to_pcm_frame((ma_wav*)pDataSource, frameIndex);
  50795. }
  50796. static ma_result ma_wav_ds_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  50797. {
  50798. return ma_wav_get_data_format((ma_wav*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  50799. }
  50800. static ma_result ma_wav_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  50801. {
  50802. return ma_wav_get_cursor_in_pcm_frames((ma_wav*)pDataSource, pCursor);
  50803. }
  50804. static ma_result ma_wav_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  50805. {
  50806. return ma_wav_get_length_in_pcm_frames((ma_wav*)pDataSource, pLength);
  50807. }
  50808. static ma_data_source_vtable g_ma_wav_ds_vtable =
  50809. {
  50810. ma_wav_ds_read,
  50811. ma_wav_ds_seek,
  50812. ma_wav_ds_get_data_format,
  50813. ma_wav_ds_get_cursor,
  50814. ma_wav_ds_get_length,
  50815. NULL, /* onSetLooping */
  50816. 0
  50817. };
  50818. #if !defined(MA_NO_WAV)
  50819. static drwav_allocation_callbacks drwav_allocation_callbacks_from_miniaudio(const ma_allocation_callbacks* pAllocationCallbacks)
  50820. {
  50821. drwav_allocation_callbacks callbacks;
  50822. if (pAllocationCallbacks != NULL) {
  50823. callbacks.onMalloc = pAllocationCallbacks->onMalloc;
  50824. callbacks.onRealloc = pAllocationCallbacks->onRealloc;
  50825. callbacks.onFree = pAllocationCallbacks->onFree;
  50826. callbacks.pUserData = pAllocationCallbacks->pUserData;
  50827. } else {
  50828. callbacks.onMalloc = ma__malloc_default;
  50829. callbacks.onRealloc = ma__realloc_default;
  50830. callbacks.onFree = ma__free_default;
  50831. callbacks.pUserData = NULL;
  50832. }
  50833. return callbacks;
  50834. }
  50835. static size_t ma_wav_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead)
  50836. {
  50837. ma_wav* pWav = (ma_wav*)pUserData;
  50838. ma_result result;
  50839. size_t bytesRead;
  50840. MA_ASSERT(pWav != NULL);
  50841. result = pWav->onRead(pWav->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead);
  50842. (void)result;
  50843. return bytesRead;
  50844. }
  50845. static drwav_bool32 ma_wav_dr_callback__seek(void* pUserData, int offset, drwav_seek_origin origin)
  50846. {
  50847. ma_wav* pWav = (ma_wav*)pUserData;
  50848. ma_result result;
  50849. ma_seek_origin maSeekOrigin;
  50850. MA_ASSERT(pWav != NULL);
  50851. maSeekOrigin = ma_seek_origin_start;
  50852. if (origin == drwav_seek_origin_current) {
  50853. maSeekOrigin = ma_seek_origin_current;
  50854. }
  50855. result = pWav->onSeek(pWav->pReadSeekTellUserData, offset, maSeekOrigin);
  50856. if (result != MA_SUCCESS) {
  50857. return MA_FALSE;
  50858. }
  50859. return MA_TRUE;
  50860. }
  50861. #endif
  50862. static ma_result ma_wav_init_internal(const ma_decoding_backend_config* pConfig, ma_wav* pWav)
  50863. {
  50864. ma_result result;
  50865. ma_data_source_config dataSourceConfig;
  50866. if (pWav == NULL) {
  50867. return MA_INVALID_ARGS;
  50868. }
  50869. MA_ZERO_OBJECT(pWav);
  50870. pWav->format = ma_format_unknown; /* Use closest match to source file by default. */
  50871. if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16 || pConfig->preferredFormat == ma_format_s32)) {
  50872. pWav->format = pConfig->preferredFormat;
  50873. } else {
  50874. /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */
  50875. }
  50876. dataSourceConfig = ma_data_source_config_init();
  50877. dataSourceConfig.vtable = &g_ma_wav_ds_vtable;
  50878. result = ma_data_source_init(&dataSourceConfig, &pWav->ds);
  50879. if (result != MA_SUCCESS) {
  50880. return result; /* Failed to initialize the base data source. */
  50881. }
  50882. return MA_SUCCESS;
  50883. }
  50884. MA_API ma_result ma_wav_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav)
  50885. {
  50886. ma_result result;
  50887. result = ma_wav_init_internal(pConfig, pWav);
  50888. if (result != MA_SUCCESS) {
  50889. return result;
  50890. }
  50891. if (onRead == NULL || onSeek == NULL) {
  50892. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  50893. }
  50894. pWav->onRead = onRead;
  50895. pWav->onSeek = onSeek;
  50896. pWav->onTell = onTell;
  50897. pWav->pReadSeekTellUserData = pReadSeekTellUserData;
  50898. #if !defined(MA_NO_WAV)
  50899. {
  50900. drwav_allocation_callbacks wavAllocationCallbacks = drwav_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  50901. drwav_bool32 wavResult;
  50902. wavResult = drwav_init(&pWav->dr, ma_wav_dr_callback__read, ma_wav_dr_callback__seek, pWav, &wavAllocationCallbacks);
  50903. if (wavResult != MA_TRUE) {
  50904. return MA_INVALID_FILE;
  50905. }
  50906. /*
  50907. If an explicit format was not specified, try picking the closest match based on the internal
  50908. format. The format needs to be supported by miniaudio.
  50909. */
  50910. if (pWav->format == ma_format_unknown) {
  50911. switch (pWav->dr.translatedFormatTag)
  50912. {
  50913. case DR_WAVE_FORMAT_PCM:
  50914. {
  50915. if (pWav->dr.bitsPerSample == 8) {
  50916. pWav->format = ma_format_u8;
  50917. } else if (pWav->dr.bitsPerSample == 16) {
  50918. pWav->format = ma_format_s16;
  50919. } else if (pWav->dr.bitsPerSample == 24) {
  50920. pWav->format = ma_format_s24;
  50921. } else if (pWav->dr.bitsPerSample == 32) {
  50922. pWav->format = ma_format_s32;
  50923. }
  50924. } break;
  50925. case DR_WAVE_FORMAT_IEEE_FLOAT:
  50926. {
  50927. if (pWav->dr.bitsPerSample == 32) {
  50928. pWav->format = ma_format_f32;
  50929. }
  50930. } break;
  50931. default: break;
  50932. }
  50933. /* Fall back to f32 if we couldn't find anything. */
  50934. if (pWav->format == ma_format_unknown) {
  50935. pWav->format = ma_format_f32;
  50936. }
  50937. }
  50938. return MA_SUCCESS;
  50939. }
  50940. #else
  50941. {
  50942. /* wav is disabled. */
  50943. (void)pAllocationCallbacks;
  50944. return MA_NOT_IMPLEMENTED;
  50945. }
  50946. #endif
  50947. }
  50948. MA_API ma_result ma_wav_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav)
  50949. {
  50950. ma_result result;
  50951. result = ma_wav_init_internal(pConfig, pWav);
  50952. if (result != MA_SUCCESS) {
  50953. return result;
  50954. }
  50955. #if !defined(MA_NO_WAV)
  50956. {
  50957. drwav_allocation_callbacks wavAllocationCallbacks = drwav_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  50958. drwav_bool32 wavResult;
  50959. wavResult = drwav_init_file(&pWav->dr, pFilePath, &wavAllocationCallbacks);
  50960. if (wavResult != MA_TRUE) {
  50961. return MA_INVALID_FILE;
  50962. }
  50963. return MA_SUCCESS;
  50964. }
  50965. #else
  50966. {
  50967. /* wav is disabled. */
  50968. (void)pFilePath;
  50969. (void)pAllocationCallbacks;
  50970. return MA_NOT_IMPLEMENTED;
  50971. }
  50972. #endif
  50973. }
  50974. MA_API ma_result ma_wav_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav)
  50975. {
  50976. ma_result result;
  50977. result = ma_wav_init_internal(pConfig, pWav);
  50978. if (result != MA_SUCCESS) {
  50979. return result;
  50980. }
  50981. #if !defined(MA_NO_WAV)
  50982. {
  50983. drwav_allocation_callbacks wavAllocationCallbacks = drwav_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  50984. drwav_bool32 wavResult;
  50985. wavResult = drwav_init_file_w(&pWav->dr, pFilePath, &wavAllocationCallbacks);
  50986. if (wavResult != MA_TRUE) {
  50987. return MA_INVALID_FILE;
  50988. }
  50989. return MA_SUCCESS;
  50990. }
  50991. #else
  50992. {
  50993. /* wav is disabled. */
  50994. (void)pFilePath;
  50995. (void)pAllocationCallbacks;
  50996. return MA_NOT_IMPLEMENTED;
  50997. }
  50998. #endif
  50999. }
  51000. MA_API ma_result ma_wav_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_wav* pWav)
  51001. {
  51002. ma_result result;
  51003. result = ma_wav_init_internal(pConfig, pWav);
  51004. if (result != MA_SUCCESS) {
  51005. return result;
  51006. }
  51007. #if !defined(MA_NO_WAV)
  51008. {
  51009. drwav_allocation_callbacks wavAllocationCallbacks = drwav_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  51010. drwav_bool32 wavResult;
  51011. wavResult = drwav_init_memory(&pWav->dr, pData, dataSize, &wavAllocationCallbacks);
  51012. if (wavResult != MA_TRUE) {
  51013. return MA_INVALID_FILE;
  51014. }
  51015. return MA_SUCCESS;
  51016. }
  51017. #else
  51018. {
  51019. /* wav is disabled. */
  51020. (void)pData;
  51021. (void)dataSize;
  51022. (void)pAllocationCallbacks;
  51023. return MA_NOT_IMPLEMENTED;
  51024. }
  51025. #endif
  51026. }
  51027. MA_API void ma_wav_uninit(ma_wav* pWav, const ma_allocation_callbacks* pAllocationCallbacks)
  51028. {
  51029. if (pWav == NULL) {
  51030. return;
  51031. }
  51032. (void)pAllocationCallbacks;
  51033. #if !defined(MA_NO_WAV)
  51034. {
  51035. drwav_uninit(&pWav->dr);
  51036. }
  51037. #else
  51038. {
  51039. /* wav is disabled. Should never hit this since initialization would have failed. */
  51040. MA_ASSERT(MA_FALSE);
  51041. }
  51042. #endif
  51043. ma_data_source_uninit(&pWav->ds);
  51044. }
  51045. MA_API ma_result ma_wav_read_pcm_frames(ma_wav* pWav, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51046. {
  51047. if (pFramesRead != NULL) {
  51048. *pFramesRead = 0;
  51049. }
  51050. if (frameCount == 0) {
  51051. return MA_INVALID_ARGS;
  51052. }
  51053. if (pWav == NULL) {
  51054. return MA_INVALID_ARGS;
  51055. }
  51056. #if !defined(MA_NO_WAV)
  51057. {
  51058. /* We always use floating point format. */
  51059. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  51060. ma_uint64 totalFramesRead = 0;
  51061. ma_format format;
  51062. ma_wav_get_data_format(pWav, &format, NULL, NULL, NULL, 0);
  51063. switch (format)
  51064. {
  51065. case ma_format_f32:
  51066. {
  51067. totalFramesRead = drwav_read_pcm_frames_f32(&pWav->dr, frameCount, (float*)pFramesOut);
  51068. } break;
  51069. case ma_format_s16:
  51070. {
  51071. totalFramesRead = drwav_read_pcm_frames_s16(&pWav->dr, frameCount, (drwav_int16*)pFramesOut);
  51072. } break;
  51073. case ma_format_s32:
  51074. {
  51075. totalFramesRead = drwav_read_pcm_frames_s32(&pWav->dr, frameCount, (drwav_int32*)pFramesOut);
  51076. } break;
  51077. /* Fallback to a raw read. */
  51078. case ma_format_unknown: return MA_INVALID_OPERATION; /* <-- this should never be hit because initialization would just fall back to a supported format. */
  51079. default:
  51080. {
  51081. totalFramesRead = drwav_read_pcm_frames(&pWav->dr, frameCount, pFramesOut);
  51082. } break;
  51083. }
  51084. /* In the future we'll update dr_wav to return MA_AT_END for us. */
  51085. if (totalFramesRead == 0) {
  51086. result = MA_AT_END;
  51087. }
  51088. if (pFramesRead != NULL) {
  51089. *pFramesRead = totalFramesRead;
  51090. }
  51091. if (result == MA_SUCCESS && totalFramesRead == 0) {
  51092. result = MA_AT_END;
  51093. }
  51094. return result;
  51095. }
  51096. #else
  51097. {
  51098. /* wav is disabled. Should never hit this since initialization would have failed. */
  51099. MA_ASSERT(MA_FALSE);
  51100. (void)pFramesOut;
  51101. (void)frameCount;
  51102. (void)pFramesRead;
  51103. return MA_NOT_IMPLEMENTED;
  51104. }
  51105. #endif
  51106. }
  51107. MA_API ma_result ma_wav_seek_to_pcm_frame(ma_wav* pWav, ma_uint64 frameIndex)
  51108. {
  51109. if (pWav == NULL) {
  51110. return MA_INVALID_ARGS;
  51111. }
  51112. #if !defined(MA_NO_WAV)
  51113. {
  51114. drwav_bool32 wavResult;
  51115. wavResult = drwav_seek_to_pcm_frame(&pWav->dr, frameIndex);
  51116. if (wavResult != DRWAV_TRUE) {
  51117. return MA_ERROR;
  51118. }
  51119. return MA_SUCCESS;
  51120. }
  51121. #else
  51122. {
  51123. /* wav is disabled. Should never hit this since initialization would have failed. */
  51124. MA_ASSERT(MA_FALSE);
  51125. (void)frameIndex;
  51126. return MA_NOT_IMPLEMENTED;
  51127. }
  51128. #endif
  51129. }
  51130. MA_API ma_result ma_wav_get_data_format(ma_wav* pWav, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  51131. {
  51132. /* Defaults for safety. */
  51133. if (pFormat != NULL) {
  51134. *pFormat = ma_format_unknown;
  51135. }
  51136. if (pChannels != NULL) {
  51137. *pChannels = 0;
  51138. }
  51139. if (pSampleRate != NULL) {
  51140. *pSampleRate = 0;
  51141. }
  51142. if (pChannelMap != NULL) {
  51143. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  51144. }
  51145. if (pWav == NULL) {
  51146. return MA_INVALID_OPERATION;
  51147. }
  51148. if (pFormat != NULL) {
  51149. *pFormat = pWav->format;
  51150. }
  51151. #if !defined(MA_NO_WAV)
  51152. {
  51153. if (pChannels != NULL) {
  51154. *pChannels = pWav->dr.channels;
  51155. }
  51156. if (pSampleRate != NULL) {
  51157. *pSampleRate = pWav->dr.sampleRate;
  51158. }
  51159. if (pChannelMap != NULL) {
  51160. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channelMapCap, pWav->dr.channels);
  51161. }
  51162. return MA_SUCCESS;
  51163. }
  51164. #else
  51165. {
  51166. /* wav is disabled. Should never hit this since initialization would have failed. */
  51167. MA_ASSERT(MA_FALSE);
  51168. return MA_NOT_IMPLEMENTED;
  51169. }
  51170. #endif
  51171. }
  51172. MA_API ma_result ma_wav_get_cursor_in_pcm_frames(ma_wav* pWav, ma_uint64* pCursor)
  51173. {
  51174. if (pCursor == NULL) {
  51175. return MA_INVALID_ARGS;
  51176. }
  51177. *pCursor = 0; /* Safety. */
  51178. if (pWav == NULL) {
  51179. return MA_INVALID_ARGS;
  51180. }
  51181. #if !defined(MA_NO_WAV)
  51182. {
  51183. drwav_result wavResult = drwav_get_cursor_in_pcm_frames(&pWav->dr, pCursor);
  51184. if (wavResult != DRWAV_SUCCESS) {
  51185. return (ma_result)wavResult; /* dr_wav result codes map to miniaudio's. */
  51186. }
  51187. return MA_SUCCESS;
  51188. }
  51189. #else
  51190. {
  51191. /* wav is disabled. Should never hit this since initialization would have failed. */
  51192. MA_ASSERT(MA_FALSE);
  51193. return MA_NOT_IMPLEMENTED;
  51194. }
  51195. #endif
  51196. }
  51197. MA_API ma_result ma_wav_get_length_in_pcm_frames(ma_wav* pWav, ma_uint64* pLength)
  51198. {
  51199. if (pLength == NULL) {
  51200. return MA_INVALID_ARGS;
  51201. }
  51202. *pLength = 0; /* Safety. */
  51203. if (pWav == NULL) {
  51204. return MA_INVALID_ARGS;
  51205. }
  51206. #if !defined(MA_NO_WAV)
  51207. {
  51208. drwav_result wavResult = drwav_get_length_in_pcm_frames(&pWav->dr, pLength);
  51209. if (wavResult != DRWAV_SUCCESS) {
  51210. return (ma_result)wavResult; /* dr_wav result codes map to miniaudio's. */
  51211. }
  51212. return MA_SUCCESS;
  51213. }
  51214. #else
  51215. {
  51216. /* wav is disabled. Should never hit this since initialization would have failed. */
  51217. MA_ASSERT(MA_FALSE);
  51218. return MA_NOT_IMPLEMENTED;
  51219. }
  51220. #endif
  51221. }
  51222. static ma_result ma_decoding_backend_init__wav(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  51223. {
  51224. ma_result result;
  51225. ma_wav* pWav;
  51226. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  51227. /* For now we're just allocating the decoder backend on the heap. */
  51228. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  51229. if (pWav == NULL) {
  51230. return MA_OUT_OF_MEMORY;
  51231. }
  51232. result = ma_wav_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pWav);
  51233. if (result != MA_SUCCESS) {
  51234. ma_free(pWav, pAllocationCallbacks);
  51235. return result;
  51236. }
  51237. *ppBackend = pWav;
  51238. return MA_SUCCESS;
  51239. }
  51240. static ma_result ma_decoding_backend_init_file__wav(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  51241. {
  51242. ma_result result;
  51243. ma_wav* pWav;
  51244. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  51245. /* For now we're just allocating the decoder backend on the heap. */
  51246. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  51247. if (pWav == NULL) {
  51248. return MA_OUT_OF_MEMORY;
  51249. }
  51250. result = ma_wav_init_file(pFilePath, pConfig, pAllocationCallbacks, pWav);
  51251. if (result != MA_SUCCESS) {
  51252. ma_free(pWav, pAllocationCallbacks);
  51253. return result;
  51254. }
  51255. *ppBackend = pWav;
  51256. return MA_SUCCESS;
  51257. }
  51258. static ma_result ma_decoding_backend_init_file_w__wav(void* pUserData, const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  51259. {
  51260. ma_result result;
  51261. ma_wav* pWav;
  51262. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  51263. /* For now we're just allocating the decoder backend on the heap. */
  51264. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  51265. if (pWav == NULL) {
  51266. return MA_OUT_OF_MEMORY;
  51267. }
  51268. result = ma_wav_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pWav);
  51269. if (result != MA_SUCCESS) {
  51270. ma_free(pWav, pAllocationCallbacks);
  51271. return result;
  51272. }
  51273. *ppBackend = pWav;
  51274. return MA_SUCCESS;
  51275. }
  51276. static ma_result ma_decoding_backend_init_memory__wav(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  51277. {
  51278. ma_result result;
  51279. ma_wav* pWav;
  51280. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  51281. /* For now we're just allocating the decoder backend on the heap. */
  51282. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  51283. if (pWav == NULL) {
  51284. return MA_OUT_OF_MEMORY;
  51285. }
  51286. result = ma_wav_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pWav);
  51287. if (result != MA_SUCCESS) {
  51288. ma_free(pWav, pAllocationCallbacks);
  51289. return result;
  51290. }
  51291. *ppBackend = pWav;
  51292. return MA_SUCCESS;
  51293. }
  51294. static void ma_decoding_backend_uninit__wav(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  51295. {
  51296. ma_wav* pWav = (ma_wav*)pBackend;
  51297. (void)pUserData;
  51298. ma_wav_uninit(pWav, pAllocationCallbacks);
  51299. ma_free(pWav, pAllocationCallbacks);
  51300. }
  51301. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_wav =
  51302. {
  51303. ma_decoding_backend_init__wav,
  51304. ma_decoding_backend_init_file__wav,
  51305. ma_decoding_backend_init_file_w__wav,
  51306. ma_decoding_backend_init_memory__wav,
  51307. ma_decoding_backend_uninit__wav
  51308. };
  51309. static ma_result ma_decoder_init_wav__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51310. {
  51311. return ma_decoder_init_from_vtable(&g_ma_decoding_backend_vtable_wav, NULL, pConfig, pDecoder);
  51312. }
  51313. #endif /* dr_wav_h */
  51314. /* FLAC */
  51315. #ifdef dr_flac_h
  51316. #define MA_HAS_FLAC
  51317. typedef struct
  51318. {
  51319. ma_data_source_base ds;
  51320. ma_read_proc onRead;
  51321. ma_seek_proc onSeek;
  51322. ma_tell_proc onTell;
  51323. void* pReadSeekTellUserData;
  51324. ma_format format; /* Can be f32, s16 or s32. */
  51325. #if !defined(MA_NO_FLAC)
  51326. drflac* dr;
  51327. #endif
  51328. } ma_flac;
  51329. MA_API ma_result ma_flac_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac);
  51330. MA_API ma_result ma_flac_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac);
  51331. MA_API ma_result ma_flac_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac);
  51332. MA_API ma_result ma_flac_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac);
  51333. MA_API void ma_flac_uninit(ma_flac* pFlac, const ma_allocation_callbacks* pAllocationCallbacks);
  51334. MA_API ma_result ma_flac_read_pcm_frames(ma_flac* pFlac, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  51335. MA_API ma_result ma_flac_seek_to_pcm_frame(ma_flac* pFlac, ma_uint64 frameIndex);
  51336. MA_API ma_result ma_flac_get_data_format(ma_flac* pFlac, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  51337. MA_API ma_result ma_flac_get_cursor_in_pcm_frames(ma_flac* pFlac, ma_uint64* pCursor);
  51338. MA_API ma_result ma_flac_get_length_in_pcm_frames(ma_flac* pFlac, ma_uint64* pLength);
  51339. static ma_result ma_flac_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51340. {
  51341. return ma_flac_read_pcm_frames((ma_flac*)pDataSource, pFramesOut, frameCount, pFramesRead);
  51342. }
  51343. static ma_result ma_flac_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  51344. {
  51345. return ma_flac_seek_to_pcm_frame((ma_flac*)pDataSource, frameIndex);
  51346. }
  51347. static ma_result ma_flac_ds_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  51348. {
  51349. return ma_flac_get_data_format((ma_flac*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  51350. }
  51351. static ma_result ma_flac_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  51352. {
  51353. return ma_flac_get_cursor_in_pcm_frames((ma_flac*)pDataSource, pCursor);
  51354. }
  51355. static ma_result ma_flac_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  51356. {
  51357. return ma_flac_get_length_in_pcm_frames((ma_flac*)pDataSource, pLength);
  51358. }
  51359. static ma_data_source_vtable g_ma_flac_ds_vtable =
  51360. {
  51361. ma_flac_ds_read,
  51362. ma_flac_ds_seek,
  51363. ma_flac_ds_get_data_format,
  51364. ma_flac_ds_get_cursor,
  51365. ma_flac_ds_get_length,
  51366. NULL, /* onSetLooping */
  51367. 0
  51368. };
  51369. #if !defined(MA_NO_FLAC)
  51370. static drflac_allocation_callbacks drflac_allocation_callbacks_from_miniaudio(const ma_allocation_callbacks* pAllocationCallbacks)
  51371. {
  51372. drflac_allocation_callbacks callbacks;
  51373. if (pAllocationCallbacks != NULL) {
  51374. callbacks.onMalloc = pAllocationCallbacks->onMalloc;
  51375. callbacks.onRealloc = pAllocationCallbacks->onRealloc;
  51376. callbacks.onFree = pAllocationCallbacks->onFree;
  51377. callbacks.pUserData = pAllocationCallbacks->pUserData;
  51378. } else {
  51379. callbacks.onMalloc = ma__malloc_default;
  51380. callbacks.onRealloc = ma__realloc_default;
  51381. callbacks.onFree = ma__free_default;
  51382. callbacks.pUserData = NULL;
  51383. }
  51384. return callbacks;
  51385. }
  51386. static size_t ma_flac_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead)
  51387. {
  51388. ma_flac* pFlac = (ma_flac*)pUserData;
  51389. ma_result result;
  51390. size_t bytesRead;
  51391. MA_ASSERT(pFlac != NULL);
  51392. result = pFlac->onRead(pFlac->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead);
  51393. (void)result;
  51394. return bytesRead;
  51395. }
  51396. static drflac_bool32 ma_flac_dr_callback__seek(void* pUserData, int offset, drflac_seek_origin origin)
  51397. {
  51398. ma_flac* pFlac = (ma_flac*)pUserData;
  51399. ma_result result;
  51400. ma_seek_origin maSeekOrigin;
  51401. MA_ASSERT(pFlac != NULL);
  51402. maSeekOrigin = ma_seek_origin_start;
  51403. if (origin == drflac_seek_origin_current) {
  51404. maSeekOrigin = ma_seek_origin_current;
  51405. }
  51406. result = pFlac->onSeek(pFlac->pReadSeekTellUserData, offset, maSeekOrigin);
  51407. if (result != MA_SUCCESS) {
  51408. return MA_FALSE;
  51409. }
  51410. return MA_TRUE;
  51411. }
  51412. #endif
  51413. static ma_result ma_flac_init_internal(const ma_decoding_backend_config* pConfig, ma_flac* pFlac)
  51414. {
  51415. ma_result result;
  51416. ma_data_source_config dataSourceConfig;
  51417. if (pFlac == NULL) {
  51418. return MA_INVALID_ARGS;
  51419. }
  51420. MA_ZERO_OBJECT(pFlac);
  51421. pFlac->format = ma_format_f32; /* f32 by default. */
  51422. if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16 || pConfig->preferredFormat == ma_format_s32)) {
  51423. pFlac->format = pConfig->preferredFormat;
  51424. } else {
  51425. /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */
  51426. }
  51427. dataSourceConfig = ma_data_source_config_init();
  51428. dataSourceConfig.vtable = &g_ma_flac_ds_vtable;
  51429. result = ma_data_source_init(&dataSourceConfig, &pFlac->ds);
  51430. if (result != MA_SUCCESS) {
  51431. return result; /* Failed to initialize the base data source. */
  51432. }
  51433. return MA_SUCCESS;
  51434. }
  51435. MA_API ma_result ma_flac_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac)
  51436. {
  51437. ma_result result;
  51438. result = ma_flac_init_internal(pConfig, pFlac);
  51439. if (result != MA_SUCCESS) {
  51440. return result;
  51441. }
  51442. if (onRead == NULL || onSeek == NULL) {
  51443. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  51444. }
  51445. pFlac->onRead = onRead;
  51446. pFlac->onSeek = onSeek;
  51447. pFlac->onTell = onTell;
  51448. pFlac->pReadSeekTellUserData = pReadSeekTellUserData;
  51449. #if !defined(MA_NO_FLAC)
  51450. {
  51451. drflac_allocation_callbacks flacAllocationCallbacks = drflac_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  51452. pFlac->dr = drflac_open(ma_flac_dr_callback__read, ma_flac_dr_callback__seek, pFlac, &flacAllocationCallbacks);
  51453. if (pFlac->dr == NULL) {
  51454. return MA_INVALID_FILE;
  51455. }
  51456. return MA_SUCCESS;
  51457. }
  51458. #else
  51459. {
  51460. /* flac is disabled. */
  51461. (void)pAllocationCallbacks;
  51462. return MA_NOT_IMPLEMENTED;
  51463. }
  51464. #endif
  51465. }
  51466. MA_API ma_result ma_flac_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac)
  51467. {
  51468. ma_result result;
  51469. result = ma_flac_init_internal(pConfig, pFlac);
  51470. if (result != MA_SUCCESS) {
  51471. return result;
  51472. }
  51473. #if !defined(MA_NO_FLAC)
  51474. {
  51475. drflac_allocation_callbacks flacAllocationCallbacks = drflac_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  51476. pFlac->dr = drflac_open_file(pFilePath, &flacAllocationCallbacks);
  51477. if (pFlac->dr == NULL) {
  51478. return MA_INVALID_FILE;
  51479. }
  51480. return MA_SUCCESS;
  51481. }
  51482. #else
  51483. {
  51484. /* flac is disabled. */
  51485. (void)pFilePath;
  51486. (void)pAllocationCallbacks;
  51487. return MA_NOT_IMPLEMENTED;
  51488. }
  51489. #endif
  51490. }
  51491. MA_API ma_result ma_flac_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac)
  51492. {
  51493. ma_result result;
  51494. result = ma_flac_init_internal(pConfig, pFlac);
  51495. if (result != MA_SUCCESS) {
  51496. return result;
  51497. }
  51498. #if !defined(MA_NO_FLAC)
  51499. {
  51500. drflac_allocation_callbacks flacAllocationCallbacks = drflac_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  51501. pFlac->dr = drflac_open_file_w(pFilePath, &flacAllocationCallbacks);
  51502. if (pFlac->dr == NULL) {
  51503. return MA_INVALID_FILE;
  51504. }
  51505. return MA_SUCCESS;
  51506. }
  51507. #else
  51508. {
  51509. /* flac is disabled. */
  51510. (void)pFilePath;
  51511. (void)pAllocationCallbacks;
  51512. return MA_NOT_IMPLEMENTED;
  51513. }
  51514. #endif
  51515. }
  51516. MA_API ma_result ma_flac_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_flac* pFlac)
  51517. {
  51518. ma_result result;
  51519. result = ma_flac_init_internal(pConfig, pFlac);
  51520. if (result != MA_SUCCESS) {
  51521. return result;
  51522. }
  51523. #if !defined(MA_NO_FLAC)
  51524. {
  51525. drflac_allocation_callbacks flacAllocationCallbacks = drflac_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  51526. pFlac->dr = drflac_open_memory(pData, dataSize, &flacAllocationCallbacks);
  51527. if (pFlac->dr == NULL) {
  51528. return MA_INVALID_FILE;
  51529. }
  51530. return MA_SUCCESS;
  51531. }
  51532. #else
  51533. {
  51534. /* flac is disabled. */
  51535. (void)pData;
  51536. (void)dataSize;
  51537. (void)pAllocationCallbacks;
  51538. return MA_NOT_IMPLEMENTED;
  51539. }
  51540. #endif
  51541. }
  51542. MA_API void ma_flac_uninit(ma_flac* pFlac, const ma_allocation_callbacks* pAllocationCallbacks)
  51543. {
  51544. if (pFlac == NULL) {
  51545. return;
  51546. }
  51547. (void)pAllocationCallbacks;
  51548. #if !defined(MA_NO_FLAC)
  51549. {
  51550. drflac_close(pFlac->dr);
  51551. }
  51552. #else
  51553. {
  51554. /* flac is disabled. Should never hit this since initialization would have failed. */
  51555. MA_ASSERT(MA_FALSE);
  51556. }
  51557. #endif
  51558. ma_data_source_uninit(&pFlac->ds);
  51559. }
  51560. MA_API ma_result ma_flac_read_pcm_frames(ma_flac* pFlac, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51561. {
  51562. if (pFramesRead != NULL) {
  51563. *pFramesRead = 0;
  51564. }
  51565. if (frameCount == 0) {
  51566. return MA_INVALID_ARGS;
  51567. }
  51568. if (pFlac == NULL) {
  51569. return MA_INVALID_ARGS;
  51570. }
  51571. #if !defined(MA_NO_FLAC)
  51572. {
  51573. /* We always use floating point format. */
  51574. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  51575. ma_uint64 totalFramesRead = 0;
  51576. ma_format format;
  51577. ma_flac_get_data_format(pFlac, &format, NULL, NULL, NULL, 0);
  51578. switch (format)
  51579. {
  51580. case ma_format_f32:
  51581. {
  51582. totalFramesRead = drflac_read_pcm_frames_f32(pFlac->dr, frameCount, (float*)pFramesOut);
  51583. } break;
  51584. case ma_format_s16:
  51585. {
  51586. totalFramesRead = drflac_read_pcm_frames_s16(pFlac->dr, frameCount, (drflac_int16*)pFramesOut);
  51587. } break;
  51588. case ma_format_s32:
  51589. {
  51590. totalFramesRead = drflac_read_pcm_frames_s32(pFlac->dr, frameCount, (drflac_int32*)pFramesOut);
  51591. } break;
  51592. case ma_format_u8:
  51593. case ma_format_s24:
  51594. case ma_format_unknown:
  51595. default:
  51596. {
  51597. return MA_INVALID_OPERATION;
  51598. };
  51599. }
  51600. /* In the future we'll update dr_flac to return MA_AT_END for us. */
  51601. if (totalFramesRead == 0) {
  51602. result = MA_AT_END;
  51603. }
  51604. if (pFramesRead != NULL) {
  51605. *pFramesRead = totalFramesRead;
  51606. }
  51607. if (result == MA_SUCCESS && totalFramesRead == 0) {
  51608. result = MA_AT_END;
  51609. }
  51610. return result;
  51611. }
  51612. #else
  51613. {
  51614. /* flac is disabled. Should never hit this since initialization would have failed. */
  51615. MA_ASSERT(MA_FALSE);
  51616. (void)pFramesOut;
  51617. (void)frameCount;
  51618. (void)pFramesRead;
  51619. return MA_NOT_IMPLEMENTED;
  51620. }
  51621. #endif
  51622. }
  51623. MA_API ma_result ma_flac_seek_to_pcm_frame(ma_flac* pFlac, ma_uint64 frameIndex)
  51624. {
  51625. if (pFlac == NULL) {
  51626. return MA_INVALID_ARGS;
  51627. }
  51628. #if !defined(MA_NO_FLAC)
  51629. {
  51630. drflac_bool32 flacResult;
  51631. flacResult = drflac_seek_to_pcm_frame(pFlac->dr, frameIndex);
  51632. if (flacResult != DRFLAC_TRUE) {
  51633. return MA_ERROR;
  51634. }
  51635. return MA_SUCCESS;
  51636. }
  51637. #else
  51638. {
  51639. /* flac is disabled. Should never hit this since initialization would have failed. */
  51640. MA_ASSERT(MA_FALSE);
  51641. (void)frameIndex;
  51642. return MA_NOT_IMPLEMENTED;
  51643. }
  51644. #endif
  51645. }
  51646. MA_API ma_result ma_flac_get_data_format(ma_flac* pFlac, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  51647. {
  51648. /* Defaults for safety. */
  51649. if (pFormat != NULL) {
  51650. *pFormat = ma_format_unknown;
  51651. }
  51652. if (pChannels != NULL) {
  51653. *pChannels = 0;
  51654. }
  51655. if (pSampleRate != NULL) {
  51656. *pSampleRate = 0;
  51657. }
  51658. if (pChannelMap != NULL) {
  51659. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  51660. }
  51661. if (pFlac == NULL) {
  51662. return MA_INVALID_OPERATION;
  51663. }
  51664. if (pFormat != NULL) {
  51665. *pFormat = pFlac->format;
  51666. }
  51667. #if !defined(MA_NO_FLAC)
  51668. {
  51669. if (pChannels != NULL) {
  51670. *pChannels = pFlac->dr->channels;
  51671. }
  51672. if (pSampleRate != NULL) {
  51673. *pSampleRate = pFlac->dr->sampleRate;
  51674. }
  51675. if (pChannelMap != NULL) {
  51676. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channelMapCap, pFlac->dr->channels);
  51677. }
  51678. return MA_SUCCESS;
  51679. }
  51680. #else
  51681. {
  51682. /* flac is disabled. Should never hit this since initialization would have failed. */
  51683. MA_ASSERT(MA_FALSE);
  51684. return MA_NOT_IMPLEMENTED;
  51685. }
  51686. #endif
  51687. }
  51688. MA_API ma_result ma_flac_get_cursor_in_pcm_frames(ma_flac* pFlac, ma_uint64* pCursor)
  51689. {
  51690. if (pCursor == NULL) {
  51691. return MA_INVALID_ARGS;
  51692. }
  51693. *pCursor = 0; /* Safety. */
  51694. if (pFlac == NULL) {
  51695. return MA_INVALID_ARGS;
  51696. }
  51697. #if !defined(MA_NO_FLAC)
  51698. {
  51699. *pCursor = pFlac->dr->currentPCMFrame;
  51700. return MA_SUCCESS;
  51701. }
  51702. #else
  51703. {
  51704. /* flac is disabled. Should never hit this since initialization would have failed. */
  51705. MA_ASSERT(MA_FALSE);
  51706. return MA_NOT_IMPLEMENTED;
  51707. }
  51708. #endif
  51709. }
  51710. MA_API ma_result ma_flac_get_length_in_pcm_frames(ma_flac* pFlac, ma_uint64* pLength)
  51711. {
  51712. if (pLength == NULL) {
  51713. return MA_INVALID_ARGS;
  51714. }
  51715. *pLength = 0; /* Safety. */
  51716. if (pFlac == NULL) {
  51717. return MA_INVALID_ARGS;
  51718. }
  51719. #if !defined(MA_NO_FLAC)
  51720. {
  51721. *pLength = pFlac->dr->totalPCMFrameCount;
  51722. return MA_SUCCESS;
  51723. }
  51724. #else
  51725. {
  51726. /* flac is disabled. Should never hit this since initialization would have failed. */
  51727. MA_ASSERT(MA_FALSE);
  51728. return MA_NOT_IMPLEMENTED;
  51729. }
  51730. #endif
  51731. }
  51732. static ma_result ma_decoding_backend_init__flac(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  51733. {
  51734. ma_result result;
  51735. ma_flac* pFlac;
  51736. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  51737. /* For now we're just allocating the decoder backend on the heap. */
  51738. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  51739. if (pFlac == NULL) {
  51740. return MA_OUT_OF_MEMORY;
  51741. }
  51742. result = ma_flac_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pFlac);
  51743. if (result != MA_SUCCESS) {
  51744. ma_free(pFlac, pAllocationCallbacks);
  51745. return result;
  51746. }
  51747. *ppBackend = pFlac;
  51748. return MA_SUCCESS;
  51749. }
  51750. static ma_result ma_decoding_backend_init_file__flac(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  51751. {
  51752. ma_result result;
  51753. ma_flac* pFlac;
  51754. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  51755. /* For now we're just allocating the decoder backend on the heap. */
  51756. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  51757. if (pFlac == NULL) {
  51758. return MA_OUT_OF_MEMORY;
  51759. }
  51760. result = ma_flac_init_file(pFilePath, pConfig, pAllocationCallbacks, pFlac);
  51761. if (result != MA_SUCCESS) {
  51762. ma_free(pFlac, pAllocationCallbacks);
  51763. return result;
  51764. }
  51765. *ppBackend = pFlac;
  51766. return MA_SUCCESS;
  51767. }
  51768. static ma_result ma_decoding_backend_init_file_w__flac(void* pUserData, const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  51769. {
  51770. ma_result result;
  51771. ma_flac* pFlac;
  51772. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  51773. /* For now we're just allocating the decoder backend on the heap. */
  51774. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  51775. if (pFlac == NULL) {
  51776. return MA_OUT_OF_MEMORY;
  51777. }
  51778. result = ma_flac_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pFlac);
  51779. if (result != MA_SUCCESS) {
  51780. ma_free(pFlac, pAllocationCallbacks);
  51781. return result;
  51782. }
  51783. *ppBackend = pFlac;
  51784. return MA_SUCCESS;
  51785. }
  51786. static ma_result ma_decoding_backend_init_memory__flac(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  51787. {
  51788. ma_result result;
  51789. ma_flac* pFlac;
  51790. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  51791. /* For now we're just allocating the decoder backend on the heap. */
  51792. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  51793. if (pFlac == NULL) {
  51794. return MA_OUT_OF_MEMORY;
  51795. }
  51796. result = ma_flac_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pFlac);
  51797. if (result != MA_SUCCESS) {
  51798. ma_free(pFlac, pAllocationCallbacks);
  51799. return result;
  51800. }
  51801. *ppBackend = pFlac;
  51802. return MA_SUCCESS;
  51803. }
  51804. static void ma_decoding_backend_uninit__flac(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  51805. {
  51806. ma_flac* pFlac = (ma_flac*)pBackend;
  51807. (void)pUserData;
  51808. ma_flac_uninit(pFlac, pAllocationCallbacks);
  51809. ma_free(pFlac, pAllocationCallbacks);
  51810. }
  51811. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_flac =
  51812. {
  51813. ma_decoding_backend_init__flac,
  51814. ma_decoding_backend_init_file__flac,
  51815. ma_decoding_backend_init_file_w__flac,
  51816. ma_decoding_backend_init_memory__flac,
  51817. ma_decoding_backend_uninit__flac
  51818. };
  51819. static ma_result ma_decoder_init_flac__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51820. {
  51821. return ma_decoder_init_from_vtable(&g_ma_decoding_backend_vtable_flac, NULL, pConfig, pDecoder);
  51822. }
  51823. #endif /* dr_flac_h */
  51824. /* MP3 */
  51825. #ifdef dr_mp3_h
  51826. #define MA_HAS_MP3
  51827. typedef struct
  51828. {
  51829. ma_data_source_base ds;
  51830. ma_read_proc onRead;
  51831. ma_seek_proc onSeek;
  51832. ma_tell_proc onTell;
  51833. void* pReadSeekTellUserData;
  51834. ma_format format; /* Can be f32 or s16. */
  51835. #if !defined(MA_NO_MP3)
  51836. drmp3 dr;
  51837. drmp3_uint32 seekPointCount;
  51838. drmp3_seek_point* pSeekPoints; /* Only used if seek table generation is used. */
  51839. #endif
  51840. } ma_mp3;
  51841. MA_API ma_result ma_mp3_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3);
  51842. MA_API ma_result ma_mp3_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3);
  51843. MA_API ma_result ma_mp3_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3);
  51844. MA_API ma_result ma_mp3_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3);
  51845. MA_API void ma_mp3_uninit(ma_mp3* pMP3, const ma_allocation_callbacks* pAllocationCallbacks);
  51846. MA_API ma_result ma_mp3_read_pcm_frames(ma_mp3* pMP3, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  51847. MA_API ma_result ma_mp3_seek_to_pcm_frame(ma_mp3* pMP3, ma_uint64 frameIndex);
  51848. MA_API ma_result ma_mp3_get_data_format(ma_mp3* pMP3, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  51849. MA_API ma_result ma_mp3_get_cursor_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pCursor);
  51850. MA_API ma_result ma_mp3_get_length_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pLength);
  51851. static ma_result ma_mp3_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51852. {
  51853. return ma_mp3_read_pcm_frames((ma_mp3*)pDataSource, pFramesOut, frameCount, pFramesRead);
  51854. }
  51855. static ma_result ma_mp3_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  51856. {
  51857. return ma_mp3_seek_to_pcm_frame((ma_mp3*)pDataSource, frameIndex);
  51858. }
  51859. static ma_result ma_mp3_ds_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  51860. {
  51861. return ma_mp3_get_data_format((ma_mp3*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  51862. }
  51863. static ma_result ma_mp3_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  51864. {
  51865. return ma_mp3_get_cursor_in_pcm_frames((ma_mp3*)pDataSource, pCursor);
  51866. }
  51867. static ma_result ma_mp3_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  51868. {
  51869. return ma_mp3_get_length_in_pcm_frames((ma_mp3*)pDataSource, pLength);
  51870. }
  51871. static ma_data_source_vtable g_ma_mp3_ds_vtable =
  51872. {
  51873. ma_mp3_ds_read,
  51874. ma_mp3_ds_seek,
  51875. ma_mp3_ds_get_data_format,
  51876. ma_mp3_ds_get_cursor,
  51877. ma_mp3_ds_get_length,
  51878. NULL, /* onSetLooping */
  51879. 0
  51880. };
  51881. #if !defined(MA_NO_MP3)
  51882. static drmp3_allocation_callbacks drmp3_allocation_callbacks_from_miniaudio(const ma_allocation_callbacks* pAllocationCallbacks)
  51883. {
  51884. drmp3_allocation_callbacks callbacks;
  51885. if (pAllocationCallbacks != NULL) {
  51886. callbacks.onMalloc = pAllocationCallbacks->onMalloc;
  51887. callbacks.onRealloc = pAllocationCallbacks->onRealloc;
  51888. callbacks.onFree = pAllocationCallbacks->onFree;
  51889. callbacks.pUserData = pAllocationCallbacks->pUserData;
  51890. } else {
  51891. callbacks.onMalloc = ma__malloc_default;
  51892. callbacks.onRealloc = ma__realloc_default;
  51893. callbacks.onFree = ma__free_default;
  51894. callbacks.pUserData = NULL;
  51895. }
  51896. return callbacks;
  51897. }
  51898. static size_t ma_mp3_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead)
  51899. {
  51900. ma_mp3* pMP3 = (ma_mp3*)pUserData;
  51901. ma_result result;
  51902. size_t bytesRead;
  51903. MA_ASSERT(pMP3 != NULL);
  51904. result = pMP3->onRead(pMP3->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead);
  51905. (void)result;
  51906. return bytesRead;
  51907. }
  51908. static drmp3_bool32 ma_mp3_dr_callback__seek(void* pUserData, int offset, drmp3_seek_origin origin)
  51909. {
  51910. ma_mp3* pMP3 = (ma_mp3*)pUserData;
  51911. ma_result result;
  51912. ma_seek_origin maSeekOrigin;
  51913. MA_ASSERT(pMP3 != NULL);
  51914. maSeekOrigin = ma_seek_origin_start;
  51915. if (origin == drmp3_seek_origin_current) {
  51916. maSeekOrigin = ma_seek_origin_current;
  51917. }
  51918. result = pMP3->onSeek(pMP3->pReadSeekTellUserData, offset, maSeekOrigin);
  51919. if (result != MA_SUCCESS) {
  51920. return MA_FALSE;
  51921. }
  51922. return MA_TRUE;
  51923. }
  51924. #endif
  51925. static ma_result ma_mp3_init_internal(const ma_decoding_backend_config* pConfig, ma_mp3* pMP3)
  51926. {
  51927. ma_result result;
  51928. ma_data_source_config dataSourceConfig;
  51929. if (pMP3 == NULL) {
  51930. return MA_INVALID_ARGS;
  51931. }
  51932. MA_ZERO_OBJECT(pMP3);
  51933. pMP3->format = ma_format_f32; /* f32 by default. */
  51934. if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16)) {
  51935. pMP3->format = pConfig->preferredFormat;
  51936. } else {
  51937. /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */
  51938. }
  51939. dataSourceConfig = ma_data_source_config_init();
  51940. dataSourceConfig.vtable = &g_ma_mp3_ds_vtable;
  51941. result = ma_data_source_init(&dataSourceConfig, &pMP3->ds);
  51942. if (result != MA_SUCCESS) {
  51943. return result; /* Failed to initialize the base data source. */
  51944. }
  51945. return MA_SUCCESS;
  51946. }
  51947. static ma_result ma_mp3_generate_seek_table(ma_mp3* pMP3, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks)
  51948. {
  51949. drmp3_bool32 mp3Result;
  51950. drmp3_uint32 seekPointCount = 0;
  51951. drmp3_seek_point* pSeekPoints = NULL;
  51952. MA_ASSERT(pMP3 != NULL);
  51953. MA_ASSERT(pConfig != NULL);
  51954. seekPointCount = pConfig->seekPointCount;
  51955. if (seekPointCount > 0) {
  51956. pSeekPoints = (drmp3_seek_point*)ma_malloc(sizeof(*pMP3->pSeekPoints) * seekPointCount, pAllocationCallbacks);
  51957. if (pSeekPoints == NULL) {
  51958. return MA_OUT_OF_MEMORY;
  51959. }
  51960. }
  51961. mp3Result = drmp3_calculate_seek_points(&pMP3->dr, &seekPointCount, pSeekPoints);
  51962. if (mp3Result != MA_TRUE) {
  51963. ma_free(pSeekPoints, pAllocationCallbacks);
  51964. return MA_ERROR;
  51965. }
  51966. mp3Result = drmp3_bind_seek_table(&pMP3->dr, seekPointCount, pSeekPoints);
  51967. if (mp3Result != MA_TRUE) {
  51968. ma_free(pSeekPoints, pAllocationCallbacks);
  51969. return MA_ERROR;
  51970. }
  51971. pMP3->seekPointCount = seekPointCount;
  51972. pMP3->pSeekPoints = pSeekPoints;
  51973. return MA_SUCCESS;
  51974. }
  51975. MA_API ma_result ma_mp3_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3)
  51976. {
  51977. ma_result result;
  51978. result = ma_mp3_init_internal(pConfig, pMP3);
  51979. if (result != MA_SUCCESS) {
  51980. return result;
  51981. }
  51982. if (onRead == NULL || onSeek == NULL) {
  51983. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  51984. }
  51985. pMP3->onRead = onRead;
  51986. pMP3->onSeek = onSeek;
  51987. pMP3->onTell = onTell;
  51988. pMP3->pReadSeekTellUserData = pReadSeekTellUserData;
  51989. #if !defined(MA_NO_MP3)
  51990. {
  51991. drmp3_allocation_callbacks mp3AllocationCallbacks = drmp3_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  51992. drmp3_bool32 mp3Result;
  51993. mp3Result = drmp3_init(&pMP3->dr, ma_mp3_dr_callback__read, ma_mp3_dr_callback__seek, pMP3, &mp3AllocationCallbacks);
  51994. if (mp3Result != MA_TRUE) {
  51995. return MA_INVALID_FILE;
  51996. }
  51997. ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks);
  51998. return MA_SUCCESS;
  51999. }
  52000. #else
  52001. {
  52002. /* mp3 is disabled. */
  52003. (void)pAllocationCallbacks;
  52004. return MA_NOT_IMPLEMENTED;
  52005. }
  52006. #endif
  52007. }
  52008. MA_API ma_result ma_mp3_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3)
  52009. {
  52010. ma_result result;
  52011. result = ma_mp3_init_internal(pConfig, pMP3);
  52012. if (result != MA_SUCCESS) {
  52013. return result;
  52014. }
  52015. #if !defined(MA_NO_MP3)
  52016. {
  52017. drmp3_allocation_callbacks mp3AllocationCallbacks = drmp3_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  52018. drmp3_bool32 mp3Result;
  52019. mp3Result = drmp3_init_file(&pMP3->dr, pFilePath, &mp3AllocationCallbacks);
  52020. if (mp3Result != MA_TRUE) {
  52021. return MA_INVALID_FILE;
  52022. }
  52023. ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks);
  52024. return MA_SUCCESS;
  52025. }
  52026. #else
  52027. {
  52028. /* mp3 is disabled. */
  52029. (void)pFilePath;
  52030. (void)pAllocationCallbacks;
  52031. return MA_NOT_IMPLEMENTED;
  52032. }
  52033. #endif
  52034. }
  52035. MA_API ma_result ma_mp3_init_file_w(const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3)
  52036. {
  52037. ma_result result;
  52038. result = ma_mp3_init_internal(pConfig, pMP3);
  52039. if (result != MA_SUCCESS) {
  52040. return result;
  52041. }
  52042. #if !defined(MA_NO_MP3)
  52043. {
  52044. drmp3_allocation_callbacks mp3AllocationCallbacks = drmp3_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  52045. drmp3_bool32 mp3Result;
  52046. mp3Result = drmp3_init_file_w(&pMP3->dr, pFilePath, &mp3AllocationCallbacks);
  52047. if (mp3Result != MA_TRUE) {
  52048. return MA_INVALID_FILE;
  52049. }
  52050. ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks);
  52051. return MA_SUCCESS;
  52052. }
  52053. #else
  52054. {
  52055. /* mp3 is disabled. */
  52056. (void)pFilePath;
  52057. (void)pAllocationCallbacks;
  52058. return MA_NOT_IMPLEMENTED;
  52059. }
  52060. #endif
  52061. }
  52062. MA_API ma_result ma_mp3_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_mp3* pMP3)
  52063. {
  52064. ma_result result;
  52065. result = ma_mp3_init_internal(pConfig, pMP3);
  52066. if (result != MA_SUCCESS) {
  52067. return result;
  52068. }
  52069. #if !defined(MA_NO_MP3)
  52070. {
  52071. drmp3_allocation_callbacks mp3AllocationCallbacks = drmp3_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  52072. drmp3_bool32 mp3Result;
  52073. mp3Result = drmp3_init_memory(&pMP3->dr, pData, dataSize, &mp3AllocationCallbacks);
  52074. if (mp3Result != MA_TRUE) {
  52075. return MA_INVALID_FILE;
  52076. }
  52077. ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks);
  52078. return MA_SUCCESS;
  52079. }
  52080. #else
  52081. {
  52082. /* mp3 is disabled. */
  52083. (void)pData;
  52084. (void)dataSize;
  52085. (void)pAllocationCallbacks;
  52086. return MA_NOT_IMPLEMENTED;
  52087. }
  52088. #endif
  52089. }
  52090. MA_API void ma_mp3_uninit(ma_mp3* pMP3, const ma_allocation_callbacks* pAllocationCallbacks)
  52091. {
  52092. if (pMP3 == NULL) {
  52093. return;
  52094. }
  52095. #if !defined(MA_NO_MP3)
  52096. {
  52097. drmp3_uninit(&pMP3->dr);
  52098. }
  52099. #else
  52100. {
  52101. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52102. MA_ASSERT(MA_FALSE);
  52103. }
  52104. #endif
  52105. /* Seek points need to be freed after the MP3 decoder has been uninitialized to ensure they're no longer being referenced. */
  52106. ma_free(pMP3->pSeekPoints, pAllocationCallbacks);
  52107. ma_data_source_uninit(&pMP3->ds);
  52108. }
  52109. MA_API ma_result ma_mp3_read_pcm_frames(ma_mp3* pMP3, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  52110. {
  52111. if (pFramesRead != NULL) {
  52112. *pFramesRead = 0;
  52113. }
  52114. if (frameCount == 0) {
  52115. return MA_INVALID_ARGS;
  52116. }
  52117. if (pMP3 == NULL) {
  52118. return MA_INVALID_ARGS;
  52119. }
  52120. #if !defined(MA_NO_MP3)
  52121. {
  52122. /* We always use floating point format. */
  52123. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  52124. ma_uint64 totalFramesRead = 0;
  52125. ma_format format;
  52126. ma_mp3_get_data_format(pMP3, &format, NULL, NULL, NULL, 0);
  52127. switch (format)
  52128. {
  52129. case ma_format_f32:
  52130. {
  52131. totalFramesRead = drmp3_read_pcm_frames_f32(&pMP3->dr, frameCount, (float*)pFramesOut);
  52132. } break;
  52133. case ma_format_s16:
  52134. {
  52135. totalFramesRead = drmp3_read_pcm_frames_s16(&pMP3->dr, frameCount, (drmp3_int16*)pFramesOut);
  52136. } break;
  52137. case ma_format_u8:
  52138. case ma_format_s24:
  52139. case ma_format_s32:
  52140. case ma_format_unknown:
  52141. default:
  52142. {
  52143. return MA_INVALID_OPERATION;
  52144. };
  52145. }
  52146. /* In the future we'll update dr_mp3 to return MA_AT_END for us. */
  52147. if (totalFramesRead == 0) {
  52148. result = MA_AT_END;
  52149. }
  52150. if (pFramesRead != NULL) {
  52151. *pFramesRead = totalFramesRead;
  52152. }
  52153. return result;
  52154. }
  52155. #else
  52156. {
  52157. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52158. MA_ASSERT(MA_FALSE);
  52159. (void)pFramesOut;
  52160. (void)frameCount;
  52161. (void)pFramesRead;
  52162. return MA_NOT_IMPLEMENTED;
  52163. }
  52164. #endif
  52165. }
  52166. MA_API ma_result ma_mp3_seek_to_pcm_frame(ma_mp3* pMP3, ma_uint64 frameIndex)
  52167. {
  52168. if (pMP3 == NULL) {
  52169. return MA_INVALID_ARGS;
  52170. }
  52171. #if !defined(MA_NO_MP3)
  52172. {
  52173. drmp3_bool32 mp3Result;
  52174. mp3Result = drmp3_seek_to_pcm_frame(&pMP3->dr, frameIndex);
  52175. if (mp3Result != DRMP3_TRUE) {
  52176. return MA_ERROR;
  52177. }
  52178. return MA_SUCCESS;
  52179. }
  52180. #else
  52181. {
  52182. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52183. MA_ASSERT(MA_FALSE);
  52184. (void)frameIndex;
  52185. return MA_NOT_IMPLEMENTED;
  52186. }
  52187. #endif
  52188. }
  52189. MA_API ma_result ma_mp3_get_data_format(ma_mp3* pMP3, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  52190. {
  52191. /* Defaults for safety. */
  52192. if (pFormat != NULL) {
  52193. *pFormat = ma_format_unknown;
  52194. }
  52195. if (pChannels != NULL) {
  52196. *pChannels = 0;
  52197. }
  52198. if (pSampleRate != NULL) {
  52199. *pSampleRate = 0;
  52200. }
  52201. if (pChannelMap != NULL) {
  52202. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  52203. }
  52204. if (pMP3 == NULL) {
  52205. return MA_INVALID_OPERATION;
  52206. }
  52207. if (pFormat != NULL) {
  52208. *pFormat = pMP3->format;
  52209. }
  52210. #if !defined(MA_NO_MP3)
  52211. {
  52212. if (pChannels != NULL) {
  52213. *pChannels = pMP3->dr.channels;
  52214. }
  52215. if (pSampleRate != NULL) {
  52216. *pSampleRate = pMP3->dr.sampleRate;
  52217. }
  52218. if (pChannelMap != NULL) {
  52219. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pMP3->dr.channels);
  52220. }
  52221. return MA_SUCCESS;
  52222. }
  52223. #else
  52224. {
  52225. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52226. MA_ASSERT(MA_FALSE);
  52227. return MA_NOT_IMPLEMENTED;
  52228. }
  52229. #endif
  52230. }
  52231. MA_API ma_result ma_mp3_get_cursor_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pCursor)
  52232. {
  52233. if (pCursor == NULL) {
  52234. return MA_INVALID_ARGS;
  52235. }
  52236. *pCursor = 0; /* Safety. */
  52237. if (pMP3 == NULL) {
  52238. return MA_INVALID_ARGS;
  52239. }
  52240. #if !defined(MA_NO_MP3)
  52241. {
  52242. *pCursor = pMP3->dr.currentPCMFrame;
  52243. return MA_SUCCESS;
  52244. }
  52245. #else
  52246. {
  52247. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52248. MA_ASSERT(MA_FALSE);
  52249. return MA_NOT_IMPLEMENTED;
  52250. }
  52251. #endif
  52252. }
  52253. MA_API ma_result ma_mp3_get_length_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pLength)
  52254. {
  52255. if (pLength == NULL) {
  52256. return MA_INVALID_ARGS;
  52257. }
  52258. *pLength = 0; /* Safety. */
  52259. if (pMP3 == NULL) {
  52260. return MA_INVALID_ARGS;
  52261. }
  52262. #if !defined(MA_NO_MP3)
  52263. {
  52264. *pLength = drmp3_get_pcm_frame_count(&pMP3->dr);
  52265. return MA_SUCCESS;
  52266. }
  52267. #else
  52268. {
  52269. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52270. MA_ASSERT(MA_FALSE);
  52271. return MA_NOT_IMPLEMENTED;
  52272. }
  52273. #endif
  52274. }
  52275. static ma_result ma_decoding_backend_init__mp3(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  52276. {
  52277. ma_result result;
  52278. ma_mp3* pMP3;
  52279. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  52280. /* For now we're just allocating the decoder backend on the heap. */
  52281. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  52282. if (pMP3 == NULL) {
  52283. return MA_OUT_OF_MEMORY;
  52284. }
  52285. result = ma_mp3_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pMP3);
  52286. if (result != MA_SUCCESS) {
  52287. ma_free(pMP3, pAllocationCallbacks);
  52288. return result;
  52289. }
  52290. *ppBackend = pMP3;
  52291. return MA_SUCCESS;
  52292. }
  52293. static ma_result ma_decoding_backend_init_file__mp3(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  52294. {
  52295. ma_result result;
  52296. ma_mp3* pMP3;
  52297. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  52298. /* For now we're just allocating the decoder backend on the heap. */
  52299. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  52300. if (pMP3 == NULL) {
  52301. return MA_OUT_OF_MEMORY;
  52302. }
  52303. result = ma_mp3_init_file(pFilePath, pConfig, pAllocationCallbacks, pMP3);
  52304. if (result != MA_SUCCESS) {
  52305. ma_free(pMP3, pAllocationCallbacks);
  52306. return result;
  52307. }
  52308. *ppBackend = pMP3;
  52309. return MA_SUCCESS;
  52310. }
  52311. static ma_result ma_decoding_backend_init_file_w__mp3(void* pUserData, const wchar_t* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  52312. {
  52313. ma_result result;
  52314. ma_mp3* pMP3;
  52315. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  52316. /* For now we're just allocating the decoder backend on the heap. */
  52317. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  52318. if (pMP3 == NULL) {
  52319. return MA_OUT_OF_MEMORY;
  52320. }
  52321. result = ma_mp3_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pMP3);
  52322. if (result != MA_SUCCESS) {
  52323. ma_free(pMP3, pAllocationCallbacks);
  52324. return result;
  52325. }
  52326. *ppBackend = pMP3;
  52327. return MA_SUCCESS;
  52328. }
  52329. static ma_result ma_decoding_backend_init_memory__mp3(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  52330. {
  52331. ma_result result;
  52332. ma_mp3* pMP3;
  52333. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  52334. /* For now we're just allocating the decoder backend on the heap. */
  52335. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  52336. if (pMP3 == NULL) {
  52337. return MA_OUT_OF_MEMORY;
  52338. }
  52339. result = ma_mp3_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pMP3);
  52340. if (result != MA_SUCCESS) {
  52341. ma_free(pMP3, pAllocationCallbacks);
  52342. return result;
  52343. }
  52344. *ppBackend = pMP3;
  52345. return MA_SUCCESS;
  52346. }
  52347. static void ma_decoding_backend_uninit__mp3(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  52348. {
  52349. ma_mp3* pMP3 = (ma_mp3*)pBackend;
  52350. (void)pUserData;
  52351. ma_mp3_uninit(pMP3, pAllocationCallbacks);
  52352. ma_free(pMP3, pAllocationCallbacks);
  52353. }
  52354. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_mp3 =
  52355. {
  52356. ma_decoding_backend_init__mp3,
  52357. ma_decoding_backend_init_file__mp3,
  52358. ma_decoding_backend_init_file_w__mp3,
  52359. ma_decoding_backend_init_memory__mp3,
  52360. ma_decoding_backend_uninit__mp3
  52361. };
  52362. static ma_result ma_decoder_init_mp3__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52363. {
  52364. return ma_decoder_init_from_vtable(&g_ma_decoding_backend_vtable_mp3, NULL, pConfig, pDecoder);
  52365. }
  52366. #endif /* dr_mp3_h */
  52367. /* Vorbis */
  52368. #ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H
  52369. #define MA_HAS_VORBIS
  52370. /* The size in bytes of each chunk of data to read from the Vorbis stream. */
  52371. #define MA_VORBIS_DATA_CHUNK_SIZE 4096
  52372. typedef struct
  52373. {
  52374. ma_data_source_base ds;
  52375. ma_read_proc onRead;
  52376. ma_seek_proc onSeek;
  52377. ma_tell_proc onTell;
  52378. void* pReadSeekTellUserData;
  52379. ma_allocation_callbacks allocationCallbacks; /* Store the allocation callbacks within the structure because we may need to dynamically expand a buffer in ma_stbvorbis_read_pcm_frames() when using push mode. */
  52380. ma_format format; /* Only f32 is allowed with stb_vorbis. */
  52381. ma_uint32 channels;
  52382. ma_uint32 sampleRate;
  52383. ma_uint64 cursor;
  52384. #if !defined(MA_NO_VORBIS)
  52385. stb_vorbis* stb;
  52386. ma_bool32 usingPushMode;
  52387. struct
  52388. {
  52389. ma_uint8* pData;
  52390. size_t dataSize;
  52391. size_t dataCapacity;
  52392. size_t audioStartOffsetInBytes;
  52393. ma_uint32 framesConsumed; /* The number of frames consumed in ppPacketData. */
  52394. ma_uint32 framesRemaining; /* The number of frames remaining in ppPacketData. */
  52395. float** ppPacketData;
  52396. } push;
  52397. #endif
  52398. } ma_stbvorbis;
  52399. MA_API ma_result ma_stbvorbis_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis);
  52400. MA_API ma_result ma_stbvorbis_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis);
  52401. MA_API ma_result ma_stbvorbis_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis);
  52402. MA_API void ma_stbvorbis_uninit(ma_stbvorbis* pVorbis, const ma_allocation_callbacks* pAllocationCallbacks);
  52403. MA_API ma_result ma_stbvorbis_read_pcm_frames(ma_stbvorbis* pVorbis, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  52404. MA_API ma_result ma_stbvorbis_seek_to_pcm_frame(ma_stbvorbis* pVorbis, ma_uint64 frameIndex);
  52405. MA_API ma_result ma_stbvorbis_get_data_format(ma_stbvorbis* pVorbis, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  52406. MA_API ma_result ma_stbvorbis_get_cursor_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pCursor);
  52407. MA_API ma_result ma_stbvorbis_get_length_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pLength);
  52408. static ma_result ma_stbvorbis_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  52409. {
  52410. return ma_stbvorbis_read_pcm_frames((ma_stbvorbis*)pDataSource, pFramesOut, frameCount, pFramesRead);
  52411. }
  52412. static ma_result ma_stbvorbis_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  52413. {
  52414. return ma_stbvorbis_seek_to_pcm_frame((ma_stbvorbis*)pDataSource, frameIndex);
  52415. }
  52416. static ma_result ma_stbvorbis_ds_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  52417. {
  52418. return ma_stbvorbis_get_data_format((ma_stbvorbis*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  52419. }
  52420. static ma_result ma_stbvorbis_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  52421. {
  52422. return ma_stbvorbis_get_cursor_in_pcm_frames((ma_stbvorbis*)pDataSource, pCursor);
  52423. }
  52424. static ma_result ma_stbvorbis_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  52425. {
  52426. return ma_stbvorbis_get_length_in_pcm_frames((ma_stbvorbis*)pDataSource, pLength);
  52427. }
  52428. static ma_data_source_vtable g_ma_stbvorbis_ds_vtable =
  52429. {
  52430. ma_stbvorbis_ds_read,
  52431. ma_stbvorbis_ds_seek,
  52432. ma_stbvorbis_ds_get_data_format,
  52433. ma_stbvorbis_ds_get_cursor,
  52434. ma_stbvorbis_ds_get_length,
  52435. NULL, /* onSetLooping */
  52436. 0
  52437. };
  52438. static ma_result ma_stbvorbis_init_internal(const ma_decoding_backend_config* pConfig, ma_stbvorbis* pVorbis)
  52439. {
  52440. ma_result result;
  52441. ma_data_source_config dataSourceConfig;
  52442. (void)pConfig;
  52443. if (pVorbis == NULL) {
  52444. return MA_INVALID_ARGS;
  52445. }
  52446. MA_ZERO_OBJECT(pVorbis);
  52447. pVorbis->format = ma_format_f32; /* Only supporting f32. */
  52448. dataSourceConfig = ma_data_source_config_init();
  52449. dataSourceConfig.vtable = &g_ma_stbvorbis_ds_vtable;
  52450. result = ma_data_source_init(&dataSourceConfig, &pVorbis->ds);
  52451. if (result != MA_SUCCESS) {
  52452. return result; /* Failed to initialize the base data source. */
  52453. }
  52454. return MA_SUCCESS;
  52455. }
  52456. #if !defined(MA_NO_VORBIS)
  52457. static ma_result ma_stbvorbis_post_init(ma_stbvorbis* pVorbis)
  52458. {
  52459. stb_vorbis_info info;
  52460. MA_ASSERT(pVorbis != NULL);
  52461. info = stb_vorbis_get_info(pVorbis->stb);
  52462. pVorbis->channels = info.channels;
  52463. pVorbis->sampleRate = info.sample_rate;
  52464. return MA_SUCCESS;
  52465. }
  52466. static ma_result ma_stbvorbis_init_internal_decoder_push(ma_stbvorbis* pVorbis)
  52467. {
  52468. ma_result result;
  52469. stb_vorbis* stb;
  52470. size_t dataSize = 0;
  52471. size_t dataCapacity = 0;
  52472. ma_uint8* pData = NULL; /* <-- Must be initialized to NULL. */
  52473. for (;;) {
  52474. int vorbisError;
  52475. int consumedDataSize; /* <-- Fill by stb_vorbis_open_pushdata(). */
  52476. size_t bytesRead;
  52477. ma_uint8* pNewData;
  52478. /* Allocate memory for the new chunk. */
  52479. dataCapacity += MA_VORBIS_DATA_CHUNK_SIZE;
  52480. pNewData = (ma_uint8*)ma_realloc(pData, dataCapacity, &pVorbis->allocationCallbacks);
  52481. if (pNewData == NULL) {
  52482. ma_free(pData, &pVorbis->allocationCallbacks);
  52483. return MA_OUT_OF_MEMORY;
  52484. }
  52485. pData = pNewData;
  52486. /* Read in the next chunk. */
  52487. result = pVorbis->onRead(pVorbis->pReadSeekTellUserData, ma_offset_ptr(pData, dataSize), (dataCapacity - dataSize), &bytesRead);
  52488. dataSize += bytesRead;
  52489. if (result != MA_SUCCESS) {
  52490. ma_free(pData, &pVorbis->allocationCallbacks);
  52491. return result;
  52492. }
  52493. /* We have a maximum of 31 bits with stb_vorbis. */
  52494. if (dataSize > INT_MAX) {
  52495. ma_free(pData, &pVorbis->allocationCallbacks);
  52496. return MA_TOO_BIG;
  52497. }
  52498. stb = stb_vorbis_open_pushdata(pData, (int)dataSize, &consumedDataSize, &vorbisError, NULL);
  52499. if (stb != NULL) {
  52500. /*
  52501. Successfully opened the Vorbis decoder. We might have some leftover unprocessed
  52502. data so we'll need to move that down to the front.
  52503. */
  52504. dataSize -= (size_t)consumedDataSize; /* Consume the data. */
  52505. MA_MOVE_MEMORY(pData, ma_offset_ptr(pData, consumedDataSize), dataSize);
  52506. /*
  52507. We need to track the start point so we can seek back to the start of the audio
  52508. data when seeking.
  52509. */
  52510. pVorbis->push.audioStartOffsetInBytes = consumedDataSize;
  52511. break;
  52512. } else {
  52513. /* Failed to open the decoder. */
  52514. if (vorbisError == VORBIS_need_more_data) {
  52515. continue;
  52516. } else {
  52517. ma_free(pData, &pVorbis->allocationCallbacks);
  52518. return MA_ERROR; /* Failed to open the stb_vorbis decoder. */
  52519. }
  52520. }
  52521. }
  52522. MA_ASSERT(stb != NULL);
  52523. pVorbis->stb = stb;
  52524. pVorbis->push.pData = pData;
  52525. pVorbis->push.dataSize = dataSize;
  52526. pVorbis->push.dataCapacity = dataCapacity;
  52527. return MA_SUCCESS;
  52528. }
  52529. #endif
  52530. MA_API ma_result ma_stbvorbis_init(ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis)
  52531. {
  52532. ma_result result;
  52533. result = ma_stbvorbis_init_internal(pConfig, pVorbis);
  52534. if (result != MA_SUCCESS) {
  52535. return result;
  52536. }
  52537. if (onRead == NULL || onSeek == NULL) {
  52538. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  52539. }
  52540. pVorbis->onRead = onRead;
  52541. pVorbis->onSeek = onSeek;
  52542. pVorbis->onTell = onTell;
  52543. pVorbis->pReadSeekTellUserData = pReadSeekTellUserData;
  52544. ma_allocation_callbacks_init_copy(&pVorbis->allocationCallbacks, pAllocationCallbacks);
  52545. #if !defined(MA_NO_VORBIS)
  52546. {
  52547. /*
  52548. stb_vorbis lacks a callback based API for it's pulling API which means we're stuck with the
  52549. pushing API. In order for us to be able to successfully initialize the decoder we need to
  52550. supply it with enough data. We need to keep loading data until we have enough.
  52551. */
  52552. result = ma_stbvorbis_init_internal_decoder_push(pVorbis);
  52553. if (result != MA_SUCCESS) {
  52554. return result;
  52555. }
  52556. pVorbis->usingPushMode = MA_TRUE;
  52557. result = ma_stbvorbis_post_init(pVorbis);
  52558. if (result != MA_SUCCESS) {
  52559. stb_vorbis_close(pVorbis->stb);
  52560. ma_free(pVorbis->push.pData, pAllocationCallbacks);
  52561. return result;
  52562. }
  52563. return MA_SUCCESS;
  52564. }
  52565. #else
  52566. {
  52567. /* vorbis is disabled. */
  52568. (void)pAllocationCallbacks;
  52569. return MA_NOT_IMPLEMENTED;
  52570. }
  52571. #endif
  52572. }
  52573. MA_API ma_result ma_stbvorbis_init_file(const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis)
  52574. {
  52575. ma_result result;
  52576. result = ma_stbvorbis_init_internal(pConfig, pVorbis);
  52577. if (result != MA_SUCCESS) {
  52578. return result;
  52579. }
  52580. #if !defined(MA_NO_VORBIS)
  52581. {
  52582. (void)pAllocationCallbacks; /* Don't know how to make use of this with stb_vorbis. */
  52583. /* We can use stb_vorbis' pull mode for file based streams. */
  52584. pVorbis->stb = stb_vorbis_open_filename(pFilePath, NULL, NULL);
  52585. if (pVorbis->stb == NULL) {
  52586. return MA_INVALID_FILE;
  52587. }
  52588. pVorbis->usingPushMode = MA_FALSE;
  52589. result = ma_stbvorbis_post_init(pVorbis);
  52590. if (result != MA_SUCCESS) {
  52591. stb_vorbis_close(pVorbis->stb);
  52592. return result;
  52593. }
  52594. return MA_SUCCESS;
  52595. }
  52596. #else
  52597. {
  52598. /* vorbis is disabled. */
  52599. (void)pFilePath;
  52600. (void)pAllocationCallbacks;
  52601. return MA_NOT_IMPLEMENTED;
  52602. }
  52603. #endif
  52604. }
  52605. MA_API ma_result ma_stbvorbis_init_memory(const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_stbvorbis* pVorbis)
  52606. {
  52607. ma_result result;
  52608. result = ma_stbvorbis_init_internal(pConfig, pVorbis);
  52609. if (result != MA_SUCCESS) {
  52610. return result;
  52611. }
  52612. #if !defined(MA_NO_VORBIS)
  52613. {
  52614. (void)pAllocationCallbacks;
  52615. /* stb_vorbis uses an int as it's size specifier, restricting it to 32-bit even on 64-bit systems. *sigh*. */
  52616. if (dataSize > INT_MAX) {
  52617. return MA_TOO_BIG;
  52618. }
  52619. pVorbis->stb = stb_vorbis_open_memory((const unsigned char*)pData, (int)dataSize, NULL, NULL);
  52620. if (pVorbis->stb == NULL) {
  52621. return MA_INVALID_FILE;
  52622. }
  52623. pVorbis->usingPushMode = MA_FALSE;
  52624. result = ma_stbvorbis_post_init(pVorbis);
  52625. if (result != MA_SUCCESS) {
  52626. stb_vorbis_close(pVorbis->stb);
  52627. return result;
  52628. }
  52629. return MA_SUCCESS;
  52630. }
  52631. #else
  52632. {
  52633. /* vorbis is disabled. */
  52634. (void)pData;
  52635. (void)dataSize;
  52636. (void)pAllocationCallbacks;
  52637. return MA_NOT_IMPLEMENTED;
  52638. }
  52639. #endif
  52640. }
  52641. MA_API void ma_stbvorbis_uninit(ma_stbvorbis* pVorbis, const ma_allocation_callbacks* pAllocationCallbacks)
  52642. {
  52643. if (pVorbis == NULL) {
  52644. return;
  52645. }
  52646. #if !defined(MA_NO_VORBIS)
  52647. {
  52648. stb_vorbis_close(pVorbis->stb);
  52649. /* We'll have to clear some memory if we're using push mode. */
  52650. if (pVorbis->usingPushMode) {
  52651. ma_free(pVorbis->push.pData, pAllocationCallbacks);
  52652. }
  52653. }
  52654. #else
  52655. {
  52656. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52657. MA_ASSERT(MA_FALSE);
  52658. }
  52659. #endif
  52660. ma_data_source_uninit(&pVorbis->ds);
  52661. }
  52662. MA_API ma_result ma_stbvorbis_read_pcm_frames(ma_stbvorbis* pVorbis, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  52663. {
  52664. if (pFramesRead != NULL) {
  52665. *pFramesRead = 0;
  52666. }
  52667. if (frameCount == 0) {
  52668. return MA_INVALID_ARGS;
  52669. }
  52670. if (pVorbis == NULL) {
  52671. return MA_INVALID_ARGS;
  52672. }
  52673. #if !defined(MA_NO_VORBIS)
  52674. {
  52675. /* We always use floating point format. */
  52676. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  52677. ma_uint64 totalFramesRead = 0;
  52678. ma_format format;
  52679. ma_uint32 channels;
  52680. ma_stbvorbis_get_data_format(pVorbis, &format, &channels, NULL, NULL, 0);
  52681. if (format == ma_format_f32) {
  52682. /* We read differently depending on whether or not we're using push mode. */
  52683. if (pVorbis->usingPushMode) {
  52684. /* Push mode. This is the complex case. */
  52685. float* pFramesOutF32 = (float*)pFramesOut;
  52686. while (totalFramesRead < frameCount) {
  52687. /* The first thing to do is read from any already-cached frames. */
  52688. ma_uint32 framesToReadFromCache = (ma_uint32)ma_min(pVorbis->push.framesRemaining, (frameCount - totalFramesRead)); /* Safe cast because pVorbis->framesRemaining is 32-bit. */
  52689. /* The output pointer can be null in which case we just treate it as a seek. */
  52690. if (pFramesOut != NULL) {
  52691. ma_uint64 iFrame;
  52692. for (iFrame = 0; iFrame < framesToReadFromCache; iFrame += 1) {
  52693. ma_uint32 iChannel;
  52694. for (iChannel = 0; iChannel < pVorbis->channels; iChannel += 1) {
  52695. pFramesOutF32[iChannel] = pVorbis->push.ppPacketData[iChannel][pVorbis->push.framesConsumed + iFrame];
  52696. }
  52697. pFramesOutF32 += pVorbis->channels;
  52698. }
  52699. }
  52700. /* Update pointers and counters. */
  52701. pVorbis->push.framesConsumed += framesToReadFromCache;
  52702. pVorbis->push.framesRemaining -= framesToReadFromCache;
  52703. totalFramesRead += framesToReadFromCache;
  52704. /* Don't bother reading any more frames right now if we've just finished loading. */
  52705. if (totalFramesRead == frameCount) {
  52706. break;
  52707. }
  52708. MA_ASSERT(pVorbis->push.framesRemaining == 0);
  52709. /* Getting here means we've run out of cached frames. We'll need to load some more. */
  52710. for (;;) {
  52711. int samplesRead = 0;
  52712. int consumedDataSize;
  52713. /* We need to case dataSize to an int, so make sure we can do it safely. */
  52714. if (pVorbis->push.dataSize > INT_MAX) {
  52715. break; /* Too big. */
  52716. }
  52717. consumedDataSize = stb_vorbis_decode_frame_pushdata(pVorbis->stb, pVorbis->push.pData, (int)pVorbis->push.dataSize, NULL, &pVorbis->push.ppPacketData, &samplesRead);
  52718. if (consumedDataSize != 0) {
  52719. /* Successfully decoded a Vorbis frame. Consume the data. */
  52720. pVorbis->push.dataSize -= (size_t)consumedDataSize;
  52721. MA_MOVE_MEMORY(pVorbis->push.pData, ma_offset_ptr(pVorbis->push.pData, consumedDataSize), pVorbis->push.dataSize);
  52722. pVorbis->push.framesConsumed = 0;
  52723. pVorbis->push.framesRemaining = samplesRead;
  52724. break;
  52725. } else {
  52726. /* Not enough data. Read more. */
  52727. size_t bytesRead;
  52728. /* Expand the data buffer if necessary. */
  52729. if (pVorbis->push.dataCapacity == pVorbis->push.dataSize) {
  52730. size_t newCap = pVorbis->push.dataCapacity + MA_VORBIS_DATA_CHUNK_SIZE;
  52731. ma_uint8* pNewData;
  52732. pNewData = (ma_uint8*)ma_realloc(pVorbis->push.pData, newCap, &pVorbis->allocationCallbacks);
  52733. if (pNewData == NULL) {
  52734. result = MA_OUT_OF_MEMORY;
  52735. break;
  52736. }
  52737. pVorbis->push.pData = pNewData;
  52738. pVorbis->push.dataCapacity = newCap;
  52739. }
  52740. /* We should have enough room to load some data. */
  52741. result = pVorbis->onRead(pVorbis->pReadSeekTellUserData, ma_offset_ptr(pVorbis->push.pData, pVorbis->push.dataSize), (pVorbis->push.dataCapacity - pVorbis->push.dataSize), &bytesRead);
  52742. pVorbis->push.dataSize += bytesRead;
  52743. if (result != MA_SUCCESS) {
  52744. break; /* Failed to read any data. Get out. */
  52745. }
  52746. }
  52747. }
  52748. /* If we don't have a success code at this point it means we've encounted an error or the end of the file has been reached (probably the latter). */
  52749. if (result != MA_SUCCESS) {
  52750. break;
  52751. }
  52752. }
  52753. } else {
  52754. /* Pull mode. This is the simple case, but we still need to run in a loop because stb_vorbis loves using 32-bit instead of 64-bit. */
  52755. while (totalFramesRead < frameCount) {
  52756. ma_uint64 framesRemaining = (frameCount - totalFramesRead);
  52757. int framesRead;
  52758. if (framesRemaining > INT_MAX) {
  52759. framesRemaining = INT_MAX;
  52760. }
  52761. framesRead = stb_vorbis_get_samples_float_interleaved(pVorbis->stb, channels, (float*)ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, format, channels), (int)framesRemaining * channels); /* Safe cast. */
  52762. totalFramesRead += framesRead;
  52763. if (framesRead < (int)framesRemaining) {
  52764. break; /* Nothing left to read. Get out. */
  52765. }
  52766. }
  52767. }
  52768. } else {
  52769. result = MA_INVALID_ARGS;
  52770. }
  52771. pVorbis->cursor += totalFramesRead;
  52772. if (totalFramesRead == 0) {
  52773. result = MA_AT_END;
  52774. }
  52775. if (pFramesRead != NULL) {
  52776. *pFramesRead = totalFramesRead;
  52777. }
  52778. if (result == MA_SUCCESS && totalFramesRead == 0) {
  52779. result = MA_AT_END;
  52780. }
  52781. return result;
  52782. }
  52783. #else
  52784. {
  52785. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52786. MA_ASSERT(MA_FALSE);
  52787. (void)pFramesOut;
  52788. (void)frameCount;
  52789. (void)pFramesRead;
  52790. return MA_NOT_IMPLEMENTED;
  52791. }
  52792. #endif
  52793. }
  52794. MA_API ma_result ma_stbvorbis_seek_to_pcm_frame(ma_stbvorbis* pVorbis, ma_uint64 frameIndex)
  52795. {
  52796. if (pVorbis == NULL) {
  52797. return MA_INVALID_ARGS;
  52798. }
  52799. #if !defined(MA_NO_VORBIS)
  52800. {
  52801. /* Different seeking methods depending on whether or not we're using push mode. */
  52802. if (pVorbis->usingPushMode) {
  52803. /* Push mode. This is the complex case. */
  52804. ma_result result;
  52805. float buffer[4096];
  52806. /* If we're seeking backwards, we need to seek back to the start and then brute-force forward. */
  52807. if (frameIndex < pVorbis->cursor) {
  52808. if (frameIndex > 0x7FFFFFFF) {
  52809. return MA_INVALID_ARGS; /* Trying to seek beyond the 32-bit maximum of stb_vorbis. */
  52810. }
  52811. /*
  52812. This is wildly inefficient due to me having trouble getting sample exact seeking working
  52813. robustly with stb_vorbis_flush_pushdata(). The only way I can think to make this work
  52814. perfectly is to reinitialize the decoder. Note that we only enter this path when seeking
  52815. backwards. This will hopefully be removed once we get our own Vorbis decoder implemented.
  52816. */
  52817. stb_vorbis_close(pVorbis->stb);
  52818. ma_free(pVorbis->push.pData, &pVorbis->allocationCallbacks);
  52819. MA_ZERO_OBJECT(&pVorbis->push);
  52820. /* Seek to the start of the file. */
  52821. result = pVorbis->onSeek(pVorbis->pReadSeekTellUserData, 0, ma_seek_origin_start);
  52822. if (result != MA_SUCCESS) {
  52823. return result;
  52824. }
  52825. result = ma_stbvorbis_init_internal_decoder_push(pVorbis);
  52826. if (result != MA_SUCCESS) {
  52827. return result;
  52828. }
  52829. /* At this point we should be sitting on the first frame. */
  52830. pVorbis->cursor = 0;
  52831. }
  52832. /* We're just brute-forcing this for now. */
  52833. while (pVorbis->cursor < frameIndex) {
  52834. ma_uint64 framesRead;
  52835. ma_uint64 framesToRead = ma_countof(buffer)/pVorbis->channels;
  52836. if (framesToRead > (frameIndex - pVorbis->cursor)) {
  52837. framesToRead = (frameIndex - pVorbis->cursor);
  52838. }
  52839. result = ma_stbvorbis_read_pcm_frames(pVorbis, buffer, framesToRead, &framesRead);
  52840. pVorbis->cursor += framesRead;
  52841. if (result != MA_SUCCESS) {
  52842. return result;
  52843. }
  52844. }
  52845. } else {
  52846. /* Pull mode. This is the simple case. */
  52847. int vorbisResult;
  52848. if (frameIndex > UINT_MAX) {
  52849. return MA_INVALID_ARGS; /* Trying to seek beyond the 32-bit maximum of stb_vorbis. */
  52850. }
  52851. vorbisResult = stb_vorbis_seek(pVorbis->stb, (unsigned int)frameIndex); /* Safe cast. */
  52852. if (vorbisResult == 0) {
  52853. return MA_ERROR; /* See failed. */
  52854. }
  52855. pVorbis->cursor = frameIndex;
  52856. }
  52857. return MA_SUCCESS;
  52858. }
  52859. #else
  52860. {
  52861. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52862. MA_ASSERT(MA_FALSE);
  52863. (void)frameIndex;
  52864. return MA_NOT_IMPLEMENTED;
  52865. }
  52866. #endif
  52867. }
  52868. MA_API ma_result ma_stbvorbis_get_data_format(ma_stbvorbis* pVorbis, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  52869. {
  52870. /* Defaults for safety. */
  52871. if (pFormat != NULL) {
  52872. *pFormat = ma_format_unknown;
  52873. }
  52874. if (pChannels != NULL) {
  52875. *pChannels = 0;
  52876. }
  52877. if (pSampleRate != NULL) {
  52878. *pSampleRate = 0;
  52879. }
  52880. if (pChannelMap != NULL) {
  52881. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  52882. }
  52883. if (pVorbis == NULL) {
  52884. return MA_INVALID_OPERATION;
  52885. }
  52886. if (pFormat != NULL) {
  52887. *pFormat = pVorbis->format;
  52888. }
  52889. #if !defined(MA_NO_VORBIS)
  52890. {
  52891. if (pChannels != NULL) {
  52892. *pChannels = pVorbis->channels;
  52893. }
  52894. if (pSampleRate != NULL) {
  52895. *pSampleRate = pVorbis->sampleRate;
  52896. }
  52897. if (pChannelMap != NULL) {
  52898. ma_channel_map_init_standard(ma_standard_channel_map_vorbis, pChannelMap, channelMapCap, pVorbis->channels);
  52899. }
  52900. return MA_SUCCESS;
  52901. }
  52902. #else
  52903. {
  52904. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52905. MA_ASSERT(MA_FALSE);
  52906. return MA_NOT_IMPLEMENTED;
  52907. }
  52908. #endif
  52909. }
  52910. MA_API ma_result ma_stbvorbis_get_cursor_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pCursor)
  52911. {
  52912. if (pCursor == NULL) {
  52913. return MA_INVALID_ARGS;
  52914. }
  52915. *pCursor = 0; /* Safety. */
  52916. if (pVorbis == NULL) {
  52917. return MA_INVALID_ARGS;
  52918. }
  52919. #if !defined(MA_NO_VORBIS)
  52920. {
  52921. *pCursor = pVorbis->cursor;
  52922. return MA_SUCCESS;
  52923. }
  52924. #else
  52925. {
  52926. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52927. MA_ASSERT(MA_FALSE);
  52928. return MA_NOT_IMPLEMENTED;
  52929. }
  52930. #endif
  52931. }
  52932. MA_API ma_result ma_stbvorbis_get_length_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pLength)
  52933. {
  52934. if (pLength == NULL) {
  52935. return MA_INVALID_ARGS;
  52936. }
  52937. *pLength = 0; /* Safety. */
  52938. if (pVorbis == NULL) {
  52939. return MA_INVALID_ARGS;
  52940. }
  52941. #if !defined(MA_NO_VORBIS)
  52942. {
  52943. if (pVorbis->usingPushMode) {
  52944. *pLength = 0; /* I don't know of a good way to determine this reliably with stb_vorbis and push mode. */
  52945. } else {
  52946. *pLength = stb_vorbis_stream_length_in_samples(pVorbis->stb);
  52947. }
  52948. return MA_SUCCESS;
  52949. }
  52950. #else
  52951. {
  52952. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52953. MA_ASSERT(MA_FALSE);
  52954. return MA_NOT_IMPLEMENTED;
  52955. }
  52956. #endif
  52957. }
  52958. static ma_result ma_decoding_backend_init__stbvorbis(void* pUserData, ma_read_proc onRead, ma_seek_proc onSeek, ma_tell_proc onTell, void* pReadSeekTellUserData, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  52959. {
  52960. ma_result result;
  52961. ma_stbvorbis* pVorbis;
  52962. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  52963. /* For now we're just allocating the decoder backend on the heap. */
  52964. pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks);
  52965. if (pVorbis == NULL) {
  52966. return MA_OUT_OF_MEMORY;
  52967. }
  52968. result = ma_stbvorbis_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pVorbis);
  52969. if (result != MA_SUCCESS) {
  52970. ma_free(pVorbis, pAllocationCallbacks);
  52971. return result;
  52972. }
  52973. *ppBackend = pVorbis;
  52974. return MA_SUCCESS;
  52975. }
  52976. static ma_result ma_decoding_backend_init_file__stbvorbis(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  52977. {
  52978. ma_result result;
  52979. ma_stbvorbis* pVorbis;
  52980. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  52981. /* For now we're just allocating the decoder backend on the heap. */
  52982. pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks);
  52983. if (pVorbis == NULL) {
  52984. return MA_OUT_OF_MEMORY;
  52985. }
  52986. result = ma_stbvorbis_init_file(pFilePath, pConfig, pAllocationCallbacks, pVorbis);
  52987. if (result != MA_SUCCESS) {
  52988. ma_free(pVorbis, pAllocationCallbacks);
  52989. return result;
  52990. }
  52991. *ppBackend = pVorbis;
  52992. return MA_SUCCESS;
  52993. }
  52994. static ma_result ma_decoding_backend_init_memory__stbvorbis(void* pUserData, const void* pData, size_t dataSize, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend)
  52995. {
  52996. ma_result result;
  52997. ma_stbvorbis* pVorbis;
  52998. (void)pUserData; /* For now not using pUserData, but once we start storing the vorbis decoder state within the ma_decoder structure this will be set to the decoder so we can avoid a malloc. */
  52999. /* For now we're just allocating the decoder backend on the heap. */
  53000. pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks);
  53001. if (pVorbis == NULL) {
  53002. return MA_OUT_OF_MEMORY;
  53003. }
  53004. result = ma_stbvorbis_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pVorbis);
  53005. if (result != MA_SUCCESS) {
  53006. ma_free(pVorbis, pAllocationCallbacks);
  53007. return result;
  53008. }
  53009. *ppBackend = pVorbis;
  53010. return MA_SUCCESS;
  53011. }
  53012. static void ma_decoding_backend_uninit__stbvorbis(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  53013. {
  53014. ma_stbvorbis* pVorbis = (ma_stbvorbis*)pBackend;
  53015. (void)pUserData;
  53016. ma_stbvorbis_uninit(pVorbis, pAllocationCallbacks);
  53017. ma_free(pVorbis, pAllocationCallbacks);
  53018. }
  53019. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_stbvorbis =
  53020. {
  53021. ma_decoding_backend_init__stbvorbis,
  53022. ma_decoding_backend_init_file__stbvorbis,
  53023. NULL, /* onInitFileW() */
  53024. ma_decoding_backend_init_memory__stbvorbis,
  53025. ma_decoding_backend_uninit__stbvorbis
  53026. };
  53027. static ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53028. {
  53029. return ma_decoder_init_from_vtable(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pConfig, pDecoder);
  53030. }
  53031. #endif /* STB_VORBIS_INCLUDE_STB_VORBIS_H */
  53032. static ma_result ma_decoder__init_allocation_callbacks(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53033. {
  53034. MA_ASSERT(pDecoder != NULL);
  53035. if (pConfig != NULL) {
  53036. return ma_allocation_callbacks_init_copy(&pDecoder->allocationCallbacks, &pConfig->allocationCallbacks);
  53037. } else {
  53038. pDecoder->allocationCallbacks = ma_allocation_callbacks_init_default();
  53039. return MA_SUCCESS;
  53040. }
  53041. }
  53042. static ma_result ma_decoder__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  53043. {
  53044. return ma_decoder_read_pcm_frames((ma_decoder*)pDataSource, pFramesOut, frameCount, pFramesRead);
  53045. }
  53046. static ma_result ma_decoder__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  53047. {
  53048. return ma_decoder_seek_to_pcm_frame((ma_decoder*)pDataSource, frameIndex);
  53049. }
  53050. static ma_result ma_decoder__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  53051. {
  53052. return ma_decoder_get_data_format((ma_decoder*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  53053. }
  53054. static ma_result ma_decoder__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  53055. {
  53056. return ma_decoder_get_cursor_in_pcm_frames((ma_decoder*)pDataSource, pCursor);
  53057. }
  53058. static ma_result ma_decoder__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  53059. {
  53060. return ma_decoder_get_length_in_pcm_frames((ma_decoder*)pDataSource, pLength);
  53061. }
  53062. static ma_data_source_vtable g_ma_decoder_data_source_vtable =
  53063. {
  53064. ma_decoder__data_source_on_read,
  53065. ma_decoder__data_source_on_seek,
  53066. ma_decoder__data_source_on_get_data_format,
  53067. ma_decoder__data_source_on_get_cursor,
  53068. ma_decoder__data_source_on_get_length,
  53069. NULL, /* onSetLooping */
  53070. 0
  53071. };
  53072. static ma_result ma_decoder__preinit(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, ma_decoder_tell_proc onTell, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53073. {
  53074. ma_result result;
  53075. ma_data_source_config dataSourceConfig;
  53076. MA_ASSERT(pConfig != NULL);
  53077. if (pDecoder == NULL) {
  53078. return MA_INVALID_ARGS;
  53079. }
  53080. MA_ZERO_OBJECT(pDecoder);
  53081. if (onRead == NULL || onSeek == NULL) {
  53082. return MA_INVALID_ARGS;
  53083. }
  53084. dataSourceConfig = ma_data_source_config_init();
  53085. dataSourceConfig.vtable = &g_ma_decoder_data_source_vtable;
  53086. result = ma_data_source_init(&dataSourceConfig, &pDecoder->ds);
  53087. if (result != MA_SUCCESS) {
  53088. return result;
  53089. }
  53090. pDecoder->onRead = onRead;
  53091. pDecoder->onSeek = onSeek;
  53092. pDecoder->onTell = onTell;
  53093. pDecoder->pUserData = pUserData;
  53094. result = ma_decoder__init_allocation_callbacks(pConfig, pDecoder);
  53095. if (result != MA_SUCCESS) {
  53096. ma_data_source_uninit(&pDecoder->ds);
  53097. return result;
  53098. }
  53099. return MA_SUCCESS;
  53100. }
  53101. static ma_result ma_decoder__postinit(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53102. {
  53103. ma_result result;
  53104. result = ma_decoder__init_data_converter(pDecoder, pConfig);
  53105. /* If we failed post initialization we need to uninitialize the decoder before returning to prevent a memory leak. */
  53106. if (result != MA_SUCCESS) {
  53107. ma_decoder_uninit(pDecoder);
  53108. return result;
  53109. }
  53110. return result;
  53111. }
  53112. static ma_result ma_decoder_init__internal(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53113. {
  53114. ma_result result = MA_NO_BACKEND;
  53115. MA_ASSERT(pConfig != NULL);
  53116. MA_ASSERT(pDecoder != NULL);
  53117. /* Silence some warnings in the case that we don't have any decoder backends enabled. */
  53118. (void)onRead;
  53119. (void)onSeek;
  53120. (void)pUserData;
  53121. /* If we've specified a specific encoding type, try that first. */
  53122. if (pConfig->encodingFormat != ma_encoding_format_unknown) {
  53123. #ifdef MA_HAS_WAV
  53124. if (pConfig->encodingFormat == ma_encoding_format_wav) {
  53125. result = ma_decoder_init_wav__internal(pConfig, pDecoder);
  53126. }
  53127. #endif
  53128. #ifdef MA_HAS_FLAC
  53129. if (pConfig->encodingFormat == ma_encoding_format_flac) {
  53130. result = ma_decoder_init_flac__internal(pConfig, pDecoder);
  53131. }
  53132. #endif
  53133. #ifdef MA_HAS_MP3
  53134. if (pConfig->encodingFormat == ma_encoding_format_mp3) {
  53135. result = ma_decoder_init_mp3__internal(pConfig, pDecoder);
  53136. }
  53137. #endif
  53138. #ifdef MA_HAS_VORBIS
  53139. if (pConfig->encodingFormat == ma_encoding_format_vorbis) {
  53140. result = ma_decoder_init_vorbis__internal(pConfig, pDecoder);
  53141. }
  53142. #endif
  53143. /* If we weren't able to initialize the decoder, seek back to the start to give the next attempts a clean start. */
  53144. if (result != MA_SUCCESS) {
  53145. onSeek(pDecoder, 0, ma_seek_origin_start);
  53146. }
  53147. }
  53148. if (result != MA_SUCCESS) {
  53149. /* Getting here means we couldn't load a specific decoding backend based on the encoding format. */
  53150. /*
  53151. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  53152. implement the same encoding format they take priority over the built-in decoders.
  53153. */
  53154. if (result != MA_SUCCESS) {
  53155. result = ma_decoder_init_custom__internal(pConfig, pDecoder);
  53156. if (result != MA_SUCCESS) {
  53157. onSeek(pDecoder, 0, ma_seek_origin_start);
  53158. }
  53159. }
  53160. /*
  53161. If we get to this point and we still haven't found a decoder, and the caller has requested a
  53162. specific encoding format, there's no hope for it. Abort.
  53163. */
  53164. if (pConfig->encodingFormat != ma_encoding_format_unknown) {
  53165. return MA_NO_BACKEND;
  53166. }
  53167. #ifdef MA_HAS_WAV
  53168. if (result != MA_SUCCESS) {
  53169. result = ma_decoder_init_wav__internal(pConfig, pDecoder);
  53170. if (result != MA_SUCCESS) {
  53171. onSeek(pDecoder, 0, ma_seek_origin_start);
  53172. }
  53173. }
  53174. #endif
  53175. #ifdef MA_HAS_FLAC
  53176. if (result != MA_SUCCESS) {
  53177. result = ma_decoder_init_flac__internal(pConfig, pDecoder);
  53178. if (result != MA_SUCCESS) {
  53179. onSeek(pDecoder, 0, ma_seek_origin_start);
  53180. }
  53181. }
  53182. #endif
  53183. #ifdef MA_HAS_MP3
  53184. if (result != MA_SUCCESS) {
  53185. result = ma_decoder_init_mp3__internal(pConfig, pDecoder);
  53186. if (result != MA_SUCCESS) {
  53187. onSeek(pDecoder, 0, ma_seek_origin_start);
  53188. }
  53189. }
  53190. #endif
  53191. #ifdef MA_HAS_VORBIS
  53192. if (result != MA_SUCCESS) {
  53193. result = ma_decoder_init_vorbis__internal(pConfig, pDecoder);
  53194. if (result != MA_SUCCESS) {
  53195. onSeek(pDecoder, 0, ma_seek_origin_start);
  53196. }
  53197. }
  53198. #endif
  53199. }
  53200. if (result != MA_SUCCESS) {
  53201. return result;
  53202. }
  53203. return ma_decoder__postinit(pConfig, pDecoder);
  53204. }
  53205. MA_API ma_result ma_decoder_init(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53206. {
  53207. ma_decoder_config config;
  53208. ma_result result;
  53209. config = ma_decoder_config_init_copy(pConfig);
  53210. result = ma_decoder__preinit(onRead, onSeek, NULL, pUserData, &config, pDecoder);
  53211. if (result != MA_SUCCESS) {
  53212. return result;
  53213. }
  53214. return ma_decoder_init__internal(onRead, onSeek, pUserData, &config, pDecoder);
  53215. }
  53216. static ma_result ma_decoder__on_read_memory(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  53217. {
  53218. size_t bytesRemaining;
  53219. MA_ASSERT(pDecoder->data.memory.dataSize >= pDecoder->data.memory.currentReadPos);
  53220. if (pBytesRead != NULL) {
  53221. *pBytesRead = 0;
  53222. }
  53223. bytesRemaining = pDecoder->data.memory.dataSize - pDecoder->data.memory.currentReadPos;
  53224. if (bytesToRead > bytesRemaining) {
  53225. bytesToRead = bytesRemaining;
  53226. }
  53227. if (bytesRemaining == 0) {
  53228. return MA_AT_END;
  53229. }
  53230. if (bytesToRead > 0) {
  53231. MA_COPY_MEMORY(pBufferOut, pDecoder->data.memory.pData + pDecoder->data.memory.currentReadPos, bytesToRead);
  53232. pDecoder->data.memory.currentReadPos += bytesToRead;
  53233. }
  53234. if (pBytesRead != NULL) {
  53235. *pBytesRead = bytesToRead;
  53236. }
  53237. return MA_SUCCESS;
  53238. }
  53239. static ma_result ma_decoder__on_seek_memory(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin)
  53240. {
  53241. if (byteOffset > 0 && (ma_uint64)byteOffset > MA_SIZE_MAX) {
  53242. return MA_BAD_SEEK;
  53243. }
  53244. if (origin == ma_seek_origin_current) {
  53245. if (byteOffset > 0) {
  53246. if (pDecoder->data.memory.currentReadPos + byteOffset > pDecoder->data.memory.dataSize) {
  53247. byteOffset = (ma_int64)(pDecoder->data.memory.dataSize - pDecoder->data.memory.currentReadPos); /* Trying to seek too far forward. */
  53248. }
  53249. pDecoder->data.memory.currentReadPos += (size_t)byteOffset;
  53250. } else {
  53251. if (pDecoder->data.memory.currentReadPos < (size_t)-byteOffset) {
  53252. byteOffset = -(ma_int64)pDecoder->data.memory.currentReadPos; /* Trying to seek too far backwards. */
  53253. }
  53254. pDecoder->data.memory.currentReadPos -= (size_t)-byteOffset;
  53255. }
  53256. } else {
  53257. if (origin == ma_seek_origin_end) {
  53258. if (byteOffset < 0) {
  53259. byteOffset = -byteOffset;
  53260. }
  53261. if (byteOffset > (ma_int64)pDecoder->data.memory.dataSize) {
  53262. pDecoder->data.memory.currentReadPos = 0; /* Trying to seek too far back. */
  53263. } else {
  53264. pDecoder->data.memory.currentReadPos = pDecoder->data.memory.dataSize - (size_t)byteOffset;
  53265. }
  53266. } else {
  53267. if ((size_t)byteOffset <= pDecoder->data.memory.dataSize) {
  53268. pDecoder->data.memory.currentReadPos = (size_t)byteOffset;
  53269. } else {
  53270. pDecoder->data.memory.currentReadPos = pDecoder->data.memory.dataSize; /* Trying to seek too far forward. */
  53271. }
  53272. }
  53273. }
  53274. return MA_SUCCESS;
  53275. }
  53276. static ma_result ma_decoder__on_tell_memory(ma_decoder* pDecoder, ma_int64* pCursor)
  53277. {
  53278. MA_ASSERT(pDecoder != NULL);
  53279. MA_ASSERT(pCursor != NULL);
  53280. *pCursor = (ma_int64)pDecoder->data.memory.currentReadPos;
  53281. return MA_SUCCESS;
  53282. }
  53283. static ma_result ma_decoder__preinit_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53284. {
  53285. ma_result result = ma_decoder__preinit(ma_decoder__on_read_memory, ma_decoder__on_seek_memory, ma_decoder__on_tell_memory, NULL, pConfig, pDecoder);
  53286. if (result != MA_SUCCESS) {
  53287. return result;
  53288. }
  53289. if (pData == NULL || dataSize == 0) {
  53290. return MA_INVALID_ARGS;
  53291. }
  53292. pDecoder->data.memory.pData = (const ma_uint8*)pData;
  53293. pDecoder->data.memory.dataSize = dataSize;
  53294. pDecoder->data.memory.currentReadPos = 0;
  53295. (void)pConfig;
  53296. return MA_SUCCESS;
  53297. }
  53298. MA_API ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53299. {
  53300. ma_decoder_config config;
  53301. ma_result result;
  53302. config = ma_decoder_config_init_copy(pConfig); /* Make sure the config is not NULL. */
  53303. result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder);
  53304. if (result != MA_SUCCESS) {
  53305. return result;
  53306. }
  53307. return ma_decoder_init__internal(ma_decoder__on_read_memory, ma_decoder__on_seek_memory, NULL, &config, pDecoder);
  53308. }
  53309. #if defined(MA_HAS_WAV) || \
  53310. defined(MA_HAS_MP3) || \
  53311. defined(MA_HAS_FLAC) || \
  53312. defined(MA_HAS_VORBIS) || \
  53313. defined(MA_HAS_OPUS)
  53314. #define MA_HAS_PATH_API
  53315. #endif
  53316. #if defined(MA_HAS_PATH_API)
  53317. static const char* ma_path_file_name(const char* path)
  53318. {
  53319. const char* fileName;
  53320. if (path == NULL) {
  53321. return NULL;
  53322. }
  53323. fileName = path;
  53324. /* We just loop through the path until we find the last slash. */
  53325. while (path[0] != '\0') {
  53326. if (path[0] == '/' || path[0] == '\\') {
  53327. fileName = path;
  53328. }
  53329. path += 1;
  53330. }
  53331. /* At this point the file name is sitting on a slash, so just move forward. */
  53332. while (fileName[0] != '\0' && (fileName[0] == '/' || fileName[0] == '\\')) {
  53333. fileName += 1;
  53334. }
  53335. return fileName;
  53336. }
  53337. static const wchar_t* ma_path_file_name_w(const wchar_t* path)
  53338. {
  53339. const wchar_t* fileName;
  53340. if (path == NULL) {
  53341. return NULL;
  53342. }
  53343. fileName = path;
  53344. /* We just loop through the path until we find the last slash. */
  53345. while (path[0] != '\0') {
  53346. if (path[0] == '/' || path[0] == '\\') {
  53347. fileName = path;
  53348. }
  53349. path += 1;
  53350. }
  53351. /* At this point the file name is sitting on a slash, so just move forward. */
  53352. while (fileName[0] != '\0' && (fileName[0] == '/' || fileName[0] == '\\')) {
  53353. fileName += 1;
  53354. }
  53355. return fileName;
  53356. }
  53357. static const char* ma_path_extension(const char* path)
  53358. {
  53359. const char* extension;
  53360. const char* lastOccurance;
  53361. if (path == NULL) {
  53362. path = "";
  53363. }
  53364. extension = ma_path_file_name(path);
  53365. lastOccurance = NULL;
  53366. /* Just find the last '.' and return. */
  53367. while (extension[0] != '\0') {
  53368. if (extension[0] == '.') {
  53369. extension += 1;
  53370. lastOccurance = extension;
  53371. }
  53372. extension += 1;
  53373. }
  53374. return (lastOccurance != NULL) ? lastOccurance : extension;
  53375. }
  53376. static const wchar_t* ma_path_extension_w(const wchar_t* path)
  53377. {
  53378. const wchar_t* extension;
  53379. const wchar_t* lastOccurance;
  53380. if (path == NULL) {
  53381. path = L"";
  53382. }
  53383. extension = ma_path_file_name_w(path);
  53384. lastOccurance = NULL;
  53385. /* Just find the last '.' and return. */
  53386. while (extension[0] != '\0') {
  53387. if (extension[0] == '.') {
  53388. extension += 1;
  53389. lastOccurance = extension;
  53390. }
  53391. extension += 1;
  53392. }
  53393. return (lastOccurance != NULL) ? lastOccurance : extension;
  53394. }
  53395. static ma_bool32 ma_path_extension_equal(const char* path, const char* extension)
  53396. {
  53397. const char* ext1;
  53398. const char* ext2;
  53399. if (path == NULL || extension == NULL) {
  53400. return MA_FALSE;
  53401. }
  53402. ext1 = extension;
  53403. ext2 = ma_path_extension(path);
  53404. #if defined(_MSC_VER) || defined(__DMC__)
  53405. return _stricmp(ext1, ext2) == 0;
  53406. #else
  53407. return strcasecmp(ext1, ext2) == 0;
  53408. #endif
  53409. }
  53410. static ma_bool32 ma_path_extension_equal_w(const wchar_t* path, const wchar_t* extension)
  53411. {
  53412. const wchar_t* ext1;
  53413. const wchar_t* ext2;
  53414. if (path == NULL || extension == NULL) {
  53415. return MA_FALSE;
  53416. }
  53417. ext1 = extension;
  53418. ext2 = ma_path_extension_w(path);
  53419. #if defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DMC__)
  53420. return _wcsicmp(ext1, ext2) == 0;
  53421. #else
  53422. /*
  53423. I'm not aware of a wide character version of strcasecmp(). I'm therefore converting the extensions to multibyte strings and comparing those. This
  53424. isn't the most efficient way to do it, but it should work OK.
  53425. */
  53426. {
  53427. char ext1MB[4096];
  53428. char ext2MB[4096];
  53429. const wchar_t* pext1 = ext1;
  53430. const wchar_t* pext2 = ext2;
  53431. mbstate_t mbs1;
  53432. mbstate_t mbs2;
  53433. MA_ZERO_OBJECT(&mbs1);
  53434. MA_ZERO_OBJECT(&mbs2);
  53435. if (wcsrtombs(ext1MB, &pext1, sizeof(ext1MB), &mbs1) == (size_t)-1) {
  53436. return MA_FALSE;
  53437. }
  53438. if (wcsrtombs(ext2MB, &pext2, sizeof(ext2MB), &mbs2) == (size_t)-1) {
  53439. return MA_FALSE;
  53440. }
  53441. return strcasecmp(ext1MB, ext2MB) == 0;
  53442. }
  53443. #endif
  53444. }
  53445. #endif /* MA_HAS_PATH_API */
  53446. static ma_result ma_decoder__on_read_vfs(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  53447. {
  53448. MA_ASSERT(pDecoder != NULL);
  53449. MA_ASSERT(pBufferOut != NULL);
  53450. return ma_vfs_or_default_read(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, pBufferOut, bytesToRead, pBytesRead);
  53451. }
  53452. static ma_result ma_decoder__on_seek_vfs(ma_decoder* pDecoder, ma_int64 offset, ma_seek_origin origin)
  53453. {
  53454. MA_ASSERT(pDecoder != NULL);
  53455. return ma_vfs_or_default_seek(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, offset, origin);
  53456. }
  53457. static ma_result ma_decoder__on_tell_vfs(ma_decoder* pDecoder, ma_int64* pCursor)
  53458. {
  53459. MA_ASSERT(pDecoder != NULL);
  53460. return ma_vfs_or_default_tell(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, pCursor);
  53461. }
  53462. static ma_result ma_decoder__preinit_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53463. {
  53464. ma_result result;
  53465. ma_vfs_file file;
  53466. result = ma_decoder__preinit(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, ma_decoder__on_tell_vfs, NULL, pConfig, pDecoder);
  53467. if (result != MA_SUCCESS) {
  53468. return result;
  53469. }
  53470. if (pFilePath == NULL || pFilePath[0] == '\0') {
  53471. return MA_INVALID_ARGS;
  53472. }
  53473. result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_READ, &file);
  53474. if (result != MA_SUCCESS) {
  53475. return result;
  53476. }
  53477. pDecoder->data.vfs.pVFS = pVFS;
  53478. pDecoder->data.vfs.file = file;
  53479. return MA_SUCCESS;
  53480. }
  53481. MA_API ma_result ma_decoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53482. {
  53483. ma_result result;
  53484. ma_decoder_config config;
  53485. config = ma_decoder_config_init_copy(pConfig);
  53486. result = ma_decoder__preinit_vfs(pVFS, pFilePath, &config, pDecoder);
  53487. if (result != MA_SUCCESS) {
  53488. return result;
  53489. }
  53490. result = MA_NO_BACKEND;
  53491. if (config.encodingFormat != ma_encoding_format_unknown) {
  53492. #ifdef MA_HAS_WAV
  53493. if (config.encodingFormat == ma_encoding_format_wav) {
  53494. result = ma_decoder_init_wav__internal(&config, pDecoder);
  53495. }
  53496. #endif
  53497. #ifdef MA_HAS_FLAC
  53498. if (config.encodingFormat == ma_encoding_format_flac) {
  53499. result = ma_decoder_init_flac__internal(&config, pDecoder);
  53500. }
  53501. #endif
  53502. #ifdef MA_HAS_MP3
  53503. if (config.encodingFormat == ma_encoding_format_mp3) {
  53504. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  53505. }
  53506. #endif
  53507. #ifdef MA_HAS_VORBIS
  53508. if (config.encodingFormat == ma_encoding_format_vorbis) {
  53509. result = ma_decoder_init_vorbis__internal(&config, pDecoder);
  53510. }
  53511. #endif
  53512. /* Make sure we seek back to the start if we didn't initialize a decoder successfully so the next attempts have a fresh start. */
  53513. if (result != MA_SUCCESS) {
  53514. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53515. }
  53516. }
  53517. if (result != MA_SUCCESS) {
  53518. /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */
  53519. /*
  53520. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  53521. implement the same encoding format they take priority over the built-in decoders.
  53522. */
  53523. if (result != MA_SUCCESS) {
  53524. result = ma_decoder_init_custom__internal(&config, pDecoder);
  53525. if (result != MA_SUCCESS) {
  53526. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53527. }
  53528. }
  53529. /*
  53530. If we get to this point and we still haven't found a decoder, and the caller has requested a
  53531. specific encoding format, there's no hope for it. Abort.
  53532. */
  53533. if (config.encodingFormat != ma_encoding_format_unknown) {
  53534. return MA_NO_BACKEND;
  53535. }
  53536. #ifdef MA_HAS_WAV
  53537. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "wav")) {
  53538. result = ma_decoder_init_wav__internal(&config, pDecoder);
  53539. if (result != MA_SUCCESS) {
  53540. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53541. }
  53542. }
  53543. #endif
  53544. #ifdef MA_HAS_FLAC
  53545. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "flac")) {
  53546. result = ma_decoder_init_flac__internal(&config, pDecoder);
  53547. if (result != MA_SUCCESS) {
  53548. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53549. }
  53550. }
  53551. #endif
  53552. #ifdef MA_HAS_MP3
  53553. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "mp3")) {
  53554. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  53555. if (result != MA_SUCCESS) {
  53556. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53557. }
  53558. }
  53559. #endif
  53560. }
  53561. /* If we still haven't got a result just use trial and error. Otherwise we can finish up. */
  53562. if (result != MA_SUCCESS) {
  53563. result = ma_decoder_init__internal(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, NULL, &config, pDecoder);
  53564. } else {
  53565. result = ma_decoder__postinit(&config, pDecoder);
  53566. }
  53567. if (result != MA_SUCCESS) {
  53568. if (pDecoder->data.vfs.file != NULL) { /* <-- Will be reset to NULL if ma_decoder_uninit() is called in one of the steps above which allows us to avoid a double close of the file. */
  53569. ma_vfs_or_default_close(pVFS, pDecoder->data.vfs.file);
  53570. }
  53571. return result;
  53572. }
  53573. return MA_SUCCESS;
  53574. }
  53575. static ma_result ma_decoder__preinit_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53576. {
  53577. ma_result result;
  53578. ma_vfs_file file;
  53579. result = ma_decoder__preinit(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, ma_decoder__on_tell_vfs, NULL, pConfig, pDecoder);
  53580. if (result != MA_SUCCESS) {
  53581. return result;
  53582. }
  53583. if (pFilePath == NULL || pFilePath[0] == '\0') {
  53584. return MA_INVALID_ARGS;
  53585. }
  53586. result = ma_vfs_or_default_open_w(pVFS, pFilePath, MA_OPEN_MODE_READ, &file);
  53587. if (result != MA_SUCCESS) {
  53588. return result;
  53589. }
  53590. pDecoder->data.vfs.pVFS = pVFS;
  53591. pDecoder->data.vfs.file = file;
  53592. return MA_SUCCESS;
  53593. }
  53594. MA_API ma_result ma_decoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53595. {
  53596. ma_result result;
  53597. ma_decoder_config config;
  53598. config = ma_decoder_config_init_copy(pConfig);
  53599. result = ma_decoder__preinit_vfs_w(pVFS, pFilePath, &config, pDecoder);
  53600. if (result != MA_SUCCESS) {
  53601. return result;
  53602. }
  53603. result = MA_NO_BACKEND;
  53604. if (config.encodingFormat != ma_encoding_format_unknown) {
  53605. #ifdef MA_HAS_WAV
  53606. if (config.encodingFormat == ma_encoding_format_wav) {
  53607. result = ma_decoder_init_wav__internal(&config, pDecoder);
  53608. }
  53609. #endif
  53610. #ifdef MA_HAS_FLAC
  53611. if (config.encodingFormat == ma_encoding_format_flac) {
  53612. result = ma_decoder_init_flac__internal(&config, pDecoder);
  53613. }
  53614. #endif
  53615. #ifdef MA_HAS_MP3
  53616. if (config.encodingFormat == ma_encoding_format_mp3) {
  53617. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  53618. }
  53619. #endif
  53620. #ifdef MA_HAS_VORBIS
  53621. if (config.encodingFormat == ma_encoding_format_vorbis) {
  53622. result = ma_decoder_init_vorbis__internal(&config, pDecoder);
  53623. }
  53624. #endif
  53625. /* Make sure we seek back to the start if we didn't initialize a decoder successfully so the next attempts have a fresh start. */
  53626. if (result != MA_SUCCESS) {
  53627. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53628. }
  53629. }
  53630. if (result != MA_SUCCESS) {
  53631. /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */
  53632. /*
  53633. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  53634. implement the same encoding format they take priority over the built-in decoders.
  53635. */
  53636. if (result != MA_SUCCESS) {
  53637. result = ma_decoder_init_custom__internal(&config, pDecoder);
  53638. if (result != MA_SUCCESS) {
  53639. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53640. }
  53641. }
  53642. /*
  53643. If we get to this point and we still haven't found a decoder, and the caller has requested a
  53644. specific encoding format, there's no hope for it. Abort.
  53645. */
  53646. if (config.encodingFormat != ma_encoding_format_unknown) {
  53647. return MA_NO_BACKEND;
  53648. }
  53649. #ifdef MA_HAS_WAV
  53650. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"wav")) {
  53651. result = ma_decoder_init_wav__internal(&config, pDecoder);
  53652. if (result != MA_SUCCESS) {
  53653. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53654. }
  53655. }
  53656. #endif
  53657. #ifdef MA_HAS_FLAC
  53658. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"flac")) {
  53659. result = ma_decoder_init_flac__internal(&config, pDecoder);
  53660. if (result != MA_SUCCESS) {
  53661. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53662. }
  53663. }
  53664. #endif
  53665. #ifdef MA_HAS_MP3
  53666. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"mp3")) {
  53667. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  53668. if (result != MA_SUCCESS) {
  53669. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53670. }
  53671. }
  53672. #endif
  53673. }
  53674. /* If we still haven't got a result just use trial and error. Otherwise we can finish up. */
  53675. if (result != MA_SUCCESS) {
  53676. result = ma_decoder_init__internal(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, NULL, &config, pDecoder);
  53677. } else {
  53678. result = ma_decoder__postinit(&config, pDecoder);
  53679. }
  53680. if (result != MA_SUCCESS) {
  53681. ma_vfs_or_default_close(pVFS, pDecoder->data.vfs.file);
  53682. return result;
  53683. }
  53684. return MA_SUCCESS;
  53685. }
  53686. MA_API ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53687. {
  53688. return ma_decoder_init_vfs(NULL, pFilePath, pConfig, pDecoder);
  53689. }
  53690. MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53691. {
  53692. return ma_decoder_init_vfs_w(NULL, pFilePath, pConfig, pDecoder);
  53693. }
  53694. MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder)
  53695. {
  53696. if (pDecoder == NULL) {
  53697. return MA_INVALID_ARGS;
  53698. }
  53699. if (pDecoder->pBackend != NULL) {
  53700. if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) {
  53701. pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, pDecoder->pBackend, &pDecoder->allocationCallbacks);
  53702. }
  53703. }
  53704. if (pDecoder->onRead == ma_decoder__on_read_vfs) {
  53705. ma_vfs_or_default_close(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file);
  53706. pDecoder->data.vfs.file = NULL;
  53707. }
  53708. ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks);
  53709. ma_data_source_uninit(&pDecoder->ds);
  53710. if (pDecoder->pInputCache != NULL) {
  53711. ma_free(pDecoder->pInputCache, &pDecoder->allocationCallbacks);
  53712. }
  53713. return MA_SUCCESS;
  53714. }
  53715. MA_API ma_result ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  53716. {
  53717. ma_result result = MA_SUCCESS;
  53718. ma_uint64 totalFramesReadOut;
  53719. void* pRunningFramesOut;
  53720. if (pFramesRead != NULL) {
  53721. *pFramesRead = 0; /* Safety. */
  53722. }
  53723. if (frameCount == 0) {
  53724. return MA_INVALID_ARGS;
  53725. }
  53726. if (pDecoder == NULL) {
  53727. return MA_INVALID_ARGS;
  53728. }
  53729. if (pDecoder->pBackend == NULL) {
  53730. return MA_INVALID_OPERATION;
  53731. }
  53732. /* Fast path. */
  53733. if (pDecoder->converter.isPassthrough) {
  53734. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pFramesOut, frameCount, &totalFramesReadOut);
  53735. } else {
  53736. /*
  53737. Getting here means we need to do data conversion. If we're seeking forward and are _not_ doing resampling we can run this in a fast path. If we're doing resampling we
  53738. need to run through each sample because we need to ensure it's internal cache is updated.
  53739. */
  53740. if (pFramesOut == NULL && pDecoder->converter.hasResampler == MA_FALSE) {
  53741. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, NULL, frameCount, &totalFramesReadOut);
  53742. } else {
  53743. /* Slow path. Need to run everything through the data converter. */
  53744. ma_format internalFormat;
  53745. ma_uint32 internalChannels;
  53746. totalFramesReadOut = 0;
  53747. pRunningFramesOut = pFramesOut;
  53748. result = ma_data_source_get_data_format(pDecoder->pBackend, &internalFormat, &internalChannels, NULL, NULL, 0);
  53749. if (result != MA_SUCCESS) {
  53750. return result; /* Failed to retrieve the internal format and channel count. */
  53751. }
  53752. /*
  53753. We run a different path depending on whether or not we are using a heap-allocated
  53754. intermediary buffer or not. If the data converter does not support the calculation of
  53755. the required number of input frames, we'll use the heap-allocated path. Otherwise we'll
  53756. use the stack-allocated path.
  53757. */
  53758. if (pDecoder->pInputCache != NULL) {
  53759. /* We don't have a way of determining the required number of input frames, so need to persistently store input data in a cache. */
  53760. while (totalFramesReadOut < frameCount) {
  53761. ma_uint64 framesToReadThisIterationIn;
  53762. ma_uint64 framesToReadThisIterationOut;
  53763. /* If there's any data available in the cache, that needs to get processed first. */
  53764. if (pDecoder->inputCacheRemaining > 0) {
  53765. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  53766. framesToReadThisIterationIn = framesToReadThisIterationOut;
  53767. if (framesToReadThisIterationIn > pDecoder->inputCacheRemaining) {
  53768. framesToReadThisIterationIn = pDecoder->inputCacheRemaining;
  53769. }
  53770. result = ma_data_converter_process_pcm_frames(&pDecoder->converter, ma_offset_pcm_frames_ptr(pDecoder->pInputCache, pDecoder->inputCacheConsumed, internalFormat, internalChannels), &framesToReadThisIterationIn, pRunningFramesOut, &framesToReadThisIterationOut);
  53771. if (result != MA_SUCCESS) {
  53772. break;
  53773. }
  53774. pDecoder->inputCacheConsumed += framesToReadThisIterationIn;
  53775. pDecoder->inputCacheRemaining -= framesToReadThisIterationIn;
  53776. totalFramesReadOut += framesToReadThisIterationOut;
  53777. if (pRunningFramesOut != NULL) {
  53778. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesToReadThisIterationOut * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels));
  53779. }
  53780. if (framesToReadThisIterationIn == 0 && framesToReadThisIterationOut == 0) {
  53781. break; /* We're done. */
  53782. }
  53783. }
  53784. /* Getting here means there's no data in the cache and we need to fill it up from the data source. */
  53785. if (pDecoder->inputCacheRemaining == 0) {
  53786. pDecoder->inputCacheConsumed = 0;
  53787. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pDecoder->pInputCache, pDecoder->inputCacheCap, &pDecoder->inputCacheRemaining);
  53788. if (result != MA_SUCCESS) {
  53789. break;
  53790. }
  53791. }
  53792. }
  53793. } else {
  53794. /* We have a way of determining the required number of input frames so just use the stack. */
  53795. while (totalFramesReadOut < frameCount) {
  53796. ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In internal format. */
  53797. ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(internalFormat, internalChannels);
  53798. ma_uint64 framesToReadThisIterationIn;
  53799. ma_uint64 framesReadThisIterationIn;
  53800. ma_uint64 framesToReadThisIterationOut;
  53801. ma_uint64 framesReadThisIterationOut;
  53802. ma_uint64 requiredInputFrameCount;
  53803. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  53804. framesToReadThisIterationIn = framesToReadThisIterationOut;
  53805. if (framesToReadThisIterationIn > intermediaryBufferCap) {
  53806. framesToReadThisIterationIn = intermediaryBufferCap;
  53807. }
  53808. ma_data_converter_get_required_input_frame_count(&pDecoder->converter, framesToReadThisIterationOut, &requiredInputFrameCount);
  53809. if (framesToReadThisIterationIn > requiredInputFrameCount) {
  53810. framesToReadThisIterationIn = requiredInputFrameCount;
  53811. }
  53812. if (requiredInputFrameCount > 0) {
  53813. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pIntermediaryBuffer, framesToReadThisIterationIn, &framesReadThisIterationIn);
  53814. } else {
  53815. framesReadThisIterationIn = 0;
  53816. }
  53817. /*
  53818. At this point we have our decoded data in input format and now we need to convert to output format. Note that even if we didn't read any
  53819. input frames, we still want to try processing frames because there may some output frames generated from cached input data.
  53820. */
  53821. framesReadThisIterationOut = framesToReadThisIterationOut;
  53822. result = ma_data_converter_process_pcm_frames(&pDecoder->converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut);
  53823. if (result != MA_SUCCESS) {
  53824. break;
  53825. }
  53826. totalFramesReadOut += framesReadThisIterationOut;
  53827. if (pRunningFramesOut != NULL) {
  53828. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels));
  53829. }
  53830. if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) {
  53831. break; /* We're done. */
  53832. }
  53833. }
  53834. }
  53835. }
  53836. }
  53837. pDecoder->readPointerInPCMFrames += totalFramesReadOut;
  53838. if (pFramesRead != NULL) {
  53839. *pFramesRead = totalFramesReadOut;
  53840. }
  53841. if (result == MA_SUCCESS && totalFramesReadOut == 0) {
  53842. result = MA_AT_END;
  53843. }
  53844. return result;
  53845. }
  53846. MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex)
  53847. {
  53848. if (pDecoder == NULL) {
  53849. return MA_INVALID_ARGS;
  53850. }
  53851. if (pDecoder->pBackend != NULL) {
  53852. ma_result result;
  53853. ma_uint64 internalFrameIndex;
  53854. ma_uint32 internalSampleRate;
  53855. ma_uint64 currentFrameIndex;
  53856. result = ma_data_source_get_data_format(pDecoder->pBackend, NULL, NULL, &internalSampleRate, NULL, 0);
  53857. if (result != MA_SUCCESS) {
  53858. return result; /* Failed to retrieve the internal sample rate. */
  53859. }
  53860. if (internalSampleRate == pDecoder->outputSampleRate) {
  53861. internalFrameIndex = frameIndex;
  53862. } else {
  53863. internalFrameIndex = ma_calculate_frame_count_after_resampling(internalSampleRate, pDecoder->outputSampleRate, frameIndex);
  53864. }
  53865. /* Only seek if we're requesting a different frame to what we're currently sitting on. */
  53866. ma_data_source_get_cursor_in_pcm_frames(pDecoder->pBackend, &currentFrameIndex);
  53867. if (currentFrameIndex != internalFrameIndex) {
  53868. result = ma_data_source_seek_to_pcm_frame(pDecoder->pBackend, internalFrameIndex);
  53869. if (result == MA_SUCCESS) {
  53870. pDecoder->readPointerInPCMFrames = frameIndex;
  53871. }
  53872. /* Reset the data converter so that any cached data in the resampler is cleared. */
  53873. ma_data_converter_reset(&pDecoder->converter);
  53874. }
  53875. return result;
  53876. }
  53877. /* Should never get here, but if we do it means onSeekToPCMFrame was not set by the backend. */
  53878. return MA_INVALID_ARGS;
  53879. }
  53880. MA_API ma_result ma_decoder_get_data_format(ma_decoder* pDecoder, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  53881. {
  53882. if (pDecoder == NULL) {
  53883. return MA_INVALID_ARGS;
  53884. }
  53885. if (pFormat != NULL) {
  53886. *pFormat = pDecoder->outputFormat;
  53887. }
  53888. if (pChannels != NULL) {
  53889. *pChannels = pDecoder->outputChannels;
  53890. }
  53891. if (pSampleRate != NULL) {
  53892. *pSampleRate = pDecoder->outputSampleRate;
  53893. }
  53894. if (pChannelMap != NULL) {
  53895. ma_data_converter_get_output_channel_map(&pDecoder->converter, pChannelMap, channelMapCap);
  53896. }
  53897. return MA_SUCCESS;
  53898. }
  53899. MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor)
  53900. {
  53901. if (pCursor == NULL) {
  53902. return MA_INVALID_ARGS;
  53903. }
  53904. *pCursor = 0;
  53905. if (pDecoder == NULL) {
  53906. return MA_INVALID_ARGS;
  53907. }
  53908. *pCursor = pDecoder->readPointerInPCMFrames;
  53909. return MA_SUCCESS;
  53910. }
  53911. MA_API ma_result ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pLength)
  53912. {
  53913. if (pLength == NULL) {
  53914. return MA_INVALID_ARGS;
  53915. }
  53916. *pLength = 0;
  53917. if (pDecoder == NULL) {
  53918. return MA_INVALID_ARGS;
  53919. }
  53920. if (pDecoder->pBackend != NULL) {
  53921. ma_result result;
  53922. ma_uint64 internalLengthInPCMFrames;
  53923. ma_uint32 internalSampleRate;
  53924. result = ma_data_source_get_length_in_pcm_frames(pDecoder->pBackend, &internalLengthInPCMFrames);
  53925. if (result != MA_SUCCESS) {
  53926. return result; /* Failed to retrieve the internal length. */
  53927. }
  53928. result = ma_data_source_get_data_format(pDecoder->pBackend, NULL, NULL, &internalSampleRate, NULL, 0);
  53929. if (result != MA_SUCCESS) {
  53930. return result; /* Failed to retrieve the internal sample rate. */
  53931. }
  53932. if (internalSampleRate == pDecoder->outputSampleRate) {
  53933. *pLength = internalLengthInPCMFrames;
  53934. } else {
  53935. *pLength = ma_calculate_frame_count_after_resampling(pDecoder->outputSampleRate, internalSampleRate, internalLengthInPCMFrames);
  53936. }
  53937. return MA_SUCCESS;
  53938. } else {
  53939. return MA_NO_BACKEND;
  53940. }
  53941. }
  53942. MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames)
  53943. {
  53944. ma_result result;
  53945. ma_uint64 totalFrameCount;
  53946. if (pAvailableFrames == NULL) {
  53947. return MA_INVALID_ARGS;
  53948. }
  53949. *pAvailableFrames = 0;
  53950. if (pDecoder == NULL) {
  53951. return MA_INVALID_ARGS;
  53952. }
  53953. result = ma_decoder_get_length_in_pcm_frames(pDecoder, &totalFrameCount);
  53954. if (result != MA_SUCCESS) {
  53955. return result;
  53956. }
  53957. if (totalFrameCount <= pDecoder->readPointerInPCMFrames) {
  53958. *pAvailableFrames = 0;
  53959. } else {
  53960. *pAvailableFrames = totalFrameCount - pDecoder->readPointerInPCMFrames;
  53961. }
  53962. return MA_SUCCESS;
  53963. }
  53964. static ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_config* pConfigOut, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  53965. {
  53966. ma_result result;
  53967. ma_uint64 totalFrameCount;
  53968. ma_uint64 bpf;
  53969. ma_uint64 dataCapInFrames;
  53970. void* pPCMFramesOut;
  53971. MA_ASSERT(pDecoder != NULL);
  53972. totalFrameCount = 0;
  53973. bpf = ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels);
  53974. /* The frame count is unknown until we try reading. Thus, we just run in a loop. */
  53975. dataCapInFrames = 0;
  53976. pPCMFramesOut = NULL;
  53977. for (;;) {
  53978. ma_uint64 frameCountToTryReading;
  53979. ma_uint64 framesJustRead;
  53980. /* Make room if there's not enough. */
  53981. if (totalFrameCount == dataCapInFrames) {
  53982. void* pNewPCMFramesOut;
  53983. ma_uint64 newDataCapInFrames = dataCapInFrames*2;
  53984. if (newDataCapInFrames == 0) {
  53985. newDataCapInFrames = 4096;
  53986. }
  53987. if ((newDataCapInFrames * bpf) > MA_SIZE_MAX) {
  53988. ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks);
  53989. return MA_TOO_BIG;
  53990. }
  53991. pNewPCMFramesOut = (void*)ma_realloc(pPCMFramesOut, (size_t)(newDataCapInFrames * bpf), &pDecoder->allocationCallbacks);
  53992. if (pNewPCMFramesOut == NULL) {
  53993. ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks);
  53994. return MA_OUT_OF_MEMORY;
  53995. }
  53996. dataCapInFrames = newDataCapInFrames;
  53997. pPCMFramesOut = pNewPCMFramesOut;
  53998. }
  53999. frameCountToTryReading = dataCapInFrames - totalFrameCount;
  54000. MA_ASSERT(frameCountToTryReading > 0);
  54001. result = ma_decoder_read_pcm_frames(pDecoder, (ma_uint8*)pPCMFramesOut + (totalFrameCount * bpf), frameCountToTryReading, &framesJustRead);
  54002. totalFrameCount += framesJustRead;
  54003. if (result != MA_SUCCESS) {
  54004. break;
  54005. }
  54006. if (framesJustRead < frameCountToTryReading) {
  54007. break;
  54008. }
  54009. }
  54010. if (pConfigOut != NULL) {
  54011. pConfigOut->format = pDecoder->outputFormat;
  54012. pConfigOut->channels = pDecoder->outputChannels;
  54013. pConfigOut->sampleRate = pDecoder->outputSampleRate;
  54014. }
  54015. if (ppPCMFramesOut != NULL) {
  54016. *ppPCMFramesOut = pPCMFramesOut;
  54017. } else {
  54018. ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks);
  54019. }
  54020. if (pFrameCountOut != NULL) {
  54021. *pFrameCountOut = totalFrameCount;
  54022. }
  54023. ma_decoder_uninit(pDecoder);
  54024. return MA_SUCCESS;
  54025. }
  54026. MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  54027. {
  54028. ma_result result;
  54029. ma_decoder_config config;
  54030. ma_decoder decoder;
  54031. if (pFrameCountOut != NULL) {
  54032. *pFrameCountOut = 0;
  54033. }
  54034. if (ppPCMFramesOut != NULL) {
  54035. *ppPCMFramesOut = NULL;
  54036. }
  54037. config = ma_decoder_config_init_copy(pConfig);
  54038. result = ma_decoder_init_vfs(pVFS, pFilePath, &config, &decoder);
  54039. if (result != MA_SUCCESS) {
  54040. return result;
  54041. }
  54042. result = ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut);
  54043. return result;
  54044. }
  54045. MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  54046. {
  54047. return ma_decode_from_vfs(NULL, pFilePath, pConfig, pFrameCountOut, ppPCMFramesOut);
  54048. }
  54049. MA_API ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  54050. {
  54051. ma_decoder_config config;
  54052. ma_decoder decoder;
  54053. ma_result result;
  54054. if (pFrameCountOut != NULL) {
  54055. *pFrameCountOut = 0;
  54056. }
  54057. if (ppPCMFramesOut != NULL) {
  54058. *ppPCMFramesOut = NULL;
  54059. }
  54060. if (pData == NULL || dataSize == 0) {
  54061. return MA_INVALID_ARGS;
  54062. }
  54063. config = ma_decoder_config_init_copy(pConfig);
  54064. result = ma_decoder_init_memory(pData, dataSize, &config, &decoder);
  54065. if (result != MA_SUCCESS) {
  54066. return result;
  54067. }
  54068. return ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut);
  54069. }
  54070. #endif /* MA_NO_DECODING */
  54071. #ifndef MA_NO_ENCODING
  54072. #if defined(MA_HAS_WAV)
  54073. static size_t ma_encoder__internal_on_write_wav(void* pUserData, const void* pData, size_t bytesToWrite)
  54074. {
  54075. ma_encoder* pEncoder = (ma_encoder*)pUserData;
  54076. size_t bytesWritten = 0;
  54077. MA_ASSERT(pEncoder != NULL);
  54078. pEncoder->onWrite(pEncoder, pData, bytesToWrite, &bytesWritten);
  54079. return bytesWritten;
  54080. }
  54081. static drwav_bool32 ma_encoder__internal_on_seek_wav(void* pUserData, int offset, drwav_seek_origin origin)
  54082. {
  54083. ma_encoder* pEncoder = (ma_encoder*)pUserData;
  54084. ma_result result;
  54085. MA_ASSERT(pEncoder != NULL);
  54086. result = pEncoder->onSeek(pEncoder, offset, (origin == drwav_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current);
  54087. if (result != MA_SUCCESS) {
  54088. return DRWAV_FALSE;
  54089. } else {
  54090. return DRWAV_TRUE;
  54091. }
  54092. }
  54093. static ma_result ma_encoder__on_init_wav(ma_encoder* pEncoder)
  54094. {
  54095. drwav_data_format wavFormat;
  54096. drwav_allocation_callbacks allocationCallbacks;
  54097. drwav* pWav;
  54098. MA_ASSERT(pEncoder != NULL);
  54099. pWav = (drwav*)ma_malloc(sizeof(*pWav), &pEncoder->config.allocationCallbacks);
  54100. if (pWav == NULL) {
  54101. return MA_OUT_OF_MEMORY;
  54102. }
  54103. wavFormat.container = drwav_container_riff;
  54104. wavFormat.channels = pEncoder->config.channels;
  54105. wavFormat.sampleRate = pEncoder->config.sampleRate;
  54106. wavFormat.bitsPerSample = ma_get_bytes_per_sample(pEncoder->config.format) * 8;
  54107. if (pEncoder->config.format == ma_format_f32) {
  54108. wavFormat.format = DR_WAVE_FORMAT_IEEE_FLOAT;
  54109. } else {
  54110. wavFormat.format = DR_WAVE_FORMAT_PCM;
  54111. }
  54112. allocationCallbacks.pUserData = pEncoder->config.allocationCallbacks.pUserData;
  54113. allocationCallbacks.onMalloc = pEncoder->config.allocationCallbacks.onMalloc;
  54114. allocationCallbacks.onRealloc = pEncoder->config.allocationCallbacks.onRealloc;
  54115. allocationCallbacks.onFree = pEncoder->config.allocationCallbacks.onFree;
  54116. if (!drwav_init_write(pWav, &wavFormat, ma_encoder__internal_on_write_wav, ma_encoder__internal_on_seek_wav, pEncoder, &allocationCallbacks)) {
  54117. return MA_ERROR;
  54118. }
  54119. pEncoder->pInternalEncoder = pWav;
  54120. return MA_SUCCESS;
  54121. }
  54122. static void ma_encoder__on_uninit_wav(ma_encoder* pEncoder)
  54123. {
  54124. drwav* pWav;
  54125. MA_ASSERT(pEncoder != NULL);
  54126. pWav = (drwav*)pEncoder->pInternalEncoder;
  54127. MA_ASSERT(pWav != NULL);
  54128. drwav_uninit(pWav);
  54129. ma_free(pWav, &pEncoder->config.allocationCallbacks);
  54130. }
  54131. static ma_result ma_encoder__on_write_pcm_frames_wav(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten)
  54132. {
  54133. drwav* pWav;
  54134. ma_uint64 framesWritten;
  54135. MA_ASSERT(pEncoder != NULL);
  54136. pWav = (drwav*)pEncoder->pInternalEncoder;
  54137. MA_ASSERT(pWav != NULL);
  54138. framesWritten = drwav_write_pcm_frames(pWav, frameCount, pFramesIn);
  54139. if (pFramesWritten != NULL) {
  54140. *pFramesWritten = framesWritten;
  54141. }
  54142. return MA_SUCCESS;
  54143. }
  54144. #endif
  54145. MA_API ma_encoder_config ma_encoder_config_init(ma_encoding_format encodingFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  54146. {
  54147. ma_encoder_config config;
  54148. MA_ZERO_OBJECT(&config);
  54149. config.encodingFormat = encodingFormat;
  54150. config.format = format;
  54151. config.channels = channels;
  54152. config.sampleRate = sampleRate;
  54153. return config;
  54154. }
  54155. MA_API ma_result ma_encoder_preinit(const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54156. {
  54157. ma_result result;
  54158. if (pEncoder == NULL) {
  54159. return MA_INVALID_ARGS;
  54160. }
  54161. MA_ZERO_OBJECT(pEncoder);
  54162. if (pConfig == NULL) {
  54163. return MA_INVALID_ARGS;
  54164. }
  54165. if (pConfig->format == ma_format_unknown || pConfig->channels == 0 || pConfig->sampleRate == 0) {
  54166. return MA_INVALID_ARGS;
  54167. }
  54168. pEncoder->config = *pConfig;
  54169. result = ma_allocation_callbacks_init_copy(&pEncoder->config.allocationCallbacks, &pConfig->allocationCallbacks);
  54170. if (result != MA_SUCCESS) {
  54171. return result;
  54172. }
  54173. return MA_SUCCESS;
  54174. }
  54175. MA_API ma_result ma_encoder_init__internal(ma_encoder_write_proc onWrite, ma_encoder_seek_proc onSeek, void* pUserData, ma_encoder* pEncoder)
  54176. {
  54177. ma_result result = MA_SUCCESS;
  54178. /* This assumes ma_encoder_preinit() has been called prior. */
  54179. MA_ASSERT(pEncoder != NULL);
  54180. if (onWrite == NULL || onSeek == NULL) {
  54181. return MA_INVALID_ARGS;
  54182. }
  54183. pEncoder->onWrite = onWrite;
  54184. pEncoder->onSeek = onSeek;
  54185. pEncoder->pUserData = pUserData;
  54186. switch (pEncoder->config.encodingFormat)
  54187. {
  54188. case ma_encoding_format_wav:
  54189. {
  54190. #if defined(MA_HAS_WAV)
  54191. pEncoder->onInit = ma_encoder__on_init_wav;
  54192. pEncoder->onUninit = ma_encoder__on_uninit_wav;
  54193. pEncoder->onWritePCMFrames = ma_encoder__on_write_pcm_frames_wav;
  54194. #else
  54195. result = MA_NO_BACKEND;
  54196. #endif
  54197. } break;
  54198. default:
  54199. {
  54200. result = MA_INVALID_ARGS;
  54201. } break;
  54202. }
  54203. /* Getting here means we should have our backend callbacks set up. */
  54204. if (result == MA_SUCCESS) {
  54205. result = pEncoder->onInit(pEncoder);
  54206. }
  54207. return result;
  54208. }
  54209. static ma_result ma_encoder__on_write_vfs(ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite, size_t* pBytesWritten)
  54210. {
  54211. return ma_vfs_or_default_write(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file, pBufferIn, bytesToWrite, pBytesWritten);
  54212. }
  54213. static ma_result ma_encoder__on_seek_vfs(ma_encoder* pEncoder, ma_int64 offset, ma_seek_origin origin)
  54214. {
  54215. return ma_vfs_or_default_seek(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file, offset, origin);
  54216. }
  54217. MA_API ma_result ma_encoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54218. {
  54219. ma_result result;
  54220. ma_vfs_file file;
  54221. result = ma_encoder_preinit(pConfig, pEncoder);
  54222. if (result != MA_SUCCESS) {
  54223. return result;
  54224. }
  54225. /* Now open the file. If this fails we don't need to uninitialize the encoder. */
  54226. result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_WRITE, &file);
  54227. if (result != MA_SUCCESS) {
  54228. return result;
  54229. }
  54230. pEncoder->data.vfs.pVFS = pVFS;
  54231. pEncoder->data.vfs.file = file;
  54232. result = ma_encoder_init__internal(ma_encoder__on_write_vfs, ma_encoder__on_seek_vfs, NULL, pEncoder);
  54233. if (result != MA_SUCCESS) {
  54234. ma_vfs_or_default_close(pVFS, file);
  54235. return result;
  54236. }
  54237. return MA_SUCCESS;
  54238. }
  54239. MA_API ma_result ma_encoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54240. {
  54241. ma_result result;
  54242. ma_vfs_file file;
  54243. result = ma_encoder_preinit(pConfig, pEncoder);
  54244. if (result != MA_SUCCESS) {
  54245. return result;
  54246. }
  54247. /* Now open the file. If this fails we don't need to uninitialize the encoder. */
  54248. result = ma_vfs_or_default_open_w(pVFS, pFilePath, MA_OPEN_MODE_WRITE, &file);
  54249. if (result != MA_SUCCESS) {
  54250. return result;
  54251. }
  54252. pEncoder->data.vfs.pVFS = pVFS;
  54253. pEncoder->data.vfs.file = file;
  54254. result = ma_encoder_init__internal(ma_encoder__on_write_vfs, ma_encoder__on_seek_vfs, NULL, pEncoder);
  54255. if (result != MA_SUCCESS) {
  54256. ma_vfs_or_default_close(pVFS, file);
  54257. return result;
  54258. }
  54259. return MA_SUCCESS;
  54260. }
  54261. MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54262. {
  54263. return ma_encoder_init_vfs(NULL, pFilePath, pConfig, pEncoder);
  54264. }
  54265. MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54266. {
  54267. return ma_encoder_init_vfs_w(NULL, pFilePath, pConfig, pEncoder);
  54268. }
  54269. MA_API ma_result ma_encoder_init(ma_encoder_write_proc onWrite, ma_encoder_seek_proc onSeek, void* pUserData, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54270. {
  54271. ma_result result;
  54272. result = ma_encoder_preinit(pConfig, pEncoder);
  54273. if (result != MA_SUCCESS) {
  54274. return result;
  54275. }
  54276. return ma_encoder_init__internal(onWrite, onSeek, pUserData, pEncoder);
  54277. }
  54278. MA_API void ma_encoder_uninit(ma_encoder* pEncoder)
  54279. {
  54280. if (pEncoder == NULL) {
  54281. return;
  54282. }
  54283. if (pEncoder->onUninit) {
  54284. pEncoder->onUninit(pEncoder);
  54285. }
  54286. /* If we have a file handle, close it. */
  54287. if (pEncoder->onWrite == ma_encoder__on_write_vfs) {
  54288. ma_vfs_or_default_close(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file);
  54289. pEncoder->data.vfs.file = NULL;
  54290. }
  54291. }
  54292. MA_API ma_result ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten)
  54293. {
  54294. if (pFramesWritten != NULL) {
  54295. *pFramesWritten = 0;
  54296. }
  54297. if (pEncoder == NULL || pFramesIn == NULL) {
  54298. return MA_INVALID_ARGS;
  54299. }
  54300. return pEncoder->onWritePCMFrames(pEncoder, pFramesIn, frameCount, pFramesWritten);
  54301. }
  54302. #endif /* MA_NO_ENCODING */
  54303. /**************************************************************************************************************************************************************
  54304. Generation
  54305. **************************************************************************************************************************************************************/
  54306. #ifndef MA_NO_GENERATION
  54307. MA_API ma_waveform_config ma_waveform_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_waveform_type type, double amplitude, double frequency)
  54308. {
  54309. ma_waveform_config config;
  54310. MA_ZERO_OBJECT(&config);
  54311. config.format = format;
  54312. config.channels = channels;
  54313. config.sampleRate = sampleRate;
  54314. config.type = type;
  54315. config.amplitude = amplitude;
  54316. config.frequency = frequency;
  54317. return config;
  54318. }
  54319. static ma_result ma_waveform__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  54320. {
  54321. return ma_waveform_read_pcm_frames((ma_waveform*)pDataSource, pFramesOut, frameCount, pFramesRead);
  54322. }
  54323. static ma_result ma_waveform__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  54324. {
  54325. return ma_waveform_seek_to_pcm_frame((ma_waveform*)pDataSource, frameIndex);
  54326. }
  54327. static ma_result ma_waveform__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  54328. {
  54329. ma_waveform* pWaveform = (ma_waveform*)pDataSource;
  54330. *pFormat = pWaveform->config.format;
  54331. *pChannels = pWaveform->config.channels;
  54332. *pSampleRate = pWaveform->config.sampleRate;
  54333. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pWaveform->config.channels);
  54334. return MA_SUCCESS;
  54335. }
  54336. static ma_result ma_waveform__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  54337. {
  54338. ma_waveform* pWaveform = (ma_waveform*)pDataSource;
  54339. *pCursor = (ma_uint64)(pWaveform->time / pWaveform->advance);
  54340. return MA_SUCCESS;
  54341. }
  54342. static double ma_waveform__calculate_advance(ma_uint32 sampleRate, double frequency)
  54343. {
  54344. return (1.0 / (sampleRate / frequency));
  54345. }
  54346. static void ma_waveform__update_advance(ma_waveform* pWaveform)
  54347. {
  54348. pWaveform->advance = ma_waveform__calculate_advance(pWaveform->config.sampleRate, pWaveform->config.frequency);
  54349. }
  54350. static ma_data_source_vtable g_ma_waveform_data_source_vtable =
  54351. {
  54352. ma_waveform__data_source_on_read,
  54353. ma_waveform__data_source_on_seek,
  54354. ma_waveform__data_source_on_get_data_format,
  54355. ma_waveform__data_source_on_get_cursor,
  54356. NULL, /* onGetLength. There's no notion of a length in waveforms. */
  54357. NULL, /* onSetLooping */
  54358. 0
  54359. };
  54360. MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform)
  54361. {
  54362. ma_result result;
  54363. ma_data_source_config dataSourceConfig;
  54364. if (pWaveform == NULL) {
  54365. return MA_INVALID_ARGS;
  54366. }
  54367. MA_ZERO_OBJECT(pWaveform);
  54368. dataSourceConfig = ma_data_source_config_init();
  54369. dataSourceConfig.vtable = &g_ma_waveform_data_source_vtable;
  54370. result = ma_data_source_init(&dataSourceConfig, &pWaveform->ds);
  54371. if (result != MA_SUCCESS) {
  54372. return result;
  54373. }
  54374. pWaveform->config = *pConfig;
  54375. pWaveform->advance = ma_waveform__calculate_advance(pWaveform->config.sampleRate, pWaveform->config.frequency);
  54376. pWaveform->time = 0;
  54377. return MA_SUCCESS;
  54378. }
  54379. MA_API void ma_waveform_uninit(ma_waveform* pWaveform)
  54380. {
  54381. if (pWaveform == NULL) {
  54382. return;
  54383. }
  54384. ma_data_source_uninit(&pWaveform->ds);
  54385. }
  54386. MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude)
  54387. {
  54388. if (pWaveform == NULL) {
  54389. return MA_INVALID_ARGS;
  54390. }
  54391. pWaveform->config.amplitude = amplitude;
  54392. return MA_SUCCESS;
  54393. }
  54394. MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency)
  54395. {
  54396. if (pWaveform == NULL) {
  54397. return MA_INVALID_ARGS;
  54398. }
  54399. pWaveform->config.frequency = frequency;
  54400. ma_waveform__update_advance(pWaveform);
  54401. return MA_SUCCESS;
  54402. }
  54403. MA_API ma_result ma_waveform_set_type(ma_waveform* pWaveform, ma_waveform_type type)
  54404. {
  54405. if (pWaveform == NULL) {
  54406. return MA_INVALID_ARGS;
  54407. }
  54408. pWaveform->config.type = type;
  54409. return MA_SUCCESS;
  54410. }
  54411. MA_API ma_result ma_waveform_set_sample_rate(ma_waveform* pWaveform, ma_uint32 sampleRate)
  54412. {
  54413. if (pWaveform == NULL) {
  54414. return MA_INVALID_ARGS;
  54415. }
  54416. pWaveform->config.sampleRate = sampleRate;
  54417. ma_waveform__update_advance(pWaveform);
  54418. return MA_SUCCESS;
  54419. }
  54420. static float ma_waveform_sine_f32(double time, double amplitude)
  54421. {
  54422. return (float)(ma_sind(MA_TAU_D * time) * amplitude);
  54423. }
  54424. static ma_int16 ma_waveform_sine_s16(double time, double amplitude)
  54425. {
  54426. return ma_pcm_sample_f32_to_s16(ma_waveform_sine_f32(time, amplitude));
  54427. }
  54428. static float ma_waveform_square_f32(double time, double amplitude)
  54429. {
  54430. double f = time - (ma_int64)time;
  54431. double r;
  54432. if (f < 0.5) {
  54433. r = amplitude;
  54434. } else {
  54435. r = -amplitude;
  54436. }
  54437. return (float)r;
  54438. }
  54439. static ma_int16 ma_waveform_square_s16(double time, double amplitude)
  54440. {
  54441. return ma_pcm_sample_f32_to_s16(ma_waveform_square_f32(time, amplitude));
  54442. }
  54443. static float ma_waveform_triangle_f32(double time, double amplitude)
  54444. {
  54445. double f = time - (ma_int64)time;
  54446. double r;
  54447. r = 2 * ma_abs(2 * (f - 0.5)) - 1;
  54448. return (float)(r * amplitude);
  54449. }
  54450. static ma_int16 ma_waveform_triangle_s16(double time, double amplitude)
  54451. {
  54452. return ma_pcm_sample_f32_to_s16(ma_waveform_triangle_f32(time, amplitude));
  54453. }
  54454. static float ma_waveform_sawtooth_f32(double time, double amplitude)
  54455. {
  54456. double f = time - (ma_int64)time;
  54457. double r;
  54458. r = 2 * (f - 0.5);
  54459. return (float)(r * amplitude);
  54460. }
  54461. static ma_int16 ma_waveform_sawtooth_s16(double time, double amplitude)
  54462. {
  54463. return ma_pcm_sample_f32_to_s16(ma_waveform_sawtooth_f32(time, amplitude));
  54464. }
  54465. static void ma_waveform_read_pcm_frames__sine(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  54466. {
  54467. ma_uint64 iFrame;
  54468. ma_uint64 iChannel;
  54469. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  54470. ma_uint32 bpf = bps * pWaveform->config.channels;
  54471. MA_ASSERT(pWaveform != NULL);
  54472. MA_ASSERT(pFramesOut != NULL);
  54473. if (pWaveform->config.format == ma_format_f32) {
  54474. float* pFramesOutF32 = (float*)pFramesOut;
  54475. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54476. float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.amplitude);
  54477. pWaveform->time += pWaveform->advance;
  54478. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54479. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  54480. }
  54481. }
  54482. } else if (pWaveform->config.format == ma_format_s16) {
  54483. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  54484. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54485. ma_int16 s = ma_waveform_sine_s16(pWaveform->time, pWaveform->config.amplitude);
  54486. pWaveform->time += pWaveform->advance;
  54487. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54488. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  54489. }
  54490. }
  54491. } else {
  54492. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54493. float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.amplitude);
  54494. pWaveform->time += pWaveform->advance;
  54495. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54496. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54497. }
  54498. }
  54499. }
  54500. }
  54501. static void ma_waveform_read_pcm_frames__square(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  54502. {
  54503. ma_uint64 iFrame;
  54504. ma_uint64 iChannel;
  54505. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  54506. ma_uint32 bpf = bps * pWaveform->config.channels;
  54507. MA_ASSERT(pWaveform != NULL);
  54508. MA_ASSERT(pFramesOut != NULL);
  54509. if (pWaveform->config.format == ma_format_f32) {
  54510. float* pFramesOutF32 = (float*)pFramesOut;
  54511. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54512. float s = ma_waveform_square_f32(pWaveform->time, pWaveform->config.amplitude);
  54513. pWaveform->time += pWaveform->advance;
  54514. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54515. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  54516. }
  54517. }
  54518. } else if (pWaveform->config.format == ma_format_s16) {
  54519. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  54520. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54521. ma_int16 s = ma_waveform_square_s16(pWaveform->time, pWaveform->config.amplitude);
  54522. pWaveform->time += pWaveform->advance;
  54523. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54524. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  54525. }
  54526. }
  54527. } else {
  54528. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54529. float s = ma_waveform_square_f32(pWaveform->time, pWaveform->config.amplitude);
  54530. pWaveform->time += pWaveform->advance;
  54531. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54532. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54533. }
  54534. }
  54535. }
  54536. }
  54537. static void ma_waveform_read_pcm_frames__triangle(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  54538. {
  54539. ma_uint64 iFrame;
  54540. ma_uint64 iChannel;
  54541. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  54542. ma_uint32 bpf = bps * pWaveform->config.channels;
  54543. MA_ASSERT(pWaveform != NULL);
  54544. MA_ASSERT(pFramesOut != NULL);
  54545. if (pWaveform->config.format == ma_format_f32) {
  54546. float* pFramesOutF32 = (float*)pFramesOut;
  54547. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54548. float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.amplitude);
  54549. pWaveform->time += pWaveform->advance;
  54550. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54551. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  54552. }
  54553. }
  54554. } else if (pWaveform->config.format == ma_format_s16) {
  54555. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  54556. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54557. ma_int16 s = ma_waveform_triangle_s16(pWaveform->time, pWaveform->config.amplitude);
  54558. pWaveform->time += pWaveform->advance;
  54559. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54560. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  54561. }
  54562. }
  54563. } else {
  54564. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54565. float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.amplitude);
  54566. pWaveform->time += pWaveform->advance;
  54567. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54568. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54569. }
  54570. }
  54571. }
  54572. }
  54573. static void ma_waveform_read_pcm_frames__sawtooth(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  54574. {
  54575. ma_uint64 iFrame;
  54576. ma_uint64 iChannel;
  54577. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  54578. ma_uint32 bpf = bps * pWaveform->config.channels;
  54579. MA_ASSERT(pWaveform != NULL);
  54580. MA_ASSERT(pFramesOut != NULL);
  54581. if (pWaveform->config.format == ma_format_f32) {
  54582. float* pFramesOutF32 = (float*)pFramesOut;
  54583. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54584. float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.amplitude);
  54585. pWaveform->time += pWaveform->advance;
  54586. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54587. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  54588. }
  54589. }
  54590. } else if (pWaveform->config.format == ma_format_s16) {
  54591. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  54592. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54593. ma_int16 s = ma_waveform_sawtooth_s16(pWaveform->time, pWaveform->config.amplitude);
  54594. pWaveform->time += pWaveform->advance;
  54595. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54596. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  54597. }
  54598. }
  54599. } else {
  54600. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54601. float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.amplitude);
  54602. pWaveform->time += pWaveform->advance;
  54603. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54604. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54605. }
  54606. }
  54607. }
  54608. }
  54609. MA_API ma_result ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  54610. {
  54611. if (pFramesRead != NULL) {
  54612. *pFramesRead = 0;
  54613. }
  54614. if (frameCount == 0) {
  54615. return MA_INVALID_ARGS;
  54616. }
  54617. if (pWaveform == NULL) {
  54618. return MA_INVALID_ARGS;
  54619. }
  54620. if (pFramesOut != NULL) {
  54621. switch (pWaveform->config.type)
  54622. {
  54623. case ma_waveform_type_sine:
  54624. {
  54625. ma_waveform_read_pcm_frames__sine(pWaveform, pFramesOut, frameCount);
  54626. } break;
  54627. case ma_waveform_type_square:
  54628. {
  54629. ma_waveform_read_pcm_frames__square(pWaveform, pFramesOut, frameCount);
  54630. } break;
  54631. case ma_waveform_type_triangle:
  54632. {
  54633. ma_waveform_read_pcm_frames__triangle(pWaveform, pFramesOut, frameCount);
  54634. } break;
  54635. case ma_waveform_type_sawtooth:
  54636. {
  54637. ma_waveform_read_pcm_frames__sawtooth(pWaveform, pFramesOut, frameCount);
  54638. } break;
  54639. default: return MA_INVALID_OPERATION; /* Unknown waveform type. */
  54640. }
  54641. } else {
  54642. pWaveform->time += pWaveform->advance * (ma_int64)frameCount; /* Cast to int64 required for VC6. Won't affect anything in practice. */
  54643. }
  54644. if (pFramesRead != NULL) {
  54645. *pFramesRead = frameCount;
  54646. }
  54647. return MA_SUCCESS;
  54648. }
  54649. MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex)
  54650. {
  54651. if (pWaveform == NULL) {
  54652. return MA_INVALID_ARGS;
  54653. }
  54654. pWaveform->time = pWaveform->advance * (ma_int64)frameIndex; /* Casting for VC6. Won't be an issue in practice. */
  54655. return MA_SUCCESS;
  54656. }
  54657. MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude)
  54658. {
  54659. ma_noise_config config;
  54660. MA_ZERO_OBJECT(&config);
  54661. config.format = format;
  54662. config.channels = channels;
  54663. config.type = type;
  54664. config.seed = seed;
  54665. config.amplitude = amplitude;
  54666. if (config.seed == 0) {
  54667. config.seed = MA_DEFAULT_LCG_SEED;
  54668. }
  54669. return config;
  54670. }
  54671. static ma_result ma_noise__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  54672. {
  54673. return ma_noise_read_pcm_frames((ma_noise*)pDataSource, pFramesOut, frameCount, pFramesRead);
  54674. }
  54675. static ma_result ma_noise__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  54676. {
  54677. /* No-op. Just pretend to be successful. */
  54678. (void)pDataSource;
  54679. (void)frameIndex;
  54680. return MA_SUCCESS;
  54681. }
  54682. static ma_result ma_noise__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  54683. {
  54684. ma_noise* pNoise = (ma_noise*)pDataSource;
  54685. *pFormat = pNoise->config.format;
  54686. *pChannels = pNoise->config.channels;
  54687. *pSampleRate = 0; /* There is no notion of sample rate with noise generation. */
  54688. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pNoise->config.channels);
  54689. return MA_SUCCESS;
  54690. }
  54691. static ma_data_source_vtable g_ma_noise_data_source_vtable =
  54692. {
  54693. ma_noise__data_source_on_read,
  54694. ma_noise__data_source_on_seek, /* No-op for noise. */
  54695. ma_noise__data_source_on_get_data_format,
  54696. NULL, /* onGetCursor. No notion of a cursor for noise. */
  54697. NULL, /* onGetLength. No notion of a length for noise. */
  54698. NULL, /* onSetLooping */
  54699. 0
  54700. };
  54701. #ifndef MA_PINK_NOISE_BIN_SIZE
  54702. #define MA_PINK_NOISE_BIN_SIZE 16
  54703. #endif
  54704. typedef struct
  54705. {
  54706. size_t sizeInBytes;
  54707. struct
  54708. {
  54709. size_t binOffset;
  54710. size_t accumulationOffset;
  54711. size_t counterOffset;
  54712. } pink;
  54713. struct
  54714. {
  54715. size_t accumulationOffset;
  54716. } brownian;
  54717. } ma_noise_heap_layout;
  54718. static ma_result ma_noise_get_heap_layout(const ma_noise_config* pConfig, ma_noise_heap_layout* pHeapLayout)
  54719. {
  54720. MA_ASSERT(pHeapLayout != NULL);
  54721. MA_ZERO_OBJECT(pHeapLayout);
  54722. if (pConfig == NULL) {
  54723. return MA_INVALID_ARGS;
  54724. }
  54725. if (pConfig->channels == 0) {
  54726. return MA_INVALID_ARGS;
  54727. }
  54728. pHeapLayout->sizeInBytes = 0;
  54729. /* Pink. */
  54730. if (pConfig->type == ma_noise_type_pink) {
  54731. /* bin */
  54732. pHeapLayout->pink.binOffset = pHeapLayout->sizeInBytes;
  54733. pHeapLayout->sizeInBytes += sizeof(double*) * pConfig->channels;
  54734. pHeapLayout->sizeInBytes += sizeof(double ) * pConfig->channels * MA_PINK_NOISE_BIN_SIZE;
  54735. /* accumulation */
  54736. pHeapLayout->pink.accumulationOffset = pHeapLayout->sizeInBytes;
  54737. pHeapLayout->sizeInBytes += sizeof(double) * pConfig->channels;
  54738. /* counter */
  54739. pHeapLayout->pink.counterOffset = pHeapLayout->sizeInBytes;
  54740. pHeapLayout->sizeInBytes += sizeof(ma_uint32) * pConfig->channels;
  54741. }
  54742. /* Brownian. */
  54743. if (pConfig->type == ma_noise_type_brownian) {
  54744. /* accumulation */
  54745. pHeapLayout->brownian.accumulationOffset = pHeapLayout->sizeInBytes;
  54746. pHeapLayout->sizeInBytes += sizeof(double) * pConfig->channels;
  54747. }
  54748. /* Make sure allocation size is aligned. */
  54749. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  54750. return MA_SUCCESS;
  54751. }
  54752. MA_API ma_result ma_noise_get_heap_size(const ma_noise_config* pConfig, size_t* pHeapSizeInBytes)
  54753. {
  54754. ma_result result;
  54755. ma_noise_heap_layout heapLayout;
  54756. if (pHeapSizeInBytes == NULL) {
  54757. return MA_INVALID_ARGS;
  54758. }
  54759. *pHeapSizeInBytes = 0;
  54760. result = ma_noise_get_heap_layout(pConfig, &heapLayout);
  54761. if (result != MA_SUCCESS) {
  54762. return result;
  54763. }
  54764. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  54765. return MA_SUCCESS;
  54766. }
  54767. MA_API ma_result ma_noise_init_preallocated(const ma_noise_config* pConfig, void* pHeap, ma_noise* pNoise)
  54768. {
  54769. ma_result result;
  54770. ma_noise_heap_layout heapLayout;
  54771. ma_data_source_config dataSourceConfig;
  54772. ma_uint32 iChannel;
  54773. if (pNoise == NULL) {
  54774. return MA_INVALID_ARGS;
  54775. }
  54776. MA_ZERO_OBJECT(pNoise);
  54777. result = ma_noise_get_heap_layout(pConfig, &heapLayout);
  54778. if (result != MA_SUCCESS) {
  54779. return result;
  54780. }
  54781. pNoise->_pHeap = pHeap;
  54782. MA_ZERO_MEMORY(pNoise->_pHeap, heapLayout.sizeInBytes);
  54783. dataSourceConfig = ma_data_source_config_init();
  54784. dataSourceConfig.vtable = &g_ma_noise_data_source_vtable;
  54785. result = ma_data_source_init(&dataSourceConfig, &pNoise->ds);
  54786. if (result != MA_SUCCESS) {
  54787. return result;
  54788. }
  54789. pNoise->config = *pConfig;
  54790. ma_lcg_seed(&pNoise->lcg, pConfig->seed);
  54791. if (pNoise->config.type == ma_noise_type_pink) {
  54792. pNoise->state.pink.bin = (double** )ma_offset_ptr(pHeap, heapLayout.pink.binOffset);
  54793. pNoise->state.pink.accumulation = (double* )ma_offset_ptr(pHeap, heapLayout.pink.accumulationOffset);
  54794. pNoise->state.pink.counter = (ma_uint32*)ma_offset_ptr(pHeap, heapLayout.pink.counterOffset);
  54795. for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
  54796. pNoise->state.pink.bin[iChannel] = (double*)ma_offset_ptr(pHeap, heapLayout.pink.binOffset + (sizeof(double*) * pConfig->channels) + (sizeof(double) * MA_PINK_NOISE_BIN_SIZE * iChannel));
  54797. pNoise->state.pink.accumulation[iChannel] = 0;
  54798. pNoise->state.pink.counter[iChannel] = 1;
  54799. }
  54800. }
  54801. if (pNoise->config.type == ma_noise_type_brownian) {
  54802. pNoise->state.brownian.accumulation = (double*)ma_offset_ptr(pHeap, heapLayout.brownian.accumulationOffset);
  54803. for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
  54804. pNoise->state.brownian.accumulation[iChannel] = 0;
  54805. }
  54806. }
  54807. return MA_SUCCESS;
  54808. }
  54809. MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_noise* pNoise)
  54810. {
  54811. ma_result result;
  54812. size_t heapSizeInBytes;
  54813. void* pHeap;
  54814. result = ma_noise_get_heap_size(pConfig, &heapSizeInBytes);
  54815. if (result != MA_SUCCESS) {
  54816. return result;
  54817. }
  54818. if (heapSizeInBytes > 0) {
  54819. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  54820. if (pHeap == NULL) {
  54821. return MA_OUT_OF_MEMORY;
  54822. }
  54823. } else {
  54824. pHeap = NULL;
  54825. }
  54826. result = ma_noise_init_preallocated(pConfig, pHeap, pNoise);
  54827. if (result != MA_SUCCESS) {
  54828. ma_free(pHeap, pAllocationCallbacks);
  54829. return result;
  54830. }
  54831. pNoise->_ownsHeap = MA_TRUE;
  54832. return MA_SUCCESS;
  54833. }
  54834. MA_API void ma_noise_uninit(ma_noise* pNoise, const ma_allocation_callbacks* pAllocationCallbacks)
  54835. {
  54836. if (pNoise == NULL) {
  54837. return;
  54838. }
  54839. ma_data_source_uninit(&pNoise->ds);
  54840. if (pNoise->_ownsHeap) {
  54841. ma_free(pNoise->_pHeap, pAllocationCallbacks);
  54842. }
  54843. }
  54844. MA_API ma_result ma_noise_set_amplitude(ma_noise* pNoise, double amplitude)
  54845. {
  54846. if (pNoise == NULL) {
  54847. return MA_INVALID_ARGS;
  54848. }
  54849. pNoise->config.amplitude = amplitude;
  54850. return MA_SUCCESS;
  54851. }
  54852. MA_API ma_result ma_noise_set_seed(ma_noise* pNoise, ma_int32 seed)
  54853. {
  54854. if (pNoise == NULL) {
  54855. return MA_INVALID_ARGS;
  54856. }
  54857. pNoise->lcg.state = seed;
  54858. return MA_SUCCESS;
  54859. }
  54860. MA_API ma_result ma_noise_set_type(ma_noise* pNoise, ma_noise_type type)
  54861. {
  54862. if (pNoise == NULL) {
  54863. return MA_INVALID_ARGS;
  54864. }
  54865. /*
  54866. This function should never have been implemented in the first place. Changing the type dynamically is not
  54867. supported. Instead you need to uninitialize and reinitiailize a fresh `ma_noise` object. This function
  54868. will be removed in version 0.12.
  54869. */
  54870. MA_ASSERT(MA_FALSE);
  54871. (void)type;
  54872. return MA_INVALID_OPERATION;
  54873. }
  54874. static MA_INLINE float ma_noise_f32_white(ma_noise* pNoise)
  54875. {
  54876. return (float)(ma_lcg_rand_f64(&pNoise->lcg) * pNoise->config.amplitude);
  54877. }
  54878. static MA_INLINE ma_int16 ma_noise_s16_white(ma_noise* pNoise)
  54879. {
  54880. return ma_pcm_sample_f32_to_s16(ma_noise_f32_white(pNoise));
  54881. }
  54882. static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__white(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
  54883. {
  54884. ma_uint64 iFrame;
  54885. ma_uint32 iChannel;
  54886. const ma_uint32 channels = pNoise->config.channels;
  54887. MA_ASSUME(channels > 0);
  54888. if (pNoise->config.format == ma_format_f32) {
  54889. float* pFramesOutF32 = (float*)pFramesOut;
  54890. if (pNoise->config.duplicateChannels) {
  54891. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54892. float s = ma_noise_f32_white(pNoise);
  54893. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  54894. pFramesOutF32[iFrame*channels + iChannel] = s;
  54895. }
  54896. }
  54897. } else {
  54898. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54899. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  54900. pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_white(pNoise);
  54901. }
  54902. }
  54903. }
  54904. } else if (pNoise->config.format == ma_format_s16) {
  54905. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  54906. if (pNoise->config.duplicateChannels) {
  54907. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54908. ma_int16 s = ma_noise_s16_white(pNoise);
  54909. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  54910. pFramesOutS16[iFrame*channels + iChannel] = s;
  54911. }
  54912. }
  54913. } else {
  54914. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54915. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  54916. pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_white(pNoise);
  54917. }
  54918. }
  54919. }
  54920. } else {
  54921. const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
  54922. const ma_uint32 bpf = bps * channels;
  54923. if (pNoise->config.duplicateChannels) {
  54924. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54925. float s = ma_noise_f32_white(pNoise);
  54926. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  54927. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54928. }
  54929. }
  54930. } else {
  54931. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54932. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  54933. float s = ma_noise_f32_white(pNoise);
  54934. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54935. }
  54936. }
  54937. }
  54938. }
  54939. return frameCount;
  54940. }
  54941. static MA_INLINE unsigned int ma_tzcnt32(unsigned int x)
  54942. {
  54943. unsigned int n;
  54944. /* Special case for odd numbers since they should happen about half the time. */
  54945. if (x & 0x1) {
  54946. return 0;
  54947. }
  54948. if (x == 0) {
  54949. return sizeof(x) << 3;
  54950. }
  54951. n = 1;
  54952. if ((x & 0x0000FFFF) == 0) { x >>= 16; n += 16; }
  54953. if ((x & 0x000000FF) == 0) { x >>= 8; n += 8; }
  54954. if ((x & 0x0000000F) == 0) { x >>= 4; n += 4; }
  54955. if ((x & 0x00000003) == 0) { x >>= 2; n += 2; }
  54956. n -= x & 0x00000001;
  54957. return n;
  54958. }
  54959. /*
  54960. Pink noise generation based on Tonic (public domain) with modifications. https://github.com/TonicAudio/Tonic/blob/master/src/Tonic/Noise.h
  54961. This is basically _the_ reference for pink noise from what I've found: http://www.firstpr.com.au/dsp/pink-noise/
  54962. */
  54963. static MA_INLINE float ma_noise_f32_pink(ma_noise* pNoise, ma_uint32 iChannel)
  54964. {
  54965. double result;
  54966. double binPrev;
  54967. double binNext;
  54968. unsigned int ibin;
  54969. ibin = ma_tzcnt32(pNoise->state.pink.counter[iChannel]) & (MA_PINK_NOISE_BIN_SIZE - 1);
  54970. binPrev = pNoise->state.pink.bin[iChannel][ibin];
  54971. binNext = ma_lcg_rand_f64(&pNoise->lcg);
  54972. pNoise->state.pink.bin[iChannel][ibin] = binNext;
  54973. pNoise->state.pink.accumulation[iChannel] += (binNext - binPrev);
  54974. pNoise->state.pink.counter[iChannel] += 1;
  54975. result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.pink.accumulation[iChannel]);
  54976. result /= 10;
  54977. return (float)(result * pNoise->config.amplitude);
  54978. }
  54979. static MA_INLINE ma_int16 ma_noise_s16_pink(ma_noise* pNoise, ma_uint32 iChannel)
  54980. {
  54981. return ma_pcm_sample_f32_to_s16(ma_noise_f32_pink(pNoise, iChannel));
  54982. }
  54983. static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__pink(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
  54984. {
  54985. ma_uint64 iFrame;
  54986. ma_uint32 iChannel;
  54987. const ma_uint32 channels = pNoise->config.channels;
  54988. MA_ASSUME(channels > 0);
  54989. if (pNoise->config.format == ma_format_f32) {
  54990. float* pFramesOutF32 = (float*)pFramesOut;
  54991. if (pNoise->config.duplicateChannels) {
  54992. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54993. float s = ma_noise_f32_pink(pNoise, 0);
  54994. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  54995. pFramesOutF32[iFrame*channels + iChannel] = s;
  54996. }
  54997. }
  54998. } else {
  54999. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55000. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55001. pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_pink(pNoise, iChannel);
  55002. }
  55003. }
  55004. }
  55005. } else if (pNoise->config.format == ma_format_s16) {
  55006. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  55007. if (pNoise->config.duplicateChannels) {
  55008. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55009. ma_int16 s = ma_noise_s16_pink(pNoise, 0);
  55010. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55011. pFramesOutS16[iFrame*channels + iChannel] = s;
  55012. }
  55013. }
  55014. } else {
  55015. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55016. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55017. pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_pink(pNoise, iChannel);
  55018. }
  55019. }
  55020. }
  55021. } else {
  55022. const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
  55023. const ma_uint32 bpf = bps * channels;
  55024. if (pNoise->config.duplicateChannels) {
  55025. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55026. float s = ma_noise_f32_pink(pNoise, 0);
  55027. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55028. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55029. }
  55030. }
  55031. } else {
  55032. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55033. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55034. float s = ma_noise_f32_pink(pNoise, iChannel);
  55035. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55036. }
  55037. }
  55038. }
  55039. }
  55040. return frameCount;
  55041. }
  55042. static MA_INLINE float ma_noise_f32_brownian(ma_noise* pNoise, ma_uint32 iChannel)
  55043. {
  55044. double result;
  55045. result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.brownian.accumulation[iChannel]);
  55046. result /= 1.005; /* Don't escape the -1..1 range on average. */
  55047. pNoise->state.brownian.accumulation[iChannel] = result;
  55048. result /= 20;
  55049. return (float)(result * pNoise->config.amplitude);
  55050. }
  55051. static MA_INLINE ma_int16 ma_noise_s16_brownian(ma_noise* pNoise, ma_uint32 iChannel)
  55052. {
  55053. return ma_pcm_sample_f32_to_s16(ma_noise_f32_brownian(pNoise, iChannel));
  55054. }
  55055. static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__brownian(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
  55056. {
  55057. ma_uint64 iFrame;
  55058. ma_uint32 iChannel;
  55059. const ma_uint32 channels = pNoise->config.channels;
  55060. MA_ASSUME(channels > 0);
  55061. if (pNoise->config.format == ma_format_f32) {
  55062. float* pFramesOutF32 = (float*)pFramesOut;
  55063. if (pNoise->config.duplicateChannels) {
  55064. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55065. float s = ma_noise_f32_brownian(pNoise, 0);
  55066. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55067. pFramesOutF32[iFrame*channels + iChannel] = s;
  55068. }
  55069. }
  55070. } else {
  55071. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55072. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55073. pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_brownian(pNoise, iChannel);
  55074. }
  55075. }
  55076. }
  55077. } else if (pNoise->config.format == ma_format_s16) {
  55078. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  55079. if (pNoise->config.duplicateChannels) {
  55080. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55081. ma_int16 s = ma_noise_s16_brownian(pNoise, 0);
  55082. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55083. pFramesOutS16[iFrame*channels + iChannel] = s;
  55084. }
  55085. }
  55086. } else {
  55087. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55088. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55089. pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_brownian(pNoise, iChannel);
  55090. }
  55091. }
  55092. }
  55093. } else {
  55094. const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
  55095. const ma_uint32 bpf = bps * channels;
  55096. if (pNoise->config.duplicateChannels) {
  55097. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55098. float s = ma_noise_f32_brownian(pNoise, 0);
  55099. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55100. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55101. }
  55102. }
  55103. } else {
  55104. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55105. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55106. float s = ma_noise_f32_brownian(pNoise, iChannel);
  55107. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55108. }
  55109. }
  55110. }
  55111. }
  55112. return frameCount;
  55113. }
  55114. MA_API ma_result ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  55115. {
  55116. ma_uint64 framesRead = 0;
  55117. if (pFramesRead != NULL) {
  55118. *pFramesRead = 0;
  55119. }
  55120. if (frameCount == 0) {
  55121. return MA_INVALID_ARGS;
  55122. }
  55123. if (pNoise == NULL) {
  55124. return MA_INVALID_ARGS;
  55125. }
  55126. /* The output buffer is allowed to be NULL. Since we aren't tracking cursors or anything we can just do nothing and pretend to be successful. */
  55127. if (pFramesOut == NULL) {
  55128. framesRead = frameCount;
  55129. } else {
  55130. switch (pNoise->config.type) {
  55131. case ma_noise_type_white: framesRead = ma_noise_read_pcm_frames__white (pNoise, pFramesOut, frameCount); break;
  55132. case ma_noise_type_pink: framesRead = ma_noise_read_pcm_frames__pink (pNoise, pFramesOut, frameCount); break;
  55133. case ma_noise_type_brownian: framesRead = ma_noise_read_pcm_frames__brownian(pNoise, pFramesOut, frameCount); break;
  55134. default: return MA_INVALID_OPERATION; /* Unknown noise type. */
  55135. }
  55136. }
  55137. if (pFramesRead != NULL) {
  55138. *pFramesRead = framesRead;
  55139. }
  55140. return MA_SUCCESS;
  55141. }
  55142. #endif /* MA_NO_GENERATION */
  55143. #ifndef MA_NO_RESOURCE_MANAGER
  55144. #ifndef MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS
  55145. #define MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS 1000
  55146. #endif
  55147. #ifndef MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY
  55148. #define MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY 1024
  55149. #endif
  55150. MA_API ma_resource_manager_pipeline_notifications ma_resource_manager_pipeline_notifications_init(void)
  55151. {
  55152. ma_resource_manager_pipeline_notifications notifications;
  55153. MA_ZERO_OBJECT(&notifications);
  55154. return notifications;
  55155. }
  55156. static void ma_resource_manager_pipeline_notifications_signal_all_notifications(const ma_resource_manager_pipeline_notifications* pPipelineNotifications)
  55157. {
  55158. if (pPipelineNotifications == NULL) {
  55159. return;
  55160. }
  55161. if (pPipelineNotifications->init.pNotification) { ma_async_notification_signal(pPipelineNotifications->init.pNotification); }
  55162. if (pPipelineNotifications->done.pNotification) { ma_async_notification_signal(pPipelineNotifications->done.pNotification); }
  55163. }
  55164. static void ma_resource_manager_pipeline_notifications_acquire_all_fences(const ma_resource_manager_pipeline_notifications* pPipelineNotifications)
  55165. {
  55166. if (pPipelineNotifications == NULL) {
  55167. return;
  55168. }
  55169. if (pPipelineNotifications->init.pFence != NULL) { ma_fence_acquire(pPipelineNotifications->init.pFence); }
  55170. if (pPipelineNotifications->done.pFence != NULL) { ma_fence_acquire(pPipelineNotifications->done.pFence); }
  55171. }
  55172. static void ma_resource_manager_pipeline_notifications_release_all_fences(const ma_resource_manager_pipeline_notifications* pPipelineNotifications)
  55173. {
  55174. if (pPipelineNotifications == NULL) {
  55175. return;
  55176. }
  55177. if (pPipelineNotifications->init.pFence != NULL) { ma_fence_release(pPipelineNotifications->init.pFence); }
  55178. if (pPipelineNotifications->done.pFence != NULL) { ma_fence_release(pPipelineNotifications->done.pFence); }
  55179. }
  55180. #ifndef MA_DEFAULT_HASH_SEED
  55181. #define MA_DEFAULT_HASH_SEED 42
  55182. #endif
  55183. /* MurmurHash3. Based on code from https://github.com/PeterScott/murmur3/blob/master/murmur3.c (public domain). */
  55184. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  55185. #pragma GCC diagnostic push
  55186. #if __GNUC__ >= 7
  55187. #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  55188. #endif
  55189. #endif
  55190. static MA_INLINE ma_uint32 ma_rotl32(ma_uint32 x, ma_int8 r)
  55191. {
  55192. return (x << r) | (x >> (32 - r));
  55193. }
  55194. static MA_INLINE ma_uint32 ma_hash_getblock(const ma_uint32* blocks, int i)
  55195. {
  55196. ma_uint32 block;
  55197. /* Try silencing a sanitization warning about unaligned access by doing a memcpy() instead of assignment. */
  55198. MA_COPY_MEMORY(&block, ma_offset_ptr(blocks, i * sizeof(block)), sizeof(block));
  55199. if (ma_is_little_endian()) {
  55200. return block;
  55201. } else {
  55202. return ma_swap_endian_uint32(block);
  55203. }
  55204. }
  55205. static MA_INLINE ma_uint32 ma_hash_fmix32(ma_uint32 h)
  55206. {
  55207. h ^= h >> 16;
  55208. h *= 0x85ebca6b;
  55209. h ^= h >> 13;
  55210. h *= 0xc2b2ae35;
  55211. h ^= h >> 16;
  55212. return h;
  55213. }
  55214. static ma_uint32 ma_hash_32(const void* key, int len, ma_uint32 seed)
  55215. {
  55216. const ma_uint8* data = (const ma_uint8*)key;
  55217. const ma_uint32* blocks;
  55218. const ma_uint8* tail;
  55219. const int nblocks = len / 4;
  55220. ma_uint32 h1 = seed;
  55221. ma_uint32 c1 = 0xcc9e2d51;
  55222. ma_uint32 c2 = 0x1b873593;
  55223. ma_uint32 k1;
  55224. int i;
  55225. blocks = (const ma_uint32 *)(data + nblocks*4);
  55226. for(i = -nblocks; i; i++) {
  55227. k1 = ma_hash_getblock(blocks,i);
  55228. k1 *= c1;
  55229. k1 = ma_rotl32(k1, 15);
  55230. k1 *= c2;
  55231. h1 ^= k1;
  55232. h1 = ma_rotl32(h1, 13);
  55233. h1 = h1*5 + 0xe6546b64;
  55234. }
  55235. tail = (const ma_uint8*)(data + nblocks*4);
  55236. k1 = 0;
  55237. switch(len & 3) {
  55238. case 3: k1 ^= tail[2] << 16;
  55239. case 2: k1 ^= tail[1] << 8;
  55240. case 1: k1 ^= tail[0];
  55241. k1 *= c1; k1 = ma_rotl32(k1, 15); k1 *= c2; h1 ^= k1;
  55242. };
  55243. h1 ^= len;
  55244. h1 = ma_hash_fmix32(h1);
  55245. return h1;
  55246. }
  55247. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  55248. #pragma GCC diagnostic push
  55249. #endif
  55250. /* End MurmurHash3 */
  55251. static ma_uint32 ma_hash_string_32(const char* str)
  55252. {
  55253. return ma_hash_32(str, (int)strlen(str), MA_DEFAULT_HASH_SEED);
  55254. }
  55255. static ma_uint32 ma_hash_string_w_32(const wchar_t* str)
  55256. {
  55257. return ma_hash_32(str, (int)wcslen(str) * sizeof(*str), MA_DEFAULT_HASH_SEED);
  55258. }
  55259. /*
  55260. Basic BST Functions
  55261. */
  55262. static ma_result ma_resource_manager_data_buffer_node_search(ma_resource_manager* pResourceManager, ma_uint32 hashedName32, ma_resource_manager_data_buffer_node** ppDataBufferNode)
  55263. {
  55264. ma_resource_manager_data_buffer_node* pCurrentNode;
  55265. MA_ASSERT(pResourceManager != NULL);
  55266. MA_ASSERT(ppDataBufferNode != NULL);
  55267. pCurrentNode = pResourceManager->pRootDataBufferNode;
  55268. while (pCurrentNode != NULL) {
  55269. if (hashedName32 == pCurrentNode->hashedName32) {
  55270. break; /* Found. */
  55271. } else if (hashedName32 < pCurrentNode->hashedName32) {
  55272. pCurrentNode = pCurrentNode->pChildLo;
  55273. } else {
  55274. pCurrentNode = pCurrentNode->pChildHi;
  55275. }
  55276. }
  55277. *ppDataBufferNode = pCurrentNode;
  55278. if (pCurrentNode == NULL) {
  55279. return MA_DOES_NOT_EXIST;
  55280. } else {
  55281. return MA_SUCCESS;
  55282. }
  55283. }
  55284. static ma_result ma_resource_manager_data_buffer_node_insert_point(ma_resource_manager* pResourceManager, ma_uint32 hashedName32, ma_resource_manager_data_buffer_node** ppInsertPoint)
  55285. {
  55286. ma_result result = MA_SUCCESS;
  55287. ma_resource_manager_data_buffer_node* pCurrentNode;
  55288. MA_ASSERT(pResourceManager != NULL);
  55289. MA_ASSERT(ppInsertPoint != NULL);
  55290. *ppInsertPoint = NULL;
  55291. if (pResourceManager->pRootDataBufferNode == NULL) {
  55292. return MA_SUCCESS; /* No items. */
  55293. }
  55294. /* We need to find the node that will become the parent of the new node. If a node is found that already has the same hashed name we need to return MA_ALREADY_EXISTS. */
  55295. pCurrentNode = pResourceManager->pRootDataBufferNode;
  55296. while (pCurrentNode != NULL) {
  55297. if (hashedName32 == pCurrentNode->hashedName32) {
  55298. result = MA_ALREADY_EXISTS;
  55299. break;
  55300. } else {
  55301. if (hashedName32 < pCurrentNode->hashedName32) {
  55302. if (pCurrentNode->pChildLo == NULL) {
  55303. result = MA_SUCCESS;
  55304. break;
  55305. } else {
  55306. pCurrentNode = pCurrentNode->pChildLo;
  55307. }
  55308. } else {
  55309. if (pCurrentNode->pChildHi == NULL) {
  55310. result = MA_SUCCESS;
  55311. break;
  55312. } else {
  55313. pCurrentNode = pCurrentNode->pChildHi;
  55314. }
  55315. }
  55316. }
  55317. }
  55318. *ppInsertPoint = pCurrentNode;
  55319. return result;
  55320. }
  55321. static ma_result ma_resource_manager_data_buffer_node_insert_at(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, ma_resource_manager_data_buffer_node* pInsertPoint)
  55322. {
  55323. MA_ASSERT(pResourceManager != NULL);
  55324. MA_ASSERT(pDataBufferNode != NULL);
  55325. /* The key must have been set before calling this function. */
  55326. MA_ASSERT(pDataBufferNode->hashedName32 != 0);
  55327. if (pInsertPoint == NULL) {
  55328. /* It's the first node. */
  55329. pResourceManager->pRootDataBufferNode = pDataBufferNode;
  55330. } else {
  55331. /* It's not the first node. It needs to be inserted. */
  55332. if (pDataBufferNode->hashedName32 < pInsertPoint->hashedName32) {
  55333. MA_ASSERT(pInsertPoint->pChildLo == NULL);
  55334. pInsertPoint->pChildLo = pDataBufferNode;
  55335. } else {
  55336. MA_ASSERT(pInsertPoint->pChildHi == NULL);
  55337. pInsertPoint->pChildHi = pDataBufferNode;
  55338. }
  55339. }
  55340. pDataBufferNode->pParent = pInsertPoint;
  55341. return MA_SUCCESS;
  55342. }
  55343. #if 0 /* Unused for now. */
  55344. static ma_result ma_resource_manager_data_buffer_node_insert(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode)
  55345. {
  55346. ma_result result;
  55347. ma_resource_manager_data_buffer_node* pInsertPoint;
  55348. MA_ASSERT(pResourceManager != NULL);
  55349. MA_ASSERT(pDataBufferNode != NULL);
  55350. result = ma_resource_manager_data_buffer_node_insert_point(pResourceManager, pDataBufferNode->hashedName32, &pInsertPoint);
  55351. if (result != MA_SUCCESS) {
  55352. return MA_INVALID_ARGS;
  55353. }
  55354. return ma_resource_manager_data_buffer_node_insert_at(pResourceManager, pDataBufferNode, pInsertPoint);
  55355. }
  55356. #endif
  55357. static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_min(ma_resource_manager_data_buffer_node* pDataBufferNode)
  55358. {
  55359. ma_resource_manager_data_buffer_node* pCurrentNode;
  55360. MA_ASSERT(pDataBufferNode != NULL);
  55361. pCurrentNode = pDataBufferNode;
  55362. while (pCurrentNode->pChildLo != NULL) {
  55363. pCurrentNode = pCurrentNode->pChildLo;
  55364. }
  55365. return pCurrentNode;
  55366. }
  55367. static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_max(ma_resource_manager_data_buffer_node* pDataBufferNode)
  55368. {
  55369. ma_resource_manager_data_buffer_node* pCurrentNode;
  55370. MA_ASSERT(pDataBufferNode != NULL);
  55371. pCurrentNode = pDataBufferNode;
  55372. while (pCurrentNode->pChildHi != NULL) {
  55373. pCurrentNode = pCurrentNode->pChildHi;
  55374. }
  55375. return pCurrentNode;
  55376. }
  55377. static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_inorder_successor(ma_resource_manager_data_buffer_node* pDataBufferNode)
  55378. {
  55379. MA_ASSERT(pDataBufferNode != NULL);
  55380. MA_ASSERT(pDataBufferNode->pChildHi != NULL);
  55381. return ma_resource_manager_data_buffer_node_find_min(pDataBufferNode->pChildHi);
  55382. }
  55383. static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_inorder_predecessor(ma_resource_manager_data_buffer_node* pDataBufferNode)
  55384. {
  55385. MA_ASSERT(pDataBufferNode != NULL);
  55386. MA_ASSERT(pDataBufferNode->pChildLo != NULL);
  55387. return ma_resource_manager_data_buffer_node_find_max(pDataBufferNode->pChildLo);
  55388. }
  55389. static ma_result ma_resource_manager_data_buffer_node_remove(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode)
  55390. {
  55391. MA_ASSERT(pResourceManager != NULL);
  55392. MA_ASSERT(pDataBufferNode != NULL);
  55393. if (pDataBufferNode->pChildLo == NULL) {
  55394. if (pDataBufferNode->pChildHi == NULL) {
  55395. /* Simple case - deleting a buffer with no children. */
  55396. if (pDataBufferNode->pParent == NULL) {
  55397. MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode); /* There is only a single buffer in the tree which should be equal to the root node. */
  55398. pResourceManager->pRootDataBufferNode = NULL;
  55399. } else {
  55400. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  55401. pDataBufferNode->pParent->pChildLo = NULL;
  55402. } else {
  55403. pDataBufferNode->pParent->pChildHi = NULL;
  55404. }
  55405. }
  55406. } else {
  55407. /* Node has one child - pChildHi != NULL. */
  55408. pDataBufferNode->pChildHi->pParent = pDataBufferNode->pParent;
  55409. if (pDataBufferNode->pParent == NULL) {
  55410. MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode);
  55411. pResourceManager->pRootDataBufferNode = pDataBufferNode->pChildHi;
  55412. } else {
  55413. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  55414. pDataBufferNode->pParent->pChildLo = pDataBufferNode->pChildHi;
  55415. } else {
  55416. pDataBufferNode->pParent->pChildHi = pDataBufferNode->pChildHi;
  55417. }
  55418. }
  55419. }
  55420. } else {
  55421. if (pDataBufferNode->pChildHi == NULL) {
  55422. /* Node has one child - pChildLo != NULL. */
  55423. pDataBufferNode->pChildLo->pParent = pDataBufferNode->pParent;
  55424. if (pDataBufferNode->pParent == NULL) {
  55425. MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode);
  55426. pResourceManager->pRootDataBufferNode = pDataBufferNode->pChildLo;
  55427. } else {
  55428. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  55429. pDataBufferNode->pParent->pChildLo = pDataBufferNode->pChildLo;
  55430. } else {
  55431. pDataBufferNode->pParent->pChildHi = pDataBufferNode->pChildLo;
  55432. }
  55433. }
  55434. } else {
  55435. /* Complex case - deleting a node with two children. */
  55436. ma_resource_manager_data_buffer_node* pReplacementDataBufferNode;
  55437. /* For now we are just going to use the in-order successor as the replacement, but we may want to try to keep this balanced by switching between the two. */
  55438. pReplacementDataBufferNode = ma_resource_manager_data_buffer_node_find_inorder_successor(pDataBufferNode);
  55439. MA_ASSERT(pReplacementDataBufferNode != NULL);
  55440. /*
  55441. Now that we have our replacement node we can make the change. The simple way to do this would be to just exchange the values, and then remove the replacement
  55442. node, however we track specific nodes via pointers which means we can't just swap out the values. We need to instead just change the pointers around. The
  55443. replacement node should have at most 1 child. Therefore, we can detach it in terms of our simpler cases above. What we're essentially doing is detaching the
  55444. replacement node and reinserting it into the same position as the deleted node.
  55445. */
  55446. MA_ASSERT(pReplacementDataBufferNode->pParent != NULL); /* The replacement node should never be the root which means it should always have a parent. */
  55447. MA_ASSERT(pReplacementDataBufferNode->pChildLo == NULL); /* Because we used in-order successor. This would be pChildHi == NULL if we used in-order predecessor. */
  55448. if (pReplacementDataBufferNode->pChildHi == NULL) {
  55449. if (pReplacementDataBufferNode->pParent->pChildLo == pReplacementDataBufferNode) {
  55450. pReplacementDataBufferNode->pParent->pChildLo = NULL;
  55451. } else {
  55452. pReplacementDataBufferNode->pParent->pChildHi = NULL;
  55453. }
  55454. } else {
  55455. pReplacementDataBufferNode->pChildHi->pParent = pReplacementDataBufferNode->pParent;
  55456. if (pReplacementDataBufferNode->pParent->pChildLo == pReplacementDataBufferNode) {
  55457. pReplacementDataBufferNode->pParent->pChildLo = pReplacementDataBufferNode->pChildHi;
  55458. } else {
  55459. pReplacementDataBufferNode->pParent->pChildHi = pReplacementDataBufferNode->pChildHi;
  55460. }
  55461. }
  55462. /* The replacement node has essentially been detached from the binary tree, so now we need to replace the old data buffer with it. The first thing to update is the parent */
  55463. if (pDataBufferNode->pParent != NULL) {
  55464. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  55465. pDataBufferNode->pParent->pChildLo = pReplacementDataBufferNode;
  55466. } else {
  55467. pDataBufferNode->pParent->pChildHi = pReplacementDataBufferNode;
  55468. }
  55469. }
  55470. /* Now need to update the replacement node's pointers. */
  55471. pReplacementDataBufferNode->pParent = pDataBufferNode->pParent;
  55472. pReplacementDataBufferNode->pChildLo = pDataBufferNode->pChildLo;
  55473. pReplacementDataBufferNode->pChildHi = pDataBufferNode->pChildHi;
  55474. /* Now the children of the replacement node need to have their parent pointers updated. */
  55475. if (pReplacementDataBufferNode->pChildLo != NULL) {
  55476. pReplacementDataBufferNode->pChildLo->pParent = pReplacementDataBufferNode;
  55477. }
  55478. if (pReplacementDataBufferNode->pChildHi != NULL) {
  55479. pReplacementDataBufferNode->pChildHi->pParent = pReplacementDataBufferNode;
  55480. }
  55481. /* Now the root node needs to be updated. */
  55482. if (pResourceManager->pRootDataBufferNode == pDataBufferNode) {
  55483. pResourceManager->pRootDataBufferNode = pReplacementDataBufferNode;
  55484. }
  55485. }
  55486. }
  55487. return MA_SUCCESS;
  55488. }
  55489. #if 0 /* Unused for now. */
  55490. static ma_result ma_resource_manager_data_buffer_node_remove_by_key(ma_resource_manager* pResourceManager, ma_uint32 hashedName32)
  55491. {
  55492. ma_result result;
  55493. ma_resource_manager_data_buffer_node* pDataBufferNode;
  55494. result = ma_resource_manager_data_buffer_search(pResourceManager, hashedName32, &pDataBufferNode);
  55495. if (result != MA_SUCCESS) {
  55496. return result; /* Could not find the data buffer. */
  55497. }
  55498. return ma_resource_manager_data_buffer_remove(pResourceManager, pDataBufferNode);
  55499. }
  55500. #endif
  55501. static ma_resource_manager_data_supply_type ma_resource_manager_data_buffer_node_get_data_supply_type(ma_resource_manager_data_buffer_node* pDataBufferNode)
  55502. {
  55503. return (ma_resource_manager_data_supply_type)c89atomic_load_i32(&pDataBufferNode->data.type);
  55504. }
  55505. static void ma_resource_manager_data_buffer_node_set_data_supply_type(ma_resource_manager_data_buffer_node* pDataBufferNode, ma_resource_manager_data_supply_type supplyType)
  55506. {
  55507. c89atomic_exchange_i32(&pDataBufferNode->data.type, supplyType);
  55508. }
  55509. static ma_result ma_resource_manager_data_buffer_node_increment_ref(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, ma_uint32* pNewRefCount)
  55510. {
  55511. ma_uint32 refCount;
  55512. MA_ASSERT(pResourceManager != NULL);
  55513. MA_ASSERT(pDataBufferNode != NULL);
  55514. (void)pResourceManager;
  55515. refCount = c89atomic_fetch_add_32(&pDataBufferNode->refCount, 1) + 1;
  55516. if (pNewRefCount != NULL) {
  55517. *pNewRefCount = refCount;
  55518. }
  55519. return MA_SUCCESS;
  55520. }
  55521. static ma_result ma_resource_manager_data_buffer_node_decrement_ref(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, ma_uint32* pNewRefCount)
  55522. {
  55523. ma_uint32 refCount;
  55524. MA_ASSERT(pResourceManager != NULL);
  55525. MA_ASSERT(pDataBufferNode != NULL);
  55526. (void)pResourceManager;
  55527. refCount = c89atomic_fetch_sub_32(&pDataBufferNode->refCount, 1) - 1;
  55528. if (pNewRefCount != NULL) {
  55529. *pNewRefCount = refCount;
  55530. }
  55531. return MA_SUCCESS;
  55532. }
  55533. static void ma_resource_manager_data_buffer_node_free(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode)
  55534. {
  55535. MA_ASSERT(pResourceManager != NULL);
  55536. MA_ASSERT(pDataBufferNode != NULL);
  55537. if (pDataBufferNode->isDataOwnedByResourceManager) {
  55538. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_encoded) {
  55539. ma_free((void*)pDataBufferNode->data.backend.encoded.pData, &pResourceManager->config.allocationCallbacks);
  55540. pDataBufferNode->data.backend.encoded.pData = NULL;
  55541. pDataBufferNode->data.backend.encoded.sizeInBytes = 0;
  55542. } else if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_decoded) {
  55543. ma_free((void*)pDataBufferNode->data.backend.decoded.pData, &pResourceManager->config.allocationCallbacks);
  55544. pDataBufferNode->data.backend.decoded.pData = NULL;
  55545. pDataBufferNode->data.backend.decoded.totalFrameCount = 0;
  55546. } else if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_decoded_paged) {
  55547. ma_paged_audio_buffer_data_uninit(&pDataBufferNode->data.backend.decodedPaged.data, &pResourceManager->config.allocationCallbacks);
  55548. } else {
  55549. /* Should never hit this if the node was successfully initialized. */
  55550. MA_ASSERT(pDataBufferNode->result != MA_SUCCESS);
  55551. }
  55552. }
  55553. /* The data buffer itself needs to be freed. */
  55554. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  55555. }
  55556. static ma_result ma_resource_manager_data_buffer_node_result(const ma_resource_manager_data_buffer_node* pDataBufferNode)
  55557. {
  55558. MA_ASSERT(pDataBufferNode != NULL);
  55559. return (ma_result)c89atomic_load_i32((ma_result*)&pDataBufferNode->result); /* Need a naughty const-cast here. */
  55560. }
  55561. static ma_bool32 ma_resource_manager_is_threading_enabled(const ma_resource_manager* pResourceManager)
  55562. {
  55563. MA_ASSERT(pResourceManager != NULL);
  55564. return (pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) == 0;
  55565. }
  55566. typedef struct
  55567. {
  55568. union
  55569. {
  55570. ma_async_notification_event e;
  55571. ma_async_notification_poll p;
  55572. } backend; /* Must be the first member. */
  55573. ma_resource_manager* pResourceManager;
  55574. } ma_resource_manager_inline_notification;
  55575. static ma_result ma_resource_manager_inline_notification_init(ma_resource_manager* pResourceManager, ma_resource_manager_inline_notification* pNotification)
  55576. {
  55577. MA_ASSERT(pResourceManager != NULL);
  55578. MA_ASSERT(pNotification != NULL);
  55579. pNotification->pResourceManager = pResourceManager;
  55580. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  55581. return ma_async_notification_event_init(&pNotification->backend.e);
  55582. } else {
  55583. return ma_async_notification_poll_init(&pNotification->backend.p);
  55584. }
  55585. }
  55586. static void ma_resource_manager_inline_notification_uninit(ma_resource_manager_inline_notification* pNotification)
  55587. {
  55588. MA_ASSERT(pNotification != NULL);
  55589. if (ma_resource_manager_is_threading_enabled(pNotification->pResourceManager)) {
  55590. ma_async_notification_event_uninit(&pNotification->backend.e);
  55591. } else {
  55592. /* No need to uninitialize a polling notification. */
  55593. }
  55594. }
  55595. static void ma_resource_manager_inline_notification_wait(ma_resource_manager_inline_notification* pNotification)
  55596. {
  55597. MA_ASSERT(pNotification != NULL);
  55598. if (ma_resource_manager_is_threading_enabled(pNotification->pResourceManager)) {
  55599. ma_async_notification_event_wait(&pNotification->backend.e);
  55600. } else {
  55601. while (ma_async_notification_poll_is_signalled(&pNotification->backend.p) == MA_FALSE) {
  55602. ma_result result = ma_resource_manager_process_next_job(pNotification->pResourceManager);
  55603. if (result == MA_NO_DATA_AVAILABLE || result == MA_CANCELLED) {
  55604. break;
  55605. }
  55606. }
  55607. }
  55608. }
  55609. static void ma_resource_manager_inline_notification_wait_and_uninit(ma_resource_manager_inline_notification* pNotification)
  55610. {
  55611. ma_resource_manager_inline_notification_wait(pNotification);
  55612. ma_resource_manager_inline_notification_uninit(pNotification);
  55613. }
  55614. static void ma_resource_manager_data_buffer_bst_lock(ma_resource_manager* pResourceManager)
  55615. {
  55616. MA_ASSERT(pResourceManager != NULL);
  55617. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  55618. #ifndef MA_NO_THREADING
  55619. {
  55620. ma_mutex_lock(&pResourceManager->dataBufferBSTLock);
  55621. }
  55622. #else
  55623. {
  55624. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  55625. }
  55626. #endif
  55627. } else {
  55628. /* Threading not enabled. Do nothing. */
  55629. }
  55630. }
  55631. static void ma_resource_manager_data_buffer_bst_unlock(ma_resource_manager* pResourceManager)
  55632. {
  55633. MA_ASSERT(pResourceManager != NULL);
  55634. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  55635. #ifndef MA_NO_THREADING
  55636. {
  55637. ma_mutex_unlock(&pResourceManager->dataBufferBSTLock);
  55638. }
  55639. #else
  55640. {
  55641. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  55642. }
  55643. #endif
  55644. } else {
  55645. /* Threading not enabled. Do nothing. */
  55646. }
  55647. }
  55648. #ifndef MA_NO_THREADING
  55649. static ma_thread_result MA_THREADCALL ma_resource_manager_job_thread(void* pUserData)
  55650. {
  55651. ma_resource_manager* pResourceManager = (ma_resource_manager*)pUserData;
  55652. MA_ASSERT(pResourceManager != NULL);
  55653. for (;;) {
  55654. ma_result result;
  55655. ma_job job;
  55656. result = ma_resource_manager_next_job(pResourceManager, &job);
  55657. if (result != MA_SUCCESS) {
  55658. break;
  55659. }
  55660. /* Terminate if we got a quit message. */
  55661. if (job.toc.breakup.code == MA_JOB_TYPE_QUIT) {
  55662. break;
  55663. }
  55664. ma_job_process(&job);
  55665. }
  55666. return (ma_thread_result)0;
  55667. }
  55668. #endif
  55669. MA_API ma_resource_manager_config ma_resource_manager_config_init(void)
  55670. {
  55671. ma_resource_manager_config config;
  55672. MA_ZERO_OBJECT(&config);
  55673. config.decodedFormat = ma_format_unknown;
  55674. config.decodedChannels = 0;
  55675. config.decodedSampleRate = 0;
  55676. config.jobThreadCount = 1; /* A single miniaudio-managed job thread by default. */
  55677. config.jobQueueCapacity = MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY;
  55678. /* Flags. */
  55679. config.flags = 0;
  55680. #ifdef MA_NO_THREADING
  55681. {
  55682. /* Threading is disabled at compile time so disable threading at runtime as well by default. */
  55683. config.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING;
  55684. config.jobThreadCount = 0;
  55685. }
  55686. #endif
  55687. return config;
  55688. }
  55689. MA_API ma_result ma_resource_manager_init(const ma_resource_manager_config* pConfig, ma_resource_manager* pResourceManager)
  55690. {
  55691. ma_result result;
  55692. ma_job_queue_config jobQueueConfig;
  55693. if (pResourceManager == NULL) {
  55694. return MA_INVALID_ARGS;
  55695. }
  55696. MA_ZERO_OBJECT(pResourceManager);
  55697. if (pConfig == NULL) {
  55698. return MA_INVALID_ARGS;
  55699. }
  55700. #ifndef MA_NO_THREADING
  55701. {
  55702. if (pConfig->jobThreadCount > ma_countof(pResourceManager->jobThreads)) {
  55703. return MA_INVALID_ARGS; /* Requesting too many job threads. */
  55704. }
  55705. }
  55706. #endif
  55707. pResourceManager->config = *pConfig;
  55708. ma_allocation_callbacks_init_copy(&pResourceManager->config.allocationCallbacks, &pConfig->allocationCallbacks);
  55709. /* Get the log set up early so we can start using it as soon as possible. */
  55710. if (pResourceManager->config.pLog == NULL) {
  55711. result = ma_log_init(&pResourceManager->config.allocationCallbacks, &pResourceManager->log);
  55712. if (result == MA_SUCCESS) {
  55713. pResourceManager->config.pLog = &pResourceManager->log;
  55714. } else {
  55715. pResourceManager->config.pLog = NULL; /* Logging is unavailable. */
  55716. }
  55717. }
  55718. if (pResourceManager->config.pVFS == NULL) {
  55719. result = ma_default_vfs_init(&pResourceManager->defaultVFS, &pResourceManager->config.allocationCallbacks);
  55720. if (result != MA_SUCCESS) {
  55721. return result; /* Failed to initialize the default file system. */
  55722. }
  55723. pResourceManager->config.pVFS = &pResourceManager->defaultVFS;
  55724. }
  55725. /* If threading has been disabled at compile time, enfore it at run time as well. */
  55726. #ifdef MA_NO_THREADING
  55727. {
  55728. pResourceManager->config.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING;
  55729. }
  55730. #endif
  55731. /* We need to force MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING if MA_RESOURCE_MANAGER_FLAG_NO_THREADING is set. */
  55732. if ((pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) != 0) {
  55733. pResourceManager->config.flags |= MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING;
  55734. /* We cannot allow job threads when MA_RESOURCE_MANAGER_FLAG_NO_THREADING has been set. This is an invalid use case. */
  55735. if (pResourceManager->config.jobThreadCount > 0) {
  55736. return MA_INVALID_ARGS;
  55737. }
  55738. }
  55739. /* Job queue. */
  55740. jobQueueConfig.capacity = pResourceManager->config.jobQueueCapacity;
  55741. jobQueueConfig.flags = 0;
  55742. if ((pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING) != 0) {
  55743. if (pResourceManager->config.jobThreadCount > 0) {
  55744. return MA_INVALID_ARGS; /* Non-blocking mode is only valid for self-managed job threads. */
  55745. }
  55746. jobQueueConfig.flags |= MA_JOB_QUEUE_FLAG_NON_BLOCKING;
  55747. }
  55748. result = ma_job_queue_init(&jobQueueConfig, &pResourceManager->config.allocationCallbacks, &pResourceManager->jobQueue);
  55749. if (result != MA_SUCCESS) {
  55750. return result;
  55751. }
  55752. /* Custom decoding backends. */
  55753. if (pConfig->ppCustomDecodingBackendVTables != NULL && pConfig->customDecodingBackendCount > 0) {
  55754. size_t sizeInBytes = sizeof(*pResourceManager->config.ppCustomDecodingBackendVTables) * pConfig->customDecodingBackendCount;
  55755. pResourceManager->config.ppCustomDecodingBackendVTables = (ma_decoding_backend_vtable**)ma_malloc(sizeInBytes, &pResourceManager->config.allocationCallbacks);
  55756. if (pResourceManager->config.ppCustomDecodingBackendVTables == NULL) {
  55757. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  55758. return MA_OUT_OF_MEMORY;
  55759. }
  55760. MA_COPY_MEMORY(pResourceManager->config.ppCustomDecodingBackendVTables, pConfig->ppCustomDecodingBackendVTables, sizeInBytes);
  55761. pResourceManager->config.customDecodingBackendCount = pConfig->customDecodingBackendCount;
  55762. pResourceManager->config.pCustomDecodingBackendUserData = pConfig->pCustomDecodingBackendUserData;
  55763. }
  55764. /* Here is where we initialize our threading stuff. We don't do this if we don't support threading. */
  55765. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  55766. #ifndef MA_NO_THREADING
  55767. {
  55768. ma_uint32 iJobThread;
  55769. /* Data buffer lock. */
  55770. result = ma_mutex_init(&pResourceManager->dataBufferBSTLock);
  55771. if (result != MA_SUCCESS) {
  55772. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  55773. return result;
  55774. }
  55775. /* Create the job threads last to ensure the threads has access to valid data. */
  55776. for (iJobThread = 0; iJobThread < pResourceManager->config.jobThreadCount; iJobThread += 1) {
  55777. result = ma_thread_create(&pResourceManager->jobThreads[iJobThread], ma_thread_priority_normal, pResourceManager->config.jobThreadStackSize, ma_resource_manager_job_thread, pResourceManager, &pResourceManager->config.allocationCallbacks);
  55778. if (result != MA_SUCCESS) {
  55779. ma_mutex_uninit(&pResourceManager->dataBufferBSTLock);
  55780. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  55781. return result;
  55782. }
  55783. }
  55784. }
  55785. #else
  55786. {
  55787. /* Threading is disabled at compile time. We should never get here because validation checks should have already been performed. */
  55788. MA_ASSERT(MA_FALSE);
  55789. }
  55790. #endif
  55791. }
  55792. return MA_SUCCESS;
  55793. }
  55794. static void ma_resource_manager_delete_all_data_buffer_nodes(ma_resource_manager* pResourceManager)
  55795. {
  55796. MA_ASSERT(pResourceManager);
  55797. /* If everything was done properly, there shouldn't be any active data buffers. */
  55798. while (pResourceManager->pRootDataBufferNode != NULL) {
  55799. ma_resource_manager_data_buffer_node* pDataBufferNode = pResourceManager->pRootDataBufferNode;
  55800. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  55801. /* The data buffer has been removed from the BST, so now we need to free it's data. */
  55802. ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode);
  55803. }
  55804. }
  55805. MA_API void ma_resource_manager_uninit(ma_resource_manager* pResourceManager)
  55806. {
  55807. if (pResourceManager == NULL) {
  55808. return;
  55809. }
  55810. /*
  55811. Job threads need to be killed first. To do this we need to post a quit message to the message queue and then wait for the thread. The quit message will never be removed from the
  55812. queue which means it will never not be returned after being encounted for the first time which means all threads will eventually receive it.
  55813. */
  55814. ma_resource_manager_post_job_quit(pResourceManager);
  55815. /* Wait for every job to finish before continuing to ensure nothing is sill trying to access any of our objects below. */
  55816. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  55817. #ifndef MA_NO_THREADING
  55818. {
  55819. ma_uint32 iJobThread;
  55820. for (iJobThread = 0; iJobThread < pResourceManager->config.jobThreadCount; iJobThread += 1) {
  55821. ma_thread_wait(&pResourceManager->jobThreads[iJobThread]);
  55822. }
  55823. }
  55824. #else
  55825. {
  55826. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  55827. }
  55828. #endif
  55829. }
  55830. /* At this point the thread should have returned and no other thread should be accessing our data. We can now delete all data buffers. */
  55831. ma_resource_manager_delete_all_data_buffer_nodes(pResourceManager);
  55832. /* The job queue is no longer needed. */
  55833. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  55834. /* We're no longer doing anything with data buffers so the lock can now be uninitialized. */
  55835. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  55836. #ifndef MA_NO_THREADING
  55837. {
  55838. ma_mutex_uninit(&pResourceManager->dataBufferBSTLock);
  55839. }
  55840. #else
  55841. {
  55842. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  55843. }
  55844. #endif
  55845. }
  55846. ma_free(pResourceManager->config.ppCustomDecodingBackendVTables, &pResourceManager->config.allocationCallbacks);
  55847. if (pResourceManager->config.pLog == &pResourceManager->log) {
  55848. ma_log_uninit(&pResourceManager->log);
  55849. }
  55850. }
  55851. MA_API ma_log* ma_resource_manager_get_log(ma_resource_manager* pResourceManager)
  55852. {
  55853. if (pResourceManager == NULL) {
  55854. return NULL;
  55855. }
  55856. return pResourceManager->config.pLog;
  55857. }
  55858. MA_API ma_resource_manager_data_source_config ma_resource_manager_data_source_config_init(void)
  55859. {
  55860. ma_resource_manager_data_source_config config;
  55861. MA_ZERO_OBJECT(&config);
  55862. config.rangeBegInPCMFrames = MA_DATA_SOURCE_DEFAULT_RANGE_BEG;
  55863. config.rangeEndInPCMFrames = MA_DATA_SOURCE_DEFAULT_RANGE_END;
  55864. config.loopPointBegInPCMFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG;
  55865. config.loopPointEndInPCMFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END;
  55866. config.isLooping = MA_FALSE;
  55867. return config;
  55868. }
  55869. static ma_decoder_config ma_resource_manager__init_decoder_config(ma_resource_manager* pResourceManager)
  55870. {
  55871. ma_decoder_config config;
  55872. config = ma_decoder_config_init(pResourceManager->config.decodedFormat, pResourceManager->config.decodedChannels, pResourceManager->config.decodedSampleRate);
  55873. config.allocationCallbacks = pResourceManager->config.allocationCallbacks;
  55874. config.ppCustomBackendVTables = pResourceManager->config.ppCustomDecodingBackendVTables;
  55875. config.customBackendCount = pResourceManager->config.customDecodingBackendCount;
  55876. config.pCustomBackendUserData = pResourceManager->config.pCustomDecodingBackendUserData;
  55877. return config;
  55878. }
  55879. static ma_result ma_resource_manager__init_decoder(ma_resource_manager* pResourceManager, const char* pFilePath, const wchar_t* pFilePathW, ma_decoder* pDecoder)
  55880. {
  55881. ma_result result;
  55882. ma_decoder_config config;
  55883. MA_ASSERT(pResourceManager != NULL);
  55884. MA_ASSERT(pFilePath != NULL || pFilePathW != NULL);
  55885. MA_ASSERT(pDecoder != NULL);
  55886. config = ma_resource_manager__init_decoder_config(pResourceManager);
  55887. if (pFilePath != NULL) {
  55888. result = ma_decoder_init_vfs(pResourceManager->config.pVFS, pFilePath, &config, pDecoder);
  55889. if (result != MA_SUCCESS) {
  55890. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to load file \"%s\". %s.\n", pFilePath, ma_result_description(result));
  55891. return result;
  55892. }
  55893. } else {
  55894. result = ma_decoder_init_vfs_w(pResourceManager->config.pVFS, pFilePathW, &config, pDecoder);
  55895. if (result != MA_SUCCESS) {
  55896. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
  55897. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to load file \"%ls\". %s.\n", pFilePathW, ma_result_description(result));
  55898. #endif
  55899. return result;
  55900. }
  55901. }
  55902. return MA_SUCCESS;
  55903. }
  55904. static ma_bool32 ma_resource_manager_data_buffer_has_connector(ma_resource_manager_data_buffer* pDataBuffer)
  55905. {
  55906. return ma_atomic_bool32_get(&pDataBuffer->isConnectorInitialized);
  55907. }
  55908. static ma_data_source* ma_resource_manager_data_buffer_get_connector(ma_resource_manager_data_buffer* pDataBuffer)
  55909. {
  55910. if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE) {
  55911. return NULL; /* Connector not yet initialized. */
  55912. }
  55913. switch (pDataBuffer->pNode->data.type)
  55914. {
  55915. case ma_resource_manager_data_supply_type_encoded: return &pDataBuffer->connector.decoder;
  55916. case ma_resource_manager_data_supply_type_decoded: return &pDataBuffer->connector.buffer;
  55917. case ma_resource_manager_data_supply_type_decoded_paged: return &pDataBuffer->connector.pagedBuffer;
  55918. case ma_resource_manager_data_supply_type_unknown:
  55919. default:
  55920. {
  55921. ma_log_postf(ma_resource_manager_get_log(pDataBuffer->pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to retrieve data buffer connector. Unknown data supply type.\n");
  55922. return NULL;
  55923. };
  55924. };
  55925. }
  55926. static ma_result ma_resource_manager_data_buffer_init_connector(ma_resource_manager_data_buffer* pDataBuffer, const ma_resource_manager_data_source_config* pConfig, ma_async_notification* pInitNotification, ma_fence* pInitFence)
  55927. {
  55928. ma_result result;
  55929. MA_ASSERT(pDataBuffer != NULL);
  55930. MA_ASSERT(pConfig != NULL);
  55931. MA_ASSERT(ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE);
  55932. /* The underlying data buffer must be initialized before we'll be able to know how to initialize the backend. */
  55933. result = ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode);
  55934. if (result != MA_SUCCESS && result != MA_BUSY) {
  55935. return result; /* The data buffer is in an erroneous state. */
  55936. }
  55937. /*
  55938. We need to initialize either a ma_decoder or an ma_audio_buffer depending on whether or not the backing data is encoded or decoded. These act as the
  55939. "instance" to the data and are used to form the connection between underlying data buffer and the data source. If the data buffer is decoded, we can use
  55940. an ma_audio_buffer. This enables us to use memory mapping when mixing which saves us a bit of data movement overhead.
  55941. */
  55942. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  55943. {
  55944. case ma_resource_manager_data_supply_type_encoded: /* Connector is a decoder. */
  55945. {
  55946. ma_decoder_config config;
  55947. config = ma_resource_manager__init_decoder_config(pDataBuffer->pResourceManager);
  55948. result = ma_decoder_init_memory(pDataBuffer->pNode->data.backend.encoded.pData, pDataBuffer->pNode->data.backend.encoded.sizeInBytes, &config, &pDataBuffer->connector.decoder);
  55949. } break;
  55950. case ma_resource_manager_data_supply_type_decoded: /* Connector is an audio buffer. */
  55951. {
  55952. ma_audio_buffer_config config;
  55953. config = ma_audio_buffer_config_init(pDataBuffer->pNode->data.backend.decoded.format, pDataBuffer->pNode->data.backend.decoded.channels, pDataBuffer->pNode->data.backend.decoded.totalFrameCount, pDataBuffer->pNode->data.backend.decoded.pData, NULL);
  55954. result = ma_audio_buffer_init(&config, &pDataBuffer->connector.buffer);
  55955. } break;
  55956. case ma_resource_manager_data_supply_type_decoded_paged: /* Connector is a paged audio buffer. */
  55957. {
  55958. ma_paged_audio_buffer_config config;
  55959. config = ma_paged_audio_buffer_config_init(&pDataBuffer->pNode->data.backend.decodedPaged.data);
  55960. result = ma_paged_audio_buffer_init(&config, &pDataBuffer->connector.pagedBuffer);
  55961. } break;
  55962. case ma_resource_manager_data_supply_type_unknown:
  55963. default:
  55964. {
  55965. /* Unknown data supply type. Should never happen. Need to post an error here. */
  55966. return MA_INVALID_ARGS;
  55967. };
  55968. }
  55969. /*
  55970. Initialization of the connector is when we can fire the init notification. This will give the application access to
  55971. the format/channels/rate of the data source.
  55972. */
  55973. if (result == MA_SUCCESS) {
  55974. /*
  55975. The resource manager supports the ability to set the range and loop settings via a config at
  55976. initialization time. This results in an case where the ranges could be set explicitly via
  55977. ma_data_source_set_*() before we get to this point here. If this happens, we'll end up
  55978. hitting a case where we just override those settings which results in what feels like a bug.
  55979. To address this we only change the relevant properties if they're not equal to defaults. If
  55980. they're equal to defaults there's no need to change them anyway. If they're *not* set to the
  55981. default values, we can assume the user has set the range and loop settings via the config. If
  55982. they're doing their own calls to ma_data_source_set_*() in addition to setting them via the
  55983. config, that's entirely on the caller and any synchronization issue becomes their problem.
  55984. */
  55985. if (pConfig->rangeBegInPCMFrames != MA_DATA_SOURCE_DEFAULT_RANGE_BEG || pConfig->rangeEndInPCMFrames != MA_DATA_SOURCE_DEFAULT_RANGE_END) {
  55986. ma_data_source_set_range_in_pcm_frames(pDataBuffer, pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames);
  55987. }
  55988. if (pConfig->loopPointBegInPCMFrames != MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG || pConfig->loopPointEndInPCMFrames != MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END) {
  55989. ma_data_source_set_loop_point_in_pcm_frames(pDataBuffer, pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames);
  55990. }
  55991. if (pConfig->isLooping != MA_FALSE) {
  55992. ma_data_source_set_looping(pDataBuffer, pConfig->isLooping);
  55993. }
  55994. ma_atomic_bool32_set(&pDataBuffer->isConnectorInitialized, MA_TRUE);
  55995. if (pInitNotification != NULL) {
  55996. ma_async_notification_signal(pInitNotification);
  55997. }
  55998. if (pInitFence != NULL) {
  55999. ma_fence_release(pInitFence);
  56000. }
  56001. }
  56002. /* At this point the backend should be initialized. We do *not* want to set pDataSource->result here - that needs to be done at a higher level to ensure it's done as the last step. */
  56003. return result;
  56004. }
  56005. static ma_result ma_resource_manager_data_buffer_uninit_connector(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer* pDataBuffer)
  56006. {
  56007. MA_ASSERT(pResourceManager != NULL);
  56008. MA_ASSERT(pDataBuffer != NULL);
  56009. (void)pResourceManager;
  56010. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  56011. {
  56012. case ma_resource_manager_data_supply_type_encoded: /* Connector is a decoder. */
  56013. {
  56014. ma_decoder_uninit(&pDataBuffer->connector.decoder);
  56015. } break;
  56016. case ma_resource_manager_data_supply_type_decoded: /* Connector is an audio buffer. */
  56017. {
  56018. ma_audio_buffer_uninit(&pDataBuffer->connector.buffer);
  56019. } break;
  56020. case ma_resource_manager_data_supply_type_decoded_paged: /* Connector is a paged audio buffer. */
  56021. {
  56022. ma_paged_audio_buffer_uninit(&pDataBuffer->connector.pagedBuffer);
  56023. } break;
  56024. case ma_resource_manager_data_supply_type_unknown:
  56025. default:
  56026. {
  56027. /* Unknown data supply type. Should never happen. Need to post an error here. */
  56028. return MA_INVALID_ARGS;
  56029. };
  56030. }
  56031. return MA_SUCCESS;
  56032. }
  56033. static ma_uint32 ma_resource_manager_data_buffer_node_next_execution_order(ma_resource_manager_data_buffer_node* pDataBufferNode)
  56034. {
  56035. MA_ASSERT(pDataBufferNode != NULL);
  56036. return c89atomic_fetch_add_32(&pDataBufferNode->executionCounter, 1);
  56037. }
  56038. static ma_result ma_resource_manager_data_buffer_node_init_supply_encoded(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, const char* pFilePath, const wchar_t* pFilePathW)
  56039. {
  56040. ma_result result;
  56041. size_t dataSizeInBytes;
  56042. void* pData;
  56043. MA_ASSERT(pResourceManager != NULL);
  56044. MA_ASSERT(pDataBufferNode != NULL);
  56045. MA_ASSERT(pFilePath != NULL || pFilePathW != NULL);
  56046. result = ma_vfs_open_and_read_file_ex(pResourceManager->config.pVFS, pFilePath, pFilePathW, &pData, &dataSizeInBytes, &pResourceManager->config.allocationCallbacks);
  56047. if (result != MA_SUCCESS) {
  56048. if (pFilePath != NULL) {
  56049. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to load file \"%s\". %s.\n", pFilePath, ma_result_description(result));
  56050. } else {
  56051. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
  56052. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to load file \"%ls\". %s.\n", pFilePathW, ma_result_description(result));
  56053. #endif
  56054. }
  56055. return result;
  56056. }
  56057. pDataBufferNode->data.backend.encoded.pData = pData;
  56058. pDataBufferNode->data.backend.encoded.sizeInBytes = dataSizeInBytes;
  56059. ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_encoded); /* <-- Must be set last. */
  56060. return MA_SUCCESS;
  56061. }
  56062. static ma_result ma_resource_manager_data_buffer_node_init_supply_decoded(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, const char* pFilePath, const wchar_t* pFilePathW, ma_uint32 flags, ma_decoder** ppDecoder)
  56063. {
  56064. ma_result result = MA_SUCCESS;
  56065. ma_decoder* pDecoder;
  56066. ma_uint64 totalFrameCount;
  56067. MA_ASSERT(pResourceManager != NULL);
  56068. MA_ASSERT(pDataBufferNode != NULL);
  56069. MA_ASSERT(ppDecoder != NULL);
  56070. MA_ASSERT(pFilePath != NULL || pFilePathW != NULL);
  56071. *ppDecoder = NULL; /* For safety. */
  56072. pDecoder = (ma_decoder*)ma_malloc(sizeof(*pDecoder), &pResourceManager->config.allocationCallbacks);
  56073. if (pDecoder == NULL) {
  56074. return MA_OUT_OF_MEMORY;
  56075. }
  56076. result = ma_resource_manager__init_decoder(pResourceManager, pFilePath, pFilePathW, pDecoder);
  56077. if (result != MA_SUCCESS) {
  56078. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56079. return result;
  56080. }
  56081. /*
  56082. At this point we have the decoder and we now need to initialize the data supply. This will
  56083. be either a decoded buffer, or a decoded paged buffer. A regular buffer is just one big heap
  56084. allocated buffer, whereas a paged buffer is a linked list of paged-sized buffers. The latter
  56085. is used when the length of a sound is unknown until a full decode has been performed.
  56086. */
  56087. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH) == 0) {
  56088. result = ma_decoder_get_length_in_pcm_frames(pDecoder, &totalFrameCount);
  56089. if (result != MA_SUCCESS) {
  56090. return result;
  56091. }
  56092. } else {
  56093. totalFrameCount = 0;
  56094. }
  56095. if (totalFrameCount > 0) {
  56096. /* It's a known length. The data supply is a regular decoded buffer. */
  56097. ma_uint64 dataSizeInBytes;
  56098. void* pData;
  56099. dataSizeInBytes = totalFrameCount * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels);
  56100. if (dataSizeInBytes > MA_SIZE_MAX) {
  56101. ma_decoder_uninit(pDecoder);
  56102. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56103. return MA_TOO_BIG;
  56104. }
  56105. pData = ma_malloc((size_t)dataSizeInBytes, &pResourceManager->config.allocationCallbacks);
  56106. if (pData == NULL) {
  56107. ma_decoder_uninit(pDecoder);
  56108. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56109. return MA_OUT_OF_MEMORY;
  56110. }
  56111. /* The buffer needs to be initialized to silence in case the caller reads from it. */
  56112. ma_silence_pcm_frames(pData, totalFrameCount, pDecoder->outputFormat, pDecoder->outputChannels);
  56113. /* Data has been allocated and the data supply can now be initialized. */
  56114. pDataBufferNode->data.backend.decoded.pData = pData;
  56115. pDataBufferNode->data.backend.decoded.totalFrameCount = totalFrameCount;
  56116. pDataBufferNode->data.backend.decoded.format = pDecoder->outputFormat;
  56117. pDataBufferNode->data.backend.decoded.channels = pDecoder->outputChannels;
  56118. pDataBufferNode->data.backend.decoded.sampleRate = pDecoder->outputSampleRate;
  56119. pDataBufferNode->data.backend.decoded.decodedFrameCount = 0;
  56120. ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_decoded); /* <-- Must be set last. */
  56121. } else {
  56122. /*
  56123. It's an unknown length. The data supply is a paged decoded buffer. Setting this up is
  56124. actually easier than the non-paged decoded buffer because we just need to initialize
  56125. a ma_paged_audio_buffer object.
  56126. */
  56127. result = ma_paged_audio_buffer_data_init(pDecoder->outputFormat, pDecoder->outputChannels, &pDataBufferNode->data.backend.decodedPaged.data);
  56128. if (result != MA_SUCCESS) {
  56129. ma_decoder_uninit(pDecoder);
  56130. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56131. return result;
  56132. }
  56133. pDataBufferNode->data.backend.decodedPaged.sampleRate = pDecoder->outputSampleRate;
  56134. pDataBufferNode->data.backend.decodedPaged.decodedFrameCount = 0;
  56135. ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_decoded_paged); /* <-- Must be set last. */
  56136. }
  56137. *ppDecoder = pDecoder;
  56138. return MA_SUCCESS;
  56139. }
  56140. static ma_result ma_resource_manager_data_buffer_node_decode_next_page(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, ma_decoder* pDecoder)
  56141. {
  56142. ma_result result = MA_SUCCESS;
  56143. ma_uint64 pageSizeInFrames;
  56144. ma_uint64 framesToTryReading;
  56145. ma_uint64 framesRead;
  56146. MA_ASSERT(pResourceManager != NULL);
  56147. MA_ASSERT(pDataBufferNode != NULL);
  56148. MA_ASSERT(pDecoder != NULL);
  56149. /* We need to know the size of a page in frames to know how many frames to decode. */
  56150. pageSizeInFrames = MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS * (pDecoder->outputSampleRate/1000);
  56151. framesToTryReading = pageSizeInFrames;
  56152. /*
  56153. Here is where we do the decoding of the next page. We'll run a slightly different path depending
  56154. on whether or not we're using a flat or paged buffer because the allocation of the page differs
  56155. between the two. For a flat buffer it's an offset to an already-allocated buffer. For a paged
  56156. buffer, we need to allocate a new page and attach it to the linked list.
  56157. */
  56158. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode))
  56159. {
  56160. case ma_resource_manager_data_supply_type_decoded:
  56161. {
  56162. /* The destination buffer is an offset to the existing buffer. Don't read more than we originally retrieved when we first initialized the decoder. */
  56163. void* pDst;
  56164. ma_uint64 framesRemaining = pDataBufferNode->data.backend.decoded.totalFrameCount - pDataBufferNode->data.backend.decoded.decodedFrameCount;
  56165. if (framesToTryReading > framesRemaining) {
  56166. framesToTryReading = framesRemaining;
  56167. }
  56168. if (framesToTryReading > 0) {
  56169. pDst = ma_offset_ptr(
  56170. pDataBufferNode->data.backend.decoded.pData,
  56171. pDataBufferNode->data.backend.decoded.decodedFrameCount * ma_get_bytes_per_frame(pDataBufferNode->data.backend.decoded.format, pDataBufferNode->data.backend.decoded.channels)
  56172. );
  56173. MA_ASSERT(pDst != NULL);
  56174. result = ma_decoder_read_pcm_frames(pDecoder, pDst, framesToTryReading, &framesRead);
  56175. if (framesRead > 0) {
  56176. pDataBufferNode->data.backend.decoded.decodedFrameCount += framesRead;
  56177. }
  56178. } else {
  56179. framesRead = 0;
  56180. }
  56181. } break;
  56182. case ma_resource_manager_data_supply_type_decoded_paged:
  56183. {
  56184. /* The destination buffer is a freshly allocated page. */
  56185. ma_paged_audio_buffer_page* pPage;
  56186. result = ma_paged_audio_buffer_data_allocate_page(&pDataBufferNode->data.backend.decodedPaged.data, framesToTryReading, NULL, &pResourceManager->config.allocationCallbacks, &pPage);
  56187. if (result != MA_SUCCESS) {
  56188. return result;
  56189. }
  56190. result = ma_decoder_read_pcm_frames(pDecoder, pPage->pAudioData, framesToTryReading, &framesRead);
  56191. if (framesRead > 0) {
  56192. pPage->sizeInFrames = framesRead;
  56193. result = ma_paged_audio_buffer_data_append_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage);
  56194. if (result == MA_SUCCESS) {
  56195. pDataBufferNode->data.backend.decodedPaged.decodedFrameCount += framesRead;
  56196. } else {
  56197. /* Failed to append the page. Just abort and set the status to MA_AT_END. */
  56198. ma_paged_audio_buffer_data_free_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage, &pResourceManager->config.allocationCallbacks);
  56199. result = MA_AT_END;
  56200. }
  56201. } else {
  56202. /* No frames were read. Free the page and just set the status to MA_AT_END. */
  56203. ma_paged_audio_buffer_data_free_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage, &pResourceManager->config.allocationCallbacks);
  56204. result = MA_AT_END;
  56205. }
  56206. } break;
  56207. case ma_resource_manager_data_supply_type_encoded:
  56208. case ma_resource_manager_data_supply_type_unknown:
  56209. default:
  56210. {
  56211. /* Unexpected data supply type. */
  56212. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Unexpected data supply type (%d) when decoding page.", ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode));
  56213. return MA_ERROR;
  56214. };
  56215. }
  56216. if (result == MA_SUCCESS && framesRead == 0) {
  56217. result = MA_AT_END;
  56218. }
  56219. return result;
  56220. }
  56221. static ma_result ma_resource_manager_data_buffer_node_acquire_critical_section(ma_resource_manager* pResourceManager, const char* pFilePath, const wchar_t* pFilePathW, ma_uint32 hashedName32, ma_uint32 flags, const ma_resource_manager_data_supply* pExistingData, ma_fence* pInitFence, ma_fence* pDoneFence, ma_resource_manager_inline_notification* pInitNotification, ma_resource_manager_data_buffer_node** ppDataBufferNode)
  56222. {
  56223. ma_result result = MA_SUCCESS;
  56224. ma_resource_manager_data_buffer_node* pDataBufferNode = NULL;
  56225. ma_resource_manager_data_buffer_node* pInsertPoint;
  56226. if (ppDataBufferNode != NULL) {
  56227. *ppDataBufferNode = NULL;
  56228. }
  56229. result = ma_resource_manager_data_buffer_node_insert_point(pResourceManager, hashedName32, &pInsertPoint);
  56230. if (result == MA_ALREADY_EXISTS) {
  56231. /* The node already exists. We just need to increment the reference count. */
  56232. pDataBufferNode = pInsertPoint;
  56233. result = ma_resource_manager_data_buffer_node_increment_ref(pResourceManager, pDataBufferNode, NULL);
  56234. if (result != MA_SUCCESS) {
  56235. return result; /* Should never happen. Failed to increment the reference count. */
  56236. }
  56237. result = MA_ALREADY_EXISTS;
  56238. goto done;
  56239. } else {
  56240. /*
  56241. The node does not already exist. We need to post a LOAD_DATA_BUFFER_NODE job here. This
  56242. needs to be done inside the critical section to ensure an uninitialization of the node
  56243. does not occur before initialization on another thread.
  56244. */
  56245. pDataBufferNode = (ma_resource_manager_data_buffer_node*)ma_malloc(sizeof(*pDataBufferNode), &pResourceManager->config.allocationCallbacks);
  56246. if (pDataBufferNode == NULL) {
  56247. return MA_OUT_OF_MEMORY;
  56248. }
  56249. MA_ZERO_OBJECT(pDataBufferNode);
  56250. pDataBufferNode->hashedName32 = hashedName32;
  56251. pDataBufferNode->refCount = 1; /* Always set to 1 by default (this is our first reference). */
  56252. if (pExistingData == NULL) {
  56253. pDataBufferNode->data.type = ma_resource_manager_data_supply_type_unknown; /* <-- We won't know this until we start decoding. */
  56254. pDataBufferNode->result = MA_BUSY; /* Must be set to MA_BUSY before we leave the critical section, so might as well do it now. */
  56255. pDataBufferNode->isDataOwnedByResourceManager = MA_TRUE;
  56256. } else {
  56257. pDataBufferNode->data = *pExistingData;
  56258. pDataBufferNode->result = MA_SUCCESS; /* Not loading asynchronously, so just set the status */
  56259. pDataBufferNode->isDataOwnedByResourceManager = MA_FALSE;
  56260. }
  56261. result = ma_resource_manager_data_buffer_node_insert_at(pResourceManager, pDataBufferNode, pInsertPoint);
  56262. if (result != MA_SUCCESS) {
  56263. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  56264. return result; /* Should never happen. Failed to insert the data buffer into the BST. */
  56265. }
  56266. /*
  56267. Here is where we'll post the job, but only if we're loading asynchronously. If we're
  56268. loading synchronously we'll defer loading to a later stage, outside of the critical
  56269. section.
  56270. */
  56271. if (pDataBufferNode->isDataOwnedByResourceManager && (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0) {
  56272. /* Loading asynchronously. Post the job. */
  56273. ma_job job;
  56274. char* pFilePathCopy = NULL;
  56275. wchar_t* pFilePathWCopy = NULL;
  56276. /* We need a copy of the file path. We should probably make this more efficient, but for now we'll do a transient memory allocation. */
  56277. if (pFilePath != NULL) {
  56278. pFilePathCopy = ma_copy_string(pFilePath, &pResourceManager->config.allocationCallbacks);
  56279. } else {
  56280. pFilePathWCopy = ma_copy_string_w(pFilePathW, &pResourceManager->config.allocationCallbacks);
  56281. }
  56282. if (pFilePathCopy == NULL && pFilePathWCopy == NULL) {
  56283. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  56284. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  56285. return MA_OUT_OF_MEMORY;
  56286. }
  56287. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56288. ma_resource_manager_inline_notification_init(pResourceManager, pInitNotification);
  56289. }
  56290. /* Acquire init and done fences before posting the job. These will be unacquired by the job thread. */
  56291. if (pInitFence != NULL) { ma_fence_acquire(pInitFence); }
  56292. if (pDoneFence != NULL) { ma_fence_acquire(pDoneFence); }
  56293. /* We now have everything we need to post the job to the job thread. */
  56294. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE);
  56295. job.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode);
  56296. job.data.resourceManager.loadDataBufferNode.pResourceManager = pResourceManager;
  56297. job.data.resourceManager.loadDataBufferNode.pDataBufferNode = pDataBufferNode;
  56298. job.data.resourceManager.loadDataBufferNode.pFilePath = pFilePathCopy;
  56299. job.data.resourceManager.loadDataBufferNode.pFilePathW = pFilePathWCopy;
  56300. job.data.resourceManager.loadDataBufferNode.flags = flags;
  56301. job.data.resourceManager.loadDataBufferNode.pInitNotification = ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) ? pInitNotification : NULL;
  56302. job.data.resourceManager.loadDataBufferNode.pDoneNotification = NULL;
  56303. job.data.resourceManager.loadDataBufferNode.pInitFence = pInitFence;
  56304. job.data.resourceManager.loadDataBufferNode.pDoneFence = pDoneFence;
  56305. result = ma_resource_manager_post_job(pResourceManager, &job);
  56306. if (result != MA_SUCCESS) {
  56307. /* Failed to post job. Probably ran out of memory. */
  56308. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to post MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE job. %s.\n", ma_result_description(result));
  56309. /*
  56310. Fences were acquired before posting the job, but since the job was not able to
  56311. be posted, we need to make sure we release them so nothing gets stuck waiting.
  56312. */
  56313. if (pInitFence != NULL) { ma_fence_release(pInitFence); }
  56314. if (pDoneFence != NULL) { ma_fence_release(pDoneFence); }
  56315. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56316. ma_resource_manager_inline_notification_init(pResourceManager, pInitNotification);
  56317. }
  56318. ma_free(pFilePathCopy, &pResourceManager->config.allocationCallbacks);
  56319. ma_free(pFilePathWCopy, &pResourceManager->config.allocationCallbacks);
  56320. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  56321. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  56322. return result;
  56323. }
  56324. }
  56325. }
  56326. done:
  56327. if (ppDataBufferNode != NULL) {
  56328. *ppDataBufferNode = pDataBufferNode;
  56329. }
  56330. return result;
  56331. }
  56332. static ma_result ma_resource_manager_data_buffer_node_acquire(ma_resource_manager* pResourceManager, const char* pFilePath, const wchar_t* pFilePathW, ma_uint32 hashedName32, ma_uint32 flags, const ma_resource_manager_data_supply* pExistingData, ma_fence* pInitFence, ma_fence* pDoneFence, ma_resource_manager_data_buffer_node** ppDataBufferNode)
  56333. {
  56334. ma_result result = MA_SUCCESS;
  56335. ma_bool32 nodeAlreadyExists = MA_FALSE;
  56336. ma_resource_manager_data_buffer_node* pDataBufferNode = NULL;
  56337. ma_resource_manager_inline_notification initNotification; /* Used when the WAIT_INIT flag is set. */
  56338. if (ppDataBufferNode != NULL) {
  56339. *ppDataBufferNode = NULL; /* Safety. */
  56340. }
  56341. if (pResourceManager == NULL || (pFilePath == NULL && pFilePathW == NULL && hashedName32 == 0)) {
  56342. return MA_INVALID_ARGS;
  56343. }
  56344. /* If we're specifying existing data, it must be valid. */
  56345. if (pExistingData != NULL && pExistingData->type == ma_resource_manager_data_supply_type_unknown) {
  56346. return MA_INVALID_ARGS;
  56347. }
  56348. /* If we don't support threading, remove the ASYNC flag to make the rest of this a bit simpler. */
  56349. if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) {
  56350. flags &= ~MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC;
  56351. }
  56352. if (hashedName32 == 0) {
  56353. if (pFilePath != NULL) {
  56354. hashedName32 = ma_hash_string_32(pFilePath);
  56355. } else {
  56356. hashedName32 = ma_hash_string_w_32(pFilePathW);
  56357. }
  56358. }
  56359. /*
  56360. Here is where we either increment the node's reference count or allocate a new one and add it
  56361. to the BST. When allocating a new node, we need to make sure the LOAD_DATA_BUFFER_NODE job is
  56362. posted inside the critical section just in case the caller immediately uninitializes the node
  56363. as this will ensure the FREE_DATA_BUFFER_NODE job is given an execution order such that the
  56364. node is not uninitialized before initialization.
  56365. */
  56366. ma_resource_manager_data_buffer_bst_lock(pResourceManager);
  56367. {
  56368. result = ma_resource_manager_data_buffer_node_acquire_critical_section(pResourceManager, pFilePath, pFilePathW, hashedName32, flags, pExistingData, pInitFence, pDoneFence, &initNotification, &pDataBufferNode);
  56369. }
  56370. ma_resource_manager_data_buffer_bst_unlock(pResourceManager);
  56371. if (result == MA_ALREADY_EXISTS) {
  56372. nodeAlreadyExists = MA_TRUE;
  56373. result = MA_SUCCESS;
  56374. } else {
  56375. if (result != MA_SUCCESS) {
  56376. return result;
  56377. }
  56378. }
  56379. /*
  56380. If we're loading synchronously, we'll need to load everything now. When loading asynchronously,
  56381. a job will have been posted inside the BST critical section so that an uninitialization can be
  56382. allocated an appropriate execution order thereby preventing it from being uninitialized before
  56383. the node is initialized by the decoding thread(s).
  56384. */
  56385. if (nodeAlreadyExists == MA_FALSE) { /* Don't need to try loading anything if the node already exists. */
  56386. if (pFilePath == NULL && pFilePathW == NULL) {
  56387. /*
  56388. If this path is hit, it means a buffer is being copied (i.e. initialized from only the
  56389. hashed name), but that node has been freed in the meantime, probably from some other
  56390. thread. This is an invalid operation.
  56391. */
  56392. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Cloning data buffer node failed because the source node was released. The source node must remain valid until the cloning has completed.\n");
  56393. result = MA_INVALID_OPERATION;
  56394. goto done;
  56395. }
  56396. if (pDataBufferNode->isDataOwnedByResourceManager) {
  56397. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) == 0) {
  56398. /* Loading synchronously. Load the sound in it's entirety here. */
  56399. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE) == 0) {
  56400. /* No decoding. This is the simple case - just store the file contents in memory. */
  56401. result = ma_resource_manager_data_buffer_node_init_supply_encoded(pResourceManager, pDataBufferNode, pFilePath, pFilePathW);
  56402. if (result != MA_SUCCESS) {
  56403. goto done;
  56404. }
  56405. } else {
  56406. /* Decoding. We do this the same way as we do when loading asynchronously. */
  56407. ma_decoder* pDecoder;
  56408. result = ma_resource_manager_data_buffer_node_init_supply_decoded(pResourceManager, pDataBufferNode, pFilePath, pFilePathW, flags, &pDecoder);
  56409. if (result != MA_SUCCESS) {
  56410. goto done;
  56411. }
  56412. /* We have the decoder, now decode page by page just like we do when loading asynchronously. */
  56413. for (;;) {
  56414. /* Decode next page. */
  56415. result = ma_resource_manager_data_buffer_node_decode_next_page(pResourceManager, pDataBufferNode, pDecoder);
  56416. if (result != MA_SUCCESS) {
  56417. break; /* Will return MA_AT_END when the last page has been decoded. */
  56418. }
  56419. }
  56420. /* Reaching the end needs to be considered successful. */
  56421. if (result == MA_AT_END) {
  56422. result = MA_SUCCESS;
  56423. }
  56424. /*
  56425. At this point the data buffer is either fully decoded or some error occurred. Either
  56426. way, the decoder is no longer necessary.
  56427. */
  56428. ma_decoder_uninit(pDecoder);
  56429. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56430. }
  56431. /* Getting here means we were successful. Make sure the status of the node is updated accordingly. */
  56432. c89atomic_exchange_i32(&pDataBufferNode->result, result);
  56433. } else {
  56434. /* Loading asynchronously. We may need to wait for initialization. */
  56435. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56436. ma_resource_manager_inline_notification_wait(&initNotification);
  56437. }
  56438. }
  56439. } else {
  56440. /* The data is not managed by the resource manager so there's nothing else to do. */
  56441. MA_ASSERT(pExistingData != NULL);
  56442. }
  56443. }
  56444. done:
  56445. /* If we failed to initialize the data buffer we need to free it. */
  56446. if (result != MA_SUCCESS) {
  56447. if (nodeAlreadyExists == MA_FALSE) {
  56448. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  56449. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  56450. }
  56451. }
  56452. /*
  56453. The init notification needs to be uninitialized. This will be used if the node does not already
  56454. exist, and we've specified ASYNC | WAIT_INIT.
  56455. */
  56456. if (nodeAlreadyExists == MA_FALSE && pDataBufferNode->isDataOwnedByResourceManager && (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0) {
  56457. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56458. ma_resource_manager_inline_notification_uninit(&initNotification);
  56459. }
  56460. }
  56461. if (ppDataBufferNode != NULL) {
  56462. *ppDataBufferNode = pDataBufferNode;
  56463. }
  56464. return result;
  56465. }
  56466. static ma_result ma_resource_manager_data_buffer_node_unacquire(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode, const char* pName, const wchar_t* pNameW)
  56467. {
  56468. ma_result result = MA_SUCCESS;
  56469. ma_uint32 refCount = 0xFFFFFFFF; /* The new reference count of the node after decrementing. Initialize to non-0 to be safe we don't fall into the freeing path. */
  56470. ma_uint32 hashedName32 = 0;
  56471. if (pResourceManager == NULL) {
  56472. return MA_INVALID_ARGS;
  56473. }
  56474. if (pDataBufferNode == NULL) {
  56475. if (pName == NULL && pNameW == NULL) {
  56476. return MA_INVALID_ARGS;
  56477. }
  56478. if (pName != NULL) {
  56479. hashedName32 = ma_hash_string_32(pName);
  56480. } else {
  56481. hashedName32 = ma_hash_string_w_32(pNameW);
  56482. }
  56483. }
  56484. /*
  56485. The first thing to do is decrement the reference counter of the node. Then, if the reference
  56486. count is zero, we need to free the node. If the node is still in the process of loading, we'll
  56487. need to post a job to the job queue to free the node. Otherwise we'll just do it here.
  56488. */
  56489. ma_resource_manager_data_buffer_bst_lock(pResourceManager);
  56490. {
  56491. /* Might need to find the node. Must be done inside the critical section. */
  56492. if (pDataBufferNode == NULL) {
  56493. result = ma_resource_manager_data_buffer_node_search(pResourceManager, hashedName32, &pDataBufferNode);
  56494. if (result != MA_SUCCESS) {
  56495. goto stage2; /* Couldn't find the node. */
  56496. }
  56497. }
  56498. result = ma_resource_manager_data_buffer_node_decrement_ref(pResourceManager, pDataBufferNode, &refCount);
  56499. if (result != MA_SUCCESS) {
  56500. goto stage2; /* Should never happen. */
  56501. }
  56502. if (refCount == 0) {
  56503. result = ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  56504. if (result != MA_SUCCESS) {
  56505. goto stage2; /* An error occurred when trying to remove the data buffer. This should never happen. */
  56506. }
  56507. }
  56508. }
  56509. ma_resource_manager_data_buffer_bst_unlock(pResourceManager);
  56510. stage2:
  56511. if (result != MA_SUCCESS) {
  56512. return result;
  56513. }
  56514. /*
  56515. Here is where we need to free the node. We don't want to do this inside the critical section
  56516. above because we want to keep that as small as possible for multi-threaded efficiency.
  56517. */
  56518. if (refCount == 0) {
  56519. if (ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_BUSY) {
  56520. /* The sound is still loading. We need to delay the freeing of the node to a safe time. */
  56521. ma_job job;
  56522. /* We need to mark the node as unavailable for the sake of the resource manager worker threads. */
  56523. c89atomic_exchange_i32(&pDataBufferNode->result, MA_UNAVAILABLE);
  56524. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE);
  56525. job.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode);
  56526. job.data.resourceManager.freeDataBufferNode.pResourceManager = pResourceManager;
  56527. job.data.resourceManager.freeDataBufferNode.pDataBufferNode = pDataBufferNode;
  56528. result = ma_resource_manager_post_job(pResourceManager, &job);
  56529. if (result != MA_SUCCESS) {
  56530. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to post MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE job. %s.\n", ma_result_description(result));
  56531. return result;
  56532. }
  56533. /* If we don't support threading, process the job queue here. */
  56534. if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) {
  56535. while (ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_BUSY) {
  56536. result = ma_resource_manager_process_next_job(pResourceManager);
  56537. if (result == MA_NO_DATA_AVAILABLE || result == MA_CANCELLED) {
  56538. result = MA_SUCCESS;
  56539. break;
  56540. }
  56541. }
  56542. } else {
  56543. /* Threading is enabled. The job queue will deal with the rest of the cleanup from here. */
  56544. }
  56545. } else {
  56546. /* The sound isn't loading so we can just free the node here. */
  56547. ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode);
  56548. }
  56549. }
  56550. return result;
  56551. }
  56552. static ma_uint32 ma_resource_manager_data_buffer_next_execution_order(ma_resource_manager_data_buffer* pDataBuffer)
  56553. {
  56554. MA_ASSERT(pDataBuffer != NULL);
  56555. return c89atomic_fetch_add_32(&pDataBuffer->executionCounter, 1);
  56556. }
  56557. static ma_result ma_resource_manager_data_buffer_cb__read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  56558. {
  56559. return ma_resource_manager_data_buffer_read_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pFramesOut, frameCount, pFramesRead);
  56560. }
  56561. static ma_result ma_resource_manager_data_buffer_cb__seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
  56562. {
  56563. return ma_resource_manager_data_buffer_seek_to_pcm_frame((ma_resource_manager_data_buffer*)pDataSource, frameIndex);
  56564. }
  56565. static ma_result ma_resource_manager_data_buffer_cb__get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  56566. {
  56567. return ma_resource_manager_data_buffer_get_data_format((ma_resource_manager_data_buffer*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  56568. }
  56569. static ma_result ma_resource_manager_data_buffer_cb__get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
  56570. {
  56571. return ma_resource_manager_data_buffer_get_cursor_in_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pCursor);
  56572. }
  56573. static ma_result ma_resource_manager_data_buffer_cb__get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
  56574. {
  56575. return ma_resource_manager_data_buffer_get_length_in_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pLength);
  56576. }
  56577. static ma_result ma_resource_manager_data_buffer_cb__set_looping(ma_data_source* pDataSource, ma_bool32 isLooping)
  56578. {
  56579. ma_resource_manager_data_buffer* pDataBuffer = (ma_resource_manager_data_buffer*)pDataSource;
  56580. MA_ASSERT(pDataBuffer != NULL);
  56581. c89atomic_exchange_32(&pDataBuffer->isLooping, isLooping);
  56582. /* The looping state needs to be set on the connector as well or else looping won't work when we read audio data. */
  56583. ma_data_source_set_looping(ma_resource_manager_data_buffer_get_connector(pDataBuffer), isLooping);
  56584. return MA_SUCCESS;
  56585. }
  56586. static ma_data_source_vtable g_ma_resource_manager_data_buffer_vtable =
  56587. {
  56588. ma_resource_manager_data_buffer_cb__read_pcm_frames,
  56589. ma_resource_manager_data_buffer_cb__seek_to_pcm_frame,
  56590. ma_resource_manager_data_buffer_cb__get_data_format,
  56591. ma_resource_manager_data_buffer_cb__get_cursor_in_pcm_frames,
  56592. ma_resource_manager_data_buffer_cb__get_length_in_pcm_frames,
  56593. ma_resource_manager_data_buffer_cb__set_looping,
  56594. 0
  56595. };
  56596. static ma_result ma_resource_manager_data_buffer_init_ex_internal(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_uint32 hashedName32, ma_resource_manager_data_buffer* pDataBuffer)
  56597. {
  56598. ma_result result = MA_SUCCESS;
  56599. ma_resource_manager_data_buffer_node* pDataBufferNode;
  56600. ma_data_source_config dataSourceConfig;
  56601. ma_bool32 async;
  56602. ma_uint32 flags;
  56603. ma_resource_manager_pipeline_notifications notifications;
  56604. if (pDataBuffer == NULL) {
  56605. if (pConfig != NULL && pConfig->pNotifications != NULL) {
  56606. ma_resource_manager_pipeline_notifications_signal_all_notifications(pConfig->pNotifications);
  56607. }
  56608. return MA_INVALID_ARGS;
  56609. }
  56610. MA_ZERO_OBJECT(pDataBuffer);
  56611. if (pConfig == NULL) {
  56612. return MA_INVALID_ARGS;
  56613. }
  56614. if (pConfig->pNotifications != NULL) {
  56615. notifications = *pConfig->pNotifications; /* From here on out we should be referencing `notifications` instead of `pNotifications`. Set this to NULL to catch errors at testing time. */
  56616. } else {
  56617. MA_ZERO_OBJECT(&notifications);
  56618. }
  56619. /* For safety, always remove the ASYNC flag if threading is disabled on the resource manager. */
  56620. flags = pConfig->flags;
  56621. if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) {
  56622. flags &= ~MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC;
  56623. }
  56624. async = (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0;
  56625. /*
  56626. Fences need to be acquired before doing anything. These must be aquired and released outside of
  56627. the node to ensure there's no holes where ma_fence_wait() could prematurely return before the
  56628. data buffer has completed initialization.
  56629. When loading asynchronously, the node acquisition routine below will acquire the fences on this
  56630. thread and then release them on the async thread when the operation is complete.
  56631. These fences are always released at the "done" tag at the end of this function. They'll be
  56632. acquired a second if loading asynchronously. This double acquisition system is just done to
  56633. simplify code maintanence.
  56634. */
  56635. ma_resource_manager_pipeline_notifications_acquire_all_fences(&notifications);
  56636. {
  56637. /* We first need to acquire a node. If ASYNC is not set, this will not return until the entire sound has been loaded. */
  56638. result = ma_resource_manager_data_buffer_node_acquire(pResourceManager, pConfig->pFilePath, pConfig->pFilePathW, hashedName32, flags, NULL, notifications.init.pFence, notifications.done.pFence, &pDataBufferNode);
  56639. if (result != MA_SUCCESS) {
  56640. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  56641. goto done;
  56642. }
  56643. dataSourceConfig = ma_data_source_config_init();
  56644. dataSourceConfig.vtable = &g_ma_resource_manager_data_buffer_vtable;
  56645. result = ma_data_source_init(&dataSourceConfig, &pDataBuffer->ds);
  56646. if (result != MA_SUCCESS) {
  56647. ma_resource_manager_data_buffer_node_unacquire(pResourceManager, pDataBufferNode, NULL, NULL);
  56648. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  56649. goto done;
  56650. }
  56651. pDataBuffer->pResourceManager = pResourceManager;
  56652. pDataBuffer->pNode = pDataBufferNode;
  56653. pDataBuffer->flags = flags;
  56654. pDataBuffer->result = MA_BUSY; /* Always default to MA_BUSY for safety. It'll be overwritten when loading completes or an error occurs. */
  56655. /* If we're loading asynchronously we need to post a job to the job queue to initialize the connector. */
  56656. if (async == MA_FALSE || ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_SUCCESS) {
  56657. /* Loading synchronously or the data has already been fully loaded. We can just initialize the connector from here without a job. */
  56658. result = ma_resource_manager_data_buffer_init_connector(pDataBuffer, pConfig, NULL, NULL);
  56659. c89atomic_exchange_i32(&pDataBuffer->result, result);
  56660. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  56661. goto done;
  56662. } else {
  56663. /* The node's data supply isn't initialized yet. The caller has requested that we load asynchronously so we need to post a job to do this. */
  56664. ma_job job;
  56665. ma_resource_manager_inline_notification initNotification; /* Used when the WAIT_INIT flag is set. */
  56666. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56667. ma_resource_manager_inline_notification_init(pResourceManager, &initNotification);
  56668. }
  56669. /*
  56670. The status of the data buffer needs to be set to MA_BUSY before posting the job so that the
  56671. worker thread is aware of it's busy state. If the LOAD_DATA_BUFFER job sees a status other
  56672. than MA_BUSY, it'll assume an error and fall through to an early exit.
  56673. */
  56674. c89atomic_exchange_i32(&pDataBuffer->result, MA_BUSY);
  56675. /* Acquire fences a second time. These will be released by the async thread. */
  56676. ma_resource_manager_pipeline_notifications_acquire_all_fences(&notifications);
  56677. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER);
  56678. job.order = ma_resource_manager_data_buffer_next_execution_order(pDataBuffer);
  56679. job.data.resourceManager.loadDataBuffer.pDataBuffer = pDataBuffer;
  56680. job.data.resourceManager.loadDataBuffer.pInitNotification = ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) ? &initNotification : notifications.init.pNotification;
  56681. job.data.resourceManager.loadDataBuffer.pDoneNotification = notifications.done.pNotification;
  56682. job.data.resourceManager.loadDataBuffer.pInitFence = notifications.init.pFence;
  56683. job.data.resourceManager.loadDataBuffer.pDoneFence = notifications.done.pFence;
  56684. job.data.resourceManager.loadDataBuffer.rangeBegInPCMFrames = pConfig->rangeBegInPCMFrames;
  56685. job.data.resourceManager.loadDataBuffer.rangeEndInPCMFrames = pConfig->rangeEndInPCMFrames;
  56686. job.data.resourceManager.loadDataBuffer.loopPointBegInPCMFrames = pConfig->loopPointBegInPCMFrames;
  56687. job.data.resourceManager.loadDataBuffer.loopPointEndInPCMFrames = pConfig->loopPointEndInPCMFrames;
  56688. job.data.resourceManager.loadDataBuffer.isLooping = pConfig->isLooping;
  56689. result = ma_resource_manager_post_job(pResourceManager, &job);
  56690. if (result != MA_SUCCESS) {
  56691. /* We failed to post the job. Most likely there isn't enough room in the queue's buffer. */
  56692. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to post MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER job. %s.\n", ma_result_description(result));
  56693. c89atomic_exchange_i32(&pDataBuffer->result, result);
  56694. /* Release the fences after the result has been set on the data buffer. */
  56695. ma_resource_manager_pipeline_notifications_release_all_fences(&notifications);
  56696. } else {
  56697. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56698. ma_resource_manager_inline_notification_wait(&initNotification);
  56699. if (notifications.init.pNotification != NULL) {
  56700. ma_async_notification_signal(notifications.init.pNotification);
  56701. }
  56702. /* NOTE: Do not release the init fence here. It will have been done by the job. */
  56703. /* Make sure we return an error if initialization failed on the async thread. */
  56704. result = ma_resource_manager_data_buffer_result(pDataBuffer);
  56705. if (result == MA_BUSY) {
  56706. result = MA_SUCCESS;
  56707. }
  56708. }
  56709. }
  56710. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56711. ma_resource_manager_inline_notification_uninit(&initNotification);
  56712. }
  56713. }
  56714. if (result != MA_SUCCESS) {
  56715. ma_resource_manager_data_buffer_node_unacquire(pResourceManager, pDataBufferNode, NULL, NULL);
  56716. goto done;
  56717. }
  56718. }
  56719. done:
  56720. if (result == MA_SUCCESS) {
  56721. if (pConfig->initialSeekPointInPCMFrames > 0) {
  56722. ma_resource_manager_data_buffer_seek_to_pcm_frame(pDataBuffer, pConfig->initialSeekPointInPCMFrames);
  56723. }
  56724. }
  56725. ma_resource_manager_pipeline_notifications_release_all_fences(&notifications);
  56726. return result;
  56727. }
  56728. MA_API ma_result ma_resource_manager_data_buffer_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_buffer* pDataBuffer)
  56729. {
  56730. return ma_resource_manager_data_buffer_init_ex_internal(pResourceManager, pConfig, 0, pDataBuffer);
  56731. }
  56732. MA_API ma_result ma_resource_manager_data_buffer_init(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_buffer* pDataBuffer)
  56733. {
  56734. ma_resource_manager_data_source_config config;
  56735. config = ma_resource_manager_data_source_config_init();
  56736. config.pFilePath = pFilePath;
  56737. config.flags = flags;
  56738. config.pNotifications = pNotifications;
  56739. return ma_resource_manager_data_buffer_init_ex(pResourceManager, &config, pDataBuffer);
  56740. }
  56741. MA_API ma_result ma_resource_manager_data_buffer_init_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_buffer* pDataBuffer)
  56742. {
  56743. ma_resource_manager_data_source_config config;
  56744. config = ma_resource_manager_data_source_config_init();
  56745. config.pFilePathW = pFilePath;
  56746. config.flags = flags;
  56747. config.pNotifications = pNotifications;
  56748. return ma_resource_manager_data_buffer_init_ex(pResourceManager, &config, pDataBuffer);
  56749. }
  56750. MA_API ma_result ma_resource_manager_data_buffer_init_copy(ma_resource_manager* pResourceManager, const ma_resource_manager_data_buffer* pExistingDataBuffer, ma_resource_manager_data_buffer* pDataBuffer)
  56751. {
  56752. ma_resource_manager_data_source_config config;
  56753. if (pExistingDataBuffer == NULL) {
  56754. return MA_INVALID_ARGS;
  56755. }
  56756. MA_ASSERT(pExistingDataBuffer->pNode != NULL); /* <-- If you've triggered this, you've passed in an invalid existing data buffer. */
  56757. config = ma_resource_manager_data_source_config_init();
  56758. config.flags = pExistingDataBuffer->flags;
  56759. return ma_resource_manager_data_buffer_init_ex_internal(pResourceManager, &config, pExistingDataBuffer->pNode->hashedName32, pDataBuffer);
  56760. }
  56761. static ma_result ma_resource_manager_data_buffer_uninit_internal(ma_resource_manager_data_buffer* pDataBuffer)
  56762. {
  56763. MA_ASSERT(pDataBuffer != NULL);
  56764. /* The connector should be uninitialized first. */
  56765. ma_resource_manager_data_buffer_uninit_connector(pDataBuffer->pResourceManager, pDataBuffer);
  56766. /* With the connector uninitialized we can unacquire the node. */
  56767. ma_resource_manager_data_buffer_node_unacquire(pDataBuffer->pResourceManager, pDataBuffer->pNode, NULL, NULL);
  56768. /* The base data source needs to be uninitialized as well. */
  56769. ma_data_source_uninit(&pDataBuffer->ds);
  56770. return MA_SUCCESS;
  56771. }
  56772. MA_API ma_result ma_resource_manager_data_buffer_uninit(ma_resource_manager_data_buffer* pDataBuffer)
  56773. {
  56774. ma_result result;
  56775. if (pDataBuffer == NULL) {
  56776. return MA_INVALID_ARGS;
  56777. }
  56778. if (ma_resource_manager_data_buffer_result(pDataBuffer) == MA_SUCCESS) {
  56779. /* The data buffer can be deleted synchronously. */
  56780. return ma_resource_manager_data_buffer_uninit_internal(pDataBuffer);
  56781. } else {
  56782. /*
  56783. The data buffer needs to be deleted asynchronously because it's still loading. With the status set to MA_UNAVAILABLE, no more pages will
  56784. be loaded and the uninitialization should happen fairly quickly. Since the caller owns the data buffer, we need to wait for this event
  56785. to get processed before returning.
  56786. */
  56787. ma_resource_manager_inline_notification notification;
  56788. ma_job job;
  56789. /*
  56790. We need to mark the node as unavailable so we don't try reading from it anymore, but also to
  56791. let the loading thread know that it needs to abort it's loading procedure.
  56792. */
  56793. c89atomic_exchange_i32(&pDataBuffer->result, MA_UNAVAILABLE);
  56794. result = ma_resource_manager_inline_notification_init(pDataBuffer->pResourceManager, &notification);
  56795. if (result != MA_SUCCESS) {
  56796. return result; /* Failed to create the notification. This should rarely, if ever, happen. */
  56797. }
  56798. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER);
  56799. job.order = ma_resource_manager_data_buffer_next_execution_order(pDataBuffer);
  56800. job.data.resourceManager.freeDataBuffer.pDataBuffer = pDataBuffer;
  56801. job.data.resourceManager.freeDataBuffer.pDoneNotification = &notification;
  56802. job.data.resourceManager.freeDataBuffer.pDoneFence = NULL;
  56803. result = ma_resource_manager_post_job(pDataBuffer->pResourceManager, &job);
  56804. if (result != MA_SUCCESS) {
  56805. ma_resource_manager_inline_notification_uninit(&notification);
  56806. return result;
  56807. }
  56808. ma_resource_manager_inline_notification_wait_and_uninit(&notification);
  56809. }
  56810. return result;
  56811. }
  56812. MA_API ma_result ma_resource_manager_data_buffer_read_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  56813. {
  56814. ma_result result = MA_SUCCESS;
  56815. ma_uint64 framesRead = 0;
  56816. ma_bool32 isDecodedBufferBusy = MA_FALSE;
  56817. /* Safety. */
  56818. if (pFramesRead != NULL) {
  56819. *pFramesRead = 0;
  56820. }
  56821. if (frameCount == 0) {
  56822. return MA_INVALID_ARGS;
  56823. }
  56824. /*
  56825. We cannot be using the data buffer after it's been uninitialized. If you trigger this assert it means you're trying to read from the data buffer after
  56826. it's been uninitialized or is in the process of uninitializing.
  56827. */
  56828. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  56829. /* If the node is not initialized we need to abort with a busy code. */
  56830. if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE) {
  56831. return MA_BUSY; /* Still loading. */
  56832. }
  56833. /*
  56834. If we've got a seek scheduled we'll want to do that before reading. However, for paged buffers, there's
  56835. a chance that the sound hasn't yet been decoded up to the seek point will result in the seek failing. If
  56836. this happens, we need to keep the seek scheduled and return MA_BUSY.
  56837. */
  56838. if (pDataBuffer->seekToCursorOnNextRead) {
  56839. pDataBuffer->seekToCursorOnNextRead = MA_FALSE;
  56840. result = ma_data_source_seek_to_pcm_frame(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pDataBuffer->seekTargetInPCMFrames);
  56841. if (result != MA_SUCCESS) {
  56842. if (result == MA_BAD_SEEK && ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_decoded_paged) {
  56843. pDataBuffer->seekToCursorOnNextRead = MA_TRUE; /* Keep the seek scheduled. We just haven't loaded enough data yet to do the seek properly. */
  56844. return MA_BUSY;
  56845. }
  56846. return result;
  56847. }
  56848. }
  56849. /*
  56850. For decoded buffers (not paged) we need to check beforehand how many frames we have available. We cannot
  56851. exceed this amount. We'll read as much as we can, and then return MA_BUSY.
  56852. */
  56853. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_decoded) {
  56854. ma_uint64 availableFrames;
  56855. isDecodedBufferBusy = (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY);
  56856. if (ma_resource_manager_data_buffer_get_available_frames(pDataBuffer, &availableFrames) == MA_SUCCESS) {
  56857. /* Don't try reading more than the available frame count. */
  56858. if (frameCount > availableFrames) {
  56859. frameCount = availableFrames;
  56860. /*
  56861. If there's no frames available we want to set the status to MA_AT_END. The logic below
  56862. will check if the node is busy, and if so, change it to MA_BUSY. The reason we do this
  56863. is because we don't want to call `ma_data_source_read_pcm_frames()` if the frame count
  56864. is 0 because that'll result in a situation where it's possible MA_AT_END won't get
  56865. returned.
  56866. */
  56867. if (frameCount == 0) {
  56868. result = MA_AT_END;
  56869. }
  56870. } else {
  56871. isDecodedBufferBusy = MA_FALSE; /* We have enough frames available in the buffer to avoid a MA_BUSY status. */
  56872. }
  56873. }
  56874. }
  56875. /* Don't attempt to read anything if we've got no frames available. */
  56876. if (frameCount > 0) {
  56877. result = ma_data_source_read_pcm_frames(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pFramesOut, frameCount, &framesRead);
  56878. }
  56879. /*
  56880. If we returned MA_AT_END, but the node is still loading, we don't want to return that code or else the caller will interpret the sound
  56881. as at the end and terminate decoding.
  56882. */
  56883. if (result == MA_AT_END) {
  56884. if (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY) {
  56885. result = MA_BUSY;
  56886. }
  56887. }
  56888. if (isDecodedBufferBusy) {
  56889. result = MA_BUSY;
  56890. }
  56891. if (pFramesRead != NULL) {
  56892. *pFramesRead = framesRead;
  56893. }
  56894. if (result == MA_SUCCESS && framesRead == 0) {
  56895. result = MA_AT_END;
  56896. }
  56897. return result;
  56898. }
  56899. MA_API ma_result ma_resource_manager_data_buffer_seek_to_pcm_frame(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64 frameIndex)
  56900. {
  56901. ma_result result;
  56902. /* We cannot be using the data source after it's been uninitialized. */
  56903. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  56904. /* If we haven't yet got a connector we need to abort. */
  56905. if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE) {
  56906. pDataBuffer->seekTargetInPCMFrames = frameIndex;
  56907. pDataBuffer->seekToCursorOnNextRead = MA_TRUE;
  56908. return MA_BUSY; /* Still loading. */
  56909. }
  56910. result = ma_data_source_seek_to_pcm_frame(ma_resource_manager_data_buffer_get_connector(pDataBuffer), frameIndex);
  56911. if (result != MA_SUCCESS) {
  56912. return result;
  56913. }
  56914. pDataBuffer->seekTargetInPCMFrames = ~(ma_uint64)0; /* <-- For identification purposes. */
  56915. pDataBuffer->seekToCursorOnNextRead = MA_FALSE;
  56916. return MA_SUCCESS;
  56917. }
  56918. MA_API ma_result ma_resource_manager_data_buffer_get_data_format(ma_resource_manager_data_buffer* pDataBuffer, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  56919. {
  56920. /* We cannot be using the data source after it's been uninitialized. */
  56921. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  56922. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  56923. {
  56924. case ma_resource_manager_data_supply_type_encoded:
  56925. {
  56926. return ma_data_source_get_data_format(&pDataBuffer->connector.decoder, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  56927. };
  56928. case ma_resource_manager_data_supply_type_decoded:
  56929. {
  56930. *pFormat = pDataBuffer->pNode->data.backend.decoded.format;
  56931. *pChannels = pDataBuffer->pNode->data.backend.decoded.channels;
  56932. *pSampleRate = pDataBuffer->pNode->data.backend.decoded.sampleRate;
  56933. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pDataBuffer->pNode->data.backend.decoded.channels);
  56934. return MA_SUCCESS;
  56935. };
  56936. case ma_resource_manager_data_supply_type_decoded_paged:
  56937. {
  56938. *pFormat = pDataBuffer->pNode->data.backend.decodedPaged.data.format;
  56939. *pChannels = pDataBuffer->pNode->data.backend.decodedPaged.data.channels;
  56940. *pSampleRate = pDataBuffer->pNode->data.backend.decodedPaged.sampleRate;
  56941. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pDataBuffer->pNode->data.backend.decoded.channels);
  56942. return MA_SUCCESS;
  56943. };
  56944. case ma_resource_manager_data_supply_type_unknown:
  56945. {
  56946. return MA_BUSY; /* Still loading. */
  56947. };
  56948. default:
  56949. {
  56950. /* Unknown supply type. Should never hit this. */
  56951. return MA_INVALID_ARGS;
  56952. }
  56953. }
  56954. }
  56955. MA_API ma_result ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pCursor)
  56956. {
  56957. /* We cannot be using the data source after it's been uninitialized. */
  56958. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  56959. if (pDataBuffer == NULL || pCursor == NULL) {
  56960. return MA_INVALID_ARGS;
  56961. }
  56962. *pCursor = 0;
  56963. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  56964. {
  56965. case ma_resource_manager_data_supply_type_encoded:
  56966. {
  56967. return ma_decoder_get_cursor_in_pcm_frames(&pDataBuffer->connector.decoder, pCursor);
  56968. };
  56969. case ma_resource_manager_data_supply_type_decoded:
  56970. {
  56971. return ma_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.buffer, pCursor);
  56972. };
  56973. case ma_resource_manager_data_supply_type_decoded_paged:
  56974. {
  56975. return ma_paged_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.pagedBuffer, pCursor);
  56976. };
  56977. case ma_resource_manager_data_supply_type_unknown:
  56978. {
  56979. return MA_BUSY;
  56980. };
  56981. default:
  56982. {
  56983. return MA_INVALID_ARGS;
  56984. }
  56985. }
  56986. }
  56987. MA_API ma_result ma_resource_manager_data_buffer_get_length_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pLength)
  56988. {
  56989. /* We cannot be using the data source after it's been uninitialized. */
  56990. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  56991. if (pDataBuffer == NULL || pLength == NULL) {
  56992. return MA_INVALID_ARGS;
  56993. }
  56994. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) {
  56995. return MA_BUSY; /* Still loading. */
  56996. }
  56997. return ma_data_source_get_length_in_pcm_frames(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pLength);
  56998. }
  56999. MA_API ma_result ma_resource_manager_data_buffer_result(const ma_resource_manager_data_buffer* pDataBuffer)
  57000. {
  57001. if (pDataBuffer == NULL) {
  57002. return MA_INVALID_ARGS;
  57003. }
  57004. return (ma_result)c89atomic_load_i32((ma_result*)&pDataBuffer->result); /* Need a naughty const-cast here. */
  57005. }
  57006. MA_API ma_result ma_resource_manager_data_buffer_set_looping(ma_resource_manager_data_buffer* pDataBuffer, ma_bool32 isLooping)
  57007. {
  57008. return ma_data_source_set_looping(pDataBuffer, isLooping);
  57009. }
  57010. MA_API ma_bool32 ma_resource_manager_data_buffer_is_looping(const ma_resource_manager_data_buffer* pDataBuffer)
  57011. {
  57012. return ma_data_source_is_looping(pDataBuffer);
  57013. }
  57014. MA_API ma_result ma_resource_manager_data_buffer_get_available_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pAvailableFrames)
  57015. {
  57016. if (pAvailableFrames == NULL) {
  57017. return MA_INVALID_ARGS;
  57018. }
  57019. *pAvailableFrames = 0;
  57020. if (pDataBuffer == NULL) {
  57021. return MA_INVALID_ARGS;
  57022. }
  57023. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) {
  57024. if (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY) {
  57025. return MA_BUSY;
  57026. } else {
  57027. return MA_INVALID_OPERATION; /* No connector. */
  57028. }
  57029. }
  57030. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  57031. {
  57032. case ma_resource_manager_data_supply_type_encoded:
  57033. {
  57034. return ma_decoder_get_available_frames(&pDataBuffer->connector.decoder, pAvailableFrames);
  57035. };
  57036. case ma_resource_manager_data_supply_type_decoded:
  57037. {
  57038. return ma_audio_buffer_get_available_frames(&pDataBuffer->connector.buffer, pAvailableFrames);
  57039. };
  57040. case ma_resource_manager_data_supply_type_decoded_paged:
  57041. {
  57042. ma_uint64 cursor;
  57043. ma_paged_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.pagedBuffer, &cursor);
  57044. if (pDataBuffer->pNode->data.backend.decodedPaged.decodedFrameCount > cursor) {
  57045. *pAvailableFrames = pDataBuffer->pNode->data.backend.decodedPaged.decodedFrameCount - cursor;
  57046. } else {
  57047. *pAvailableFrames = 0;
  57048. }
  57049. return MA_SUCCESS;
  57050. };
  57051. case ma_resource_manager_data_supply_type_unknown:
  57052. default:
  57053. {
  57054. /* Unknown supply type. Should never hit this. */
  57055. return MA_INVALID_ARGS;
  57056. }
  57057. }
  57058. }
  57059. MA_API ma_result ma_resource_manager_register_file(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags)
  57060. {
  57061. return ma_resource_manager_data_buffer_node_acquire(pResourceManager, pFilePath, NULL, 0, flags, NULL, NULL, NULL, NULL);
  57062. }
  57063. MA_API ma_result ma_resource_manager_register_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags)
  57064. {
  57065. return ma_resource_manager_data_buffer_node_acquire(pResourceManager, NULL, pFilePath, 0, flags, NULL, NULL, NULL, NULL);
  57066. }
  57067. static ma_result ma_resource_manager_register_data(ma_resource_manager* pResourceManager, const char* pName, const wchar_t* pNameW, ma_resource_manager_data_supply* pExistingData)
  57068. {
  57069. return ma_resource_manager_data_buffer_node_acquire(pResourceManager, pName, pNameW, 0, 0, pExistingData, NULL, NULL, NULL);
  57070. }
  57071. static ma_result ma_resource_manager_register_decoded_data_internal(ma_resource_manager* pResourceManager, const char* pName, const wchar_t* pNameW, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  57072. {
  57073. ma_resource_manager_data_supply data;
  57074. data.type = ma_resource_manager_data_supply_type_decoded;
  57075. data.backend.decoded.pData = pData;
  57076. data.backend.decoded.totalFrameCount = frameCount;
  57077. data.backend.decoded.format = format;
  57078. data.backend.decoded.channels = channels;
  57079. data.backend.decoded.sampleRate = sampleRate;
  57080. return ma_resource_manager_register_data(pResourceManager, pName, pNameW, &data);
  57081. }
  57082. MA_API ma_result ma_resource_manager_register_decoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  57083. {
  57084. return ma_resource_manager_register_decoded_data_internal(pResourceManager, pName, NULL, pData, frameCount, format, channels, sampleRate);
  57085. }
  57086. MA_API ma_result ma_resource_manager_register_decoded_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName, const void* pData, ma_uint64 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  57087. {
  57088. return ma_resource_manager_register_decoded_data_internal(pResourceManager, NULL, pName, pData, frameCount, format, channels, sampleRate);
  57089. }
  57090. static ma_result ma_resource_manager_register_encoded_data_internal(ma_resource_manager* pResourceManager, const char* pName, const wchar_t* pNameW, const void* pData, size_t sizeInBytes)
  57091. {
  57092. ma_resource_manager_data_supply data;
  57093. data.type = ma_resource_manager_data_supply_type_encoded;
  57094. data.backend.encoded.pData = pData;
  57095. data.backend.encoded.sizeInBytes = sizeInBytes;
  57096. return ma_resource_manager_register_data(pResourceManager, pName, pNameW, &data);
  57097. }
  57098. MA_API ma_result ma_resource_manager_register_encoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, size_t sizeInBytes)
  57099. {
  57100. return ma_resource_manager_register_encoded_data_internal(pResourceManager, pName, NULL, pData, sizeInBytes);
  57101. }
  57102. MA_API ma_result ma_resource_manager_register_encoded_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName, const void* pData, size_t sizeInBytes)
  57103. {
  57104. return ma_resource_manager_register_encoded_data_internal(pResourceManager, NULL, pName, pData, sizeInBytes);
  57105. }
  57106. MA_API ma_result ma_resource_manager_unregister_file(ma_resource_manager* pResourceManager, const char* pFilePath)
  57107. {
  57108. return ma_resource_manager_unregister_data(pResourceManager, pFilePath);
  57109. }
  57110. MA_API ma_result ma_resource_manager_unregister_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath)
  57111. {
  57112. return ma_resource_manager_unregister_data_w(pResourceManager, pFilePath);
  57113. }
  57114. MA_API ma_result ma_resource_manager_unregister_data(ma_resource_manager* pResourceManager, const char* pName)
  57115. {
  57116. return ma_resource_manager_data_buffer_node_unacquire(pResourceManager, NULL, pName, NULL);
  57117. }
  57118. MA_API ma_result ma_resource_manager_unregister_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName)
  57119. {
  57120. return ma_resource_manager_data_buffer_node_unacquire(pResourceManager, NULL, NULL, pName);
  57121. }
  57122. static ma_uint32 ma_resource_manager_data_stream_next_execution_order(ma_resource_manager_data_stream* pDataStream)
  57123. {
  57124. MA_ASSERT(pDataStream != NULL);
  57125. return c89atomic_fetch_add_32(&pDataStream->executionCounter, 1);
  57126. }
  57127. static ma_bool32 ma_resource_manager_data_stream_is_decoder_at_end(const ma_resource_manager_data_stream* pDataStream)
  57128. {
  57129. MA_ASSERT(pDataStream != NULL);
  57130. return c89atomic_load_32((ma_bool32*)&pDataStream->isDecoderAtEnd);
  57131. }
  57132. static ma_uint32 ma_resource_manager_data_stream_seek_counter(const ma_resource_manager_data_stream* pDataStream)
  57133. {
  57134. MA_ASSERT(pDataStream != NULL);
  57135. return c89atomic_load_32((ma_uint32*)&pDataStream->seekCounter);
  57136. }
  57137. static ma_result ma_resource_manager_data_stream_cb__read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  57138. {
  57139. return ma_resource_manager_data_stream_read_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pFramesOut, frameCount, pFramesRead);
  57140. }
  57141. static ma_result ma_resource_manager_data_stream_cb__seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
  57142. {
  57143. return ma_resource_manager_data_stream_seek_to_pcm_frame((ma_resource_manager_data_stream*)pDataSource, frameIndex);
  57144. }
  57145. static ma_result ma_resource_manager_data_stream_cb__get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  57146. {
  57147. return ma_resource_manager_data_stream_get_data_format((ma_resource_manager_data_stream*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  57148. }
  57149. static ma_result ma_resource_manager_data_stream_cb__get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
  57150. {
  57151. return ma_resource_manager_data_stream_get_cursor_in_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pCursor);
  57152. }
  57153. static ma_result ma_resource_manager_data_stream_cb__get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
  57154. {
  57155. return ma_resource_manager_data_stream_get_length_in_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pLength);
  57156. }
  57157. static ma_result ma_resource_manager_data_stream_cb__set_looping(ma_data_source* pDataSource, ma_bool32 isLooping)
  57158. {
  57159. ma_resource_manager_data_stream* pDataStream = (ma_resource_manager_data_stream*)pDataSource;
  57160. MA_ASSERT(pDataStream != NULL);
  57161. c89atomic_exchange_32(&pDataStream->isLooping, isLooping);
  57162. return MA_SUCCESS;
  57163. }
  57164. static ma_data_source_vtable g_ma_resource_manager_data_stream_vtable =
  57165. {
  57166. ma_resource_manager_data_stream_cb__read_pcm_frames,
  57167. ma_resource_manager_data_stream_cb__seek_to_pcm_frame,
  57168. ma_resource_manager_data_stream_cb__get_data_format,
  57169. ma_resource_manager_data_stream_cb__get_cursor_in_pcm_frames,
  57170. ma_resource_manager_data_stream_cb__get_length_in_pcm_frames,
  57171. ma_resource_manager_data_stream_cb__set_looping,
  57172. 0 /*MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT*/
  57173. };
  57174. static void ma_resource_manager_data_stream_set_absolute_cursor(ma_resource_manager_data_stream* pDataStream, ma_uint64 absoluteCursor)
  57175. {
  57176. /* Loop if possible. */
  57177. if (absoluteCursor > pDataStream->totalLengthInPCMFrames && pDataStream->totalLengthInPCMFrames > 0) {
  57178. absoluteCursor = absoluteCursor % pDataStream->totalLengthInPCMFrames;
  57179. }
  57180. c89atomic_exchange_64(&pDataStream->absoluteCursor, absoluteCursor);
  57181. }
  57182. MA_API ma_result ma_resource_manager_data_stream_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_stream* pDataStream)
  57183. {
  57184. ma_result result;
  57185. ma_data_source_config dataSourceConfig;
  57186. char* pFilePathCopy = NULL;
  57187. wchar_t* pFilePathWCopy = NULL;
  57188. ma_job job;
  57189. ma_bool32 waitBeforeReturning = MA_FALSE;
  57190. ma_resource_manager_inline_notification waitNotification;
  57191. ma_resource_manager_pipeline_notifications notifications;
  57192. if (pDataStream == NULL) {
  57193. if (pConfig != NULL && pConfig->pNotifications != NULL) {
  57194. ma_resource_manager_pipeline_notifications_signal_all_notifications(pConfig->pNotifications);
  57195. }
  57196. return MA_INVALID_ARGS;
  57197. }
  57198. MA_ZERO_OBJECT(pDataStream);
  57199. if (pConfig == NULL) {
  57200. return MA_INVALID_ARGS;
  57201. }
  57202. if (pConfig->pNotifications != NULL) {
  57203. notifications = *pConfig->pNotifications; /* From here on out, `notifications` should be used instead of `pNotifications`. Setting this to NULL to catch any errors at testing time. */
  57204. } else {
  57205. MA_ZERO_OBJECT(&notifications);
  57206. }
  57207. dataSourceConfig = ma_data_source_config_init();
  57208. dataSourceConfig.vtable = &g_ma_resource_manager_data_stream_vtable;
  57209. result = ma_data_source_init(&dataSourceConfig, &pDataStream->ds);
  57210. if (result != MA_SUCCESS) {
  57211. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  57212. return result;
  57213. }
  57214. pDataStream->pResourceManager = pResourceManager;
  57215. pDataStream->flags = pConfig->flags;
  57216. pDataStream->result = MA_BUSY;
  57217. ma_data_source_set_range_in_pcm_frames(pDataStream, pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames);
  57218. ma_data_source_set_loop_point_in_pcm_frames(pDataStream, pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames);
  57219. ma_data_source_set_looping(pDataStream, pConfig->isLooping);
  57220. if (pResourceManager == NULL || (pConfig->pFilePath == NULL && pConfig->pFilePathW == NULL)) {
  57221. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  57222. return MA_INVALID_ARGS;
  57223. }
  57224. /* We want all access to the VFS and the internal decoder to happen on the job thread just to keep things easier to manage for the VFS. */
  57225. /* We need a copy of the file path. We should probably make this more efficient, but for now we'll do a transient memory allocation. */
  57226. if (pConfig->pFilePath != NULL) {
  57227. pFilePathCopy = ma_copy_string(pConfig->pFilePath, &pResourceManager->config.allocationCallbacks);
  57228. } else {
  57229. pFilePathWCopy = ma_copy_string_w(pConfig->pFilePathW, &pResourceManager->config.allocationCallbacks);
  57230. }
  57231. if (pFilePathCopy == NULL && pFilePathWCopy == NULL) {
  57232. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  57233. return MA_OUT_OF_MEMORY;
  57234. }
  57235. /*
  57236. We need to check for the presence of MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC. If it's not set, we need to wait before returning. Otherwise we
  57237. can return immediately. Likewise, we'll also check for MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT and do the same.
  57238. */
  57239. if ((pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) == 0 || (pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  57240. waitBeforeReturning = MA_TRUE;
  57241. ma_resource_manager_inline_notification_init(pResourceManager, &waitNotification);
  57242. }
  57243. ma_resource_manager_pipeline_notifications_acquire_all_fences(&notifications);
  57244. /* Set the absolute cursor to our initial seek position so retrieval of the cursor returns a good value. */
  57245. ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, pConfig->initialSeekPointInPCMFrames);
  57246. /* We now have everything we need to post the job. This is the last thing we need to do from here. The rest will be done by the job thread. */
  57247. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM);
  57248. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  57249. job.data.resourceManager.loadDataStream.pDataStream = pDataStream;
  57250. job.data.resourceManager.loadDataStream.pFilePath = pFilePathCopy;
  57251. job.data.resourceManager.loadDataStream.pFilePathW = pFilePathWCopy;
  57252. job.data.resourceManager.loadDataStream.initialSeekPoint = pConfig->initialSeekPointInPCMFrames;
  57253. job.data.resourceManager.loadDataStream.pInitNotification = (waitBeforeReturning == MA_TRUE) ? &waitNotification : notifications.init.pNotification;
  57254. job.data.resourceManager.loadDataStream.pInitFence = notifications.init.pFence;
  57255. result = ma_resource_manager_post_job(pResourceManager, &job);
  57256. if (result != MA_SUCCESS) {
  57257. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  57258. ma_resource_manager_pipeline_notifications_release_all_fences(&notifications);
  57259. if (waitBeforeReturning) {
  57260. ma_resource_manager_inline_notification_uninit(&waitNotification);
  57261. }
  57262. ma_free(pFilePathCopy, &pResourceManager->config.allocationCallbacks);
  57263. ma_free(pFilePathWCopy, &pResourceManager->config.allocationCallbacks);
  57264. return result;
  57265. }
  57266. /* Wait if needed. */
  57267. if (waitBeforeReturning) {
  57268. ma_resource_manager_inline_notification_wait_and_uninit(&waitNotification);
  57269. if (notifications.init.pNotification != NULL) {
  57270. ma_async_notification_signal(notifications.init.pNotification);
  57271. }
  57272. /*
  57273. If there was an error during initialization make sure we return that result here. We don't want to do this
  57274. if we're not waiting because it will most likely be in a busy state.
  57275. */
  57276. if (pDataStream->result != MA_SUCCESS) {
  57277. return pDataStream->result;
  57278. }
  57279. /* NOTE: Do not release pInitFence here. That will be done by the job. */
  57280. }
  57281. return MA_SUCCESS;
  57282. }
  57283. MA_API ma_result ma_resource_manager_data_stream_init(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_stream* pDataStream)
  57284. {
  57285. ma_resource_manager_data_source_config config;
  57286. config = ma_resource_manager_data_source_config_init();
  57287. config.pFilePath = pFilePath;
  57288. config.flags = flags;
  57289. config.pNotifications = pNotifications;
  57290. return ma_resource_manager_data_stream_init_ex(pResourceManager, &config, pDataStream);
  57291. }
  57292. MA_API ma_result ma_resource_manager_data_stream_init_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_stream* pDataStream)
  57293. {
  57294. ma_resource_manager_data_source_config config;
  57295. config = ma_resource_manager_data_source_config_init();
  57296. config.pFilePathW = pFilePath;
  57297. config.flags = flags;
  57298. config.pNotifications = pNotifications;
  57299. return ma_resource_manager_data_stream_init_ex(pResourceManager, &config, pDataStream);
  57300. }
  57301. MA_API ma_result ma_resource_manager_data_stream_uninit(ma_resource_manager_data_stream* pDataStream)
  57302. {
  57303. ma_resource_manager_inline_notification freeEvent;
  57304. ma_job job;
  57305. if (pDataStream == NULL) {
  57306. return MA_INVALID_ARGS;
  57307. }
  57308. /* The first thing to do is set the result to unavailable. This will prevent future page decoding. */
  57309. c89atomic_exchange_i32(&pDataStream->result, MA_UNAVAILABLE);
  57310. /*
  57311. We need to post a job to ensure we're not in the middle or decoding or anything. Because the object is owned by the caller, we'll need
  57312. to wait for it to complete before returning which means we need an event.
  57313. */
  57314. ma_resource_manager_inline_notification_init(pDataStream->pResourceManager, &freeEvent);
  57315. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM);
  57316. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  57317. job.data.resourceManager.freeDataStream.pDataStream = pDataStream;
  57318. job.data.resourceManager.freeDataStream.pDoneNotification = &freeEvent;
  57319. job.data.resourceManager.freeDataStream.pDoneFence = NULL;
  57320. ma_resource_manager_post_job(pDataStream->pResourceManager, &job);
  57321. /* We need to wait for the job to finish processing before we return. */
  57322. ma_resource_manager_inline_notification_wait_and_uninit(&freeEvent);
  57323. return MA_SUCCESS;
  57324. }
  57325. static ma_uint32 ma_resource_manager_data_stream_get_page_size_in_frames(ma_resource_manager_data_stream* pDataStream)
  57326. {
  57327. MA_ASSERT(pDataStream != NULL);
  57328. MA_ASSERT(pDataStream->isDecoderInitialized == MA_TRUE);
  57329. return MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS * (pDataStream->decoder.outputSampleRate/1000);
  57330. }
  57331. static void* ma_resource_manager_data_stream_get_page_data_pointer(ma_resource_manager_data_stream* pDataStream, ma_uint32 pageIndex, ma_uint32 relativeCursor)
  57332. {
  57333. MA_ASSERT(pDataStream != NULL);
  57334. MA_ASSERT(pDataStream->isDecoderInitialized == MA_TRUE);
  57335. MA_ASSERT(pageIndex == 0 || pageIndex == 1);
  57336. return ma_offset_ptr(pDataStream->pPageData, ((ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream) * pageIndex) + relativeCursor) * ma_get_bytes_per_frame(pDataStream->decoder.outputFormat, pDataStream->decoder.outputChannels));
  57337. }
  57338. static void ma_resource_manager_data_stream_fill_page(ma_resource_manager_data_stream* pDataStream, ma_uint32 pageIndex)
  57339. {
  57340. ma_result result = MA_SUCCESS;
  57341. ma_uint64 pageSizeInFrames;
  57342. ma_uint64 totalFramesReadForThisPage = 0;
  57343. void* pPageData = ma_resource_manager_data_stream_get_page_data_pointer(pDataStream, pageIndex, 0);
  57344. pageSizeInFrames = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream);
  57345. /* The decoder needs to inherit the stream's looping and range state. */
  57346. {
  57347. ma_uint64 rangeBeg;
  57348. ma_uint64 rangeEnd;
  57349. ma_uint64 loopPointBeg;
  57350. ma_uint64 loopPointEnd;
  57351. ma_data_source_set_looping(&pDataStream->decoder, ma_resource_manager_data_stream_is_looping(pDataStream));
  57352. ma_data_source_get_range_in_pcm_frames(pDataStream, &rangeBeg, &rangeEnd);
  57353. ma_data_source_set_range_in_pcm_frames(&pDataStream->decoder, rangeBeg, rangeEnd);
  57354. ma_data_source_get_loop_point_in_pcm_frames(pDataStream, &loopPointBeg, &loopPointEnd);
  57355. ma_data_source_set_loop_point_in_pcm_frames(&pDataStream->decoder, loopPointBeg, loopPointEnd);
  57356. }
  57357. /* Just read straight from the decoder. It will deal with ranges and looping for us. */
  57358. result = ma_data_source_read_pcm_frames(&pDataStream->decoder, pPageData, pageSizeInFrames, &totalFramesReadForThisPage);
  57359. if (result == MA_AT_END || totalFramesReadForThisPage < pageSizeInFrames) {
  57360. c89atomic_exchange_32(&pDataStream->isDecoderAtEnd, MA_TRUE);
  57361. }
  57362. c89atomic_exchange_32(&pDataStream->pageFrameCount[pageIndex], (ma_uint32)totalFramesReadForThisPage);
  57363. c89atomic_exchange_32(&pDataStream->isPageValid[pageIndex], MA_TRUE);
  57364. }
  57365. static void ma_resource_manager_data_stream_fill_pages(ma_resource_manager_data_stream* pDataStream)
  57366. {
  57367. ma_uint32 iPage;
  57368. MA_ASSERT(pDataStream != NULL);
  57369. for (iPage = 0; iPage < 2; iPage += 1) {
  57370. ma_resource_manager_data_stream_fill_page(pDataStream, iPage);
  57371. }
  57372. }
  57373. static ma_result ma_resource_manager_data_stream_map(ma_resource_manager_data_stream* pDataStream, void** ppFramesOut, ma_uint64* pFrameCount)
  57374. {
  57375. ma_uint64 framesAvailable;
  57376. ma_uint64 frameCount = 0;
  57377. /* We cannot be using the data source after it's been uninitialized. */
  57378. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57379. if (pFrameCount != NULL) {
  57380. frameCount = *pFrameCount;
  57381. *pFrameCount = 0;
  57382. }
  57383. if (ppFramesOut != NULL) {
  57384. *ppFramesOut = NULL;
  57385. }
  57386. if (pDataStream == NULL || ppFramesOut == NULL || pFrameCount == NULL) {
  57387. return MA_INVALID_ARGS;
  57388. }
  57389. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  57390. return MA_INVALID_OPERATION;
  57391. }
  57392. /* Don't attempt to read while we're in the middle of seeking. Tell the caller that we're busy. */
  57393. if (ma_resource_manager_data_stream_seek_counter(pDataStream) > 0) {
  57394. return MA_BUSY;
  57395. }
  57396. /* If the page we're on is invalid it means we've caught up to the job thread. */
  57397. if (c89atomic_load_32(&pDataStream->isPageValid[pDataStream->currentPageIndex]) == MA_FALSE) {
  57398. framesAvailable = 0;
  57399. } else {
  57400. /*
  57401. The page we're on is valid so we must have some frames available. We need to make sure that we don't overflow into the next page, even if it's valid. The reason is
  57402. that the unmap process will only post an update for one page at a time. Keeping mapping tied to page boundaries makes this simpler.
  57403. */
  57404. ma_uint32 currentPageFrameCount = c89atomic_load_32(&pDataStream->pageFrameCount[pDataStream->currentPageIndex]);
  57405. MA_ASSERT(currentPageFrameCount >= pDataStream->relativeCursor);
  57406. framesAvailable = currentPageFrameCount - pDataStream->relativeCursor;
  57407. }
  57408. /* If there's no frames available and the result is set to MA_AT_END we need to return MA_AT_END. */
  57409. if (framesAvailable == 0) {
  57410. if (ma_resource_manager_data_stream_is_decoder_at_end(pDataStream)) {
  57411. return MA_AT_END;
  57412. } else {
  57413. return MA_BUSY; /* There are no frames available, but we're not marked as EOF so we might have caught up to the job thread. Need to return MA_BUSY and wait for more data. */
  57414. }
  57415. }
  57416. MA_ASSERT(framesAvailable > 0);
  57417. if (frameCount > framesAvailable) {
  57418. frameCount = framesAvailable;
  57419. }
  57420. *ppFramesOut = ma_resource_manager_data_stream_get_page_data_pointer(pDataStream, pDataStream->currentPageIndex, pDataStream->relativeCursor);
  57421. *pFrameCount = frameCount;
  57422. return MA_SUCCESS;
  57423. }
  57424. static ma_result ma_resource_manager_data_stream_unmap(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameCount)
  57425. {
  57426. ma_uint32 newRelativeCursor;
  57427. ma_uint32 pageSizeInFrames;
  57428. ma_job job;
  57429. /* We cannot be using the data source after it's been uninitialized. */
  57430. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57431. if (pDataStream == NULL) {
  57432. return MA_INVALID_ARGS;
  57433. }
  57434. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  57435. return MA_INVALID_OPERATION;
  57436. }
  57437. /* The frame count should always fit inside a 32-bit integer. */
  57438. if (frameCount > 0xFFFFFFFF) {
  57439. return MA_INVALID_ARGS;
  57440. }
  57441. pageSizeInFrames = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream);
  57442. /* The absolute cursor needs to be updated for ma_resource_manager_data_stream_get_cursor_in_pcm_frames(). */
  57443. ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, c89atomic_load_64(&pDataStream->absoluteCursor) + frameCount);
  57444. /* Here is where we need to check if we need to load a new page, and if so, post a job to load it. */
  57445. newRelativeCursor = pDataStream->relativeCursor + (ma_uint32)frameCount;
  57446. /* If the new cursor has flowed over to the next page we need to mark the old one as invalid and post an event for it. */
  57447. if (newRelativeCursor >= pageSizeInFrames) {
  57448. newRelativeCursor -= pageSizeInFrames;
  57449. /* Here is where we post the job start decoding. */
  57450. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM);
  57451. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  57452. job.data.resourceManager.pageDataStream.pDataStream = pDataStream;
  57453. job.data.resourceManager.pageDataStream.pageIndex = pDataStream->currentPageIndex;
  57454. /* The page needs to be marked as invalid so that the public API doesn't try reading from it. */
  57455. c89atomic_exchange_32(&pDataStream->isPageValid[pDataStream->currentPageIndex], MA_FALSE);
  57456. /* Before posting the job we need to make sure we set some state. */
  57457. pDataStream->relativeCursor = newRelativeCursor;
  57458. pDataStream->currentPageIndex = (pDataStream->currentPageIndex + 1) & 0x01;
  57459. return ma_resource_manager_post_job(pDataStream->pResourceManager, &job);
  57460. } else {
  57461. /* We haven't moved into a new page so we can just move the cursor forward. */
  57462. pDataStream->relativeCursor = newRelativeCursor;
  57463. return MA_SUCCESS;
  57464. }
  57465. }
  57466. MA_API ma_result ma_resource_manager_data_stream_read_pcm_frames(ma_resource_manager_data_stream* pDataStream, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  57467. {
  57468. ma_result result = MA_SUCCESS;
  57469. ma_uint64 totalFramesProcessed;
  57470. ma_format format;
  57471. ma_uint32 channels;
  57472. /* Safety. */
  57473. if (pFramesRead != NULL) {
  57474. *pFramesRead = 0;
  57475. }
  57476. if (frameCount == 0) {
  57477. return MA_INVALID_ARGS;
  57478. }
  57479. /* We cannot be using the data source after it's been uninitialized. */
  57480. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57481. if (pDataStream == NULL) {
  57482. return MA_INVALID_ARGS;
  57483. }
  57484. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  57485. return MA_INVALID_OPERATION;
  57486. }
  57487. /* Don't attempt to read while we're in the middle of seeking. Tell the caller that we're busy. */
  57488. if (ma_resource_manager_data_stream_seek_counter(pDataStream) > 0) {
  57489. return MA_BUSY;
  57490. }
  57491. ma_resource_manager_data_stream_get_data_format(pDataStream, &format, &channels, NULL, NULL, 0);
  57492. /* Reading is implemented in terms of map/unmap. We need to run this in a loop because mapping is clamped against page boundaries. */
  57493. totalFramesProcessed = 0;
  57494. while (totalFramesProcessed < frameCount) {
  57495. void* pMappedFrames;
  57496. ma_uint64 mappedFrameCount;
  57497. mappedFrameCount = frameCount - totalFramesProcessed;
  57498. result = ma_resource_manager_data_stream_map(pDataStream, &pMappedFrames, &mappedFrameCount);
  57499. if (result != MA_SUCCESS) {
  57500. break;
  57501. }
  57502. /* Copy the mapped data to the output buffer if we have one. It's allowed for pFramesOut to be NULL in which case a relative forward seek is performed. */
  57503. if (pFramesOut != NULL) {
  57504. ma_copy_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesProcessed, format, channels), pMappedFrames, mappedFrameCount, format, channels);
  57505. }
  57506. totalFramesProcessed += mappedFrameCount;
  57507. result = ma_resource_manager_data_stream_unmap(pDataStream, mappedFrameCount);
  57508. if (result != MA_SUCCESS) {
  57509. break; /* This is really bad - will only get an error here if we failed to post a job to the queue for loading the next page. */
  57510. }
  57511. }
  57512. if (pFramesRead != NULL) {
  57513. *pFramesRead = totalFramesProcessed;
  57514. }
  57515. if (result == MA_SUCCESS && totalFramesProcessed == 0) {
  57516. result = MA_AT_END;
  57517. }
  57518. return result;
  57519. }
  57520. MA_API ma_result ma_resource_manager_data_stream_seek_to_pcm_frame(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameIndex)
  57521. {
  57522. ma_job job;
  57523. ma_result streamResult;
  57524. streamResult = ma_resource_manager_data_stream_result(pDataStream);
  57525. /* We cannot be using the data source after it's been uninitialized. */
  57526. MA_ASSERT(streamResult != MA_UNAVAILABLE);
  57527. if (pDataStream == NULL) {
  57528. return MA_INVALID_ARGS;
  57529. }
  57530. if (streamResult != MA_SUCCESS && streamResult != MA_BUSY) {
  57531. return MA_INVALID_OPERATION;
  57532. }
  57533. /* If we're not already seeking and we're sitting on the same frame, just make this a no-op. */
  57534. if (c89atomic_load_32(&pDataStream->seekCounter) == 0) {
  57535. if (c89atomic_load_64(&pDataStream->absoluteCursor) == frameIndex) {
  57536. return MA_SUCCESS;
  57537. }
  57538. }
  57539. /* Increment the seek counter first to indicate to read_paged_pcm_frames() and map_paged_pcm_frames() that we are in the middle of a seek and MA_BUSY should be returned. */
  57540. c89atomic_fetch_add_32(&pDataStream->seekCounter, 1);
  57541. /* Update the absolute cursor so that ma_resource_manager_data_stream_get_cursor_in_pcm_frames() returns the new position. */
  57542. ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, frameIndex);
  57543. /*
  57544. We need to clear our currently loaded pages so that the stream starts playback from the new seek point as soon as possible. These are for the purpose of the public
  57545. API and will be ignored by the seek job. The seek job will operate on the assumption that both pages have been marked as invalid and the cursor is at the start of
  57546. the first page.
  57547. */
  57548. pDataStream->relativeCursor = 0;
  57549. pDataStream->currentPageIndex = 0;
  57550. c89atomic_exchange_32(&pDataStream->isPageValid[0], MA_FALSE);
  57551. c89atomic_exchange_32(&pDataStream->isPageValid[1], MA_FALSE);
  57552. /* Make sure the data stream is not marked as at the end or else if we seek in response to hitting the end, we won't be able to read any more data. */
  57553. c89atomic_exchange_32(&pDataStream->isDecoderAtEnd, MA_FALSE);
  57554. /*
  57555. The public API is not allowed to touch the internal decoder so we need to use a job to perform the seek. When seeking, the job thread will assume both pages
  57556. are invalid and any content contained within them will be discarded and replaced with newly decoded data.
  57557. */
  57558. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM);
  57559. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  57560. job.data.resourceManager.seekDataStream.pDataStream = pDataStream;
  57561. job.data.resourceManager.seekDataStream.frameIndex = frameIndex;
  57562. return ma_resource_manager_post_job(pDataStream->pResourceManager, &job);
  57563. }
  57564. MA_API ma_result ma_resource_manager_data_stream_get_data_format(ma_resource_manager_data_stream* pDataStream, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  57565. {
  57566. /* We cannot be using the data source after it's been uninitialized. */
  57567. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57568. if (pFormat != NULL) {
  57569. *pFormat = ma_format_unknown;
  57570. }
  57571. if (pChannels != NULL) {
  57572. *pChannels = 0;
  57573. }
  57574. if (pSampleRate != NULL) {
  57575. *pSampleRate = 0;
  57576. }
  57577. if (pChannelMap != NULL) {
  57578. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  57579. }
  57580. if (pDataStream == NULL) {
  57581. return MA_INVALID_ARGS;
  57582. }
  57583. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  57584. return MA_INVALID_OPERATION;
  57585. }
  57586. /*
  57587. We're being a little bit naughty here and accessing the internal decoder from the public API. The output data format is constant, and we've defined this function
  57588. such that the application is responsible for ensuring it's not called while uninitializing so it should be safe.
  57589. */
  57590. return ma_data_source_get_data_format(&pDataStream->decoder, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  57591. }
  57592. MA_API ma_result ma_resource_manager_data_stream_get_cursor_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pCursor)
  57593. {
  57594. ma_result result;
  57595. if (pCursor == NULL) {
  57596. return MA_INVALID_ARGS;
  57597. }
  57598. *pCursor = 0;
  57599. /* We cannot be using the data source after it's been uninitialized. */
  57600. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57601. if (pDataStream == NULL) {
  57602. return MA_INVALID_ARGS;
  57603. }
  57604. /*
  57605. If the stream is in an erroneous state we need to return an invalid operation. We can allow
  57606. this to be called when the data stream is in a busy state because the caller may have asked
  57607. for an initial seek position and it's convenient to return that as the cursor position.
  57608. */
  57609. result = ma_resource_manager_data_stream_result(pDataStream);
  57610. if (result != MA_SUCCESS && result != MA_BUSY) {
  57611. return MA_INVALID_OPERATION;
  57612. }
  57613. *pCursor = c89atomic_load_64(&pDataStream->absoluteCursor);
  57614. return MA_SUCCESS;
  57615. }
  57616. MA_API ma_result ma_resource_manager_data_stream_get_length_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pLength)
  57617. {
  57618. ma_result streamResult;
  57619. if (pLength == NULL) {
  57620. return MA_INVALID_ARGS;
  57621. }
  57622. *pLength = 0;
  57623. streamResult = ma_resource_manager_data_stream_result(pDataStream);
  57624. /* We cannot be using the data source after it's been uninitialized. */
  57625. MA_ASSERT(streamResult != MA_UNAVAILABLE);
  57626. if (pDataStream == NULL) {
  57627. return MA_INVALID_ARGS;
  57628. }
  57629. if (streamResult != MA_SUCCESS) {
  57630. return streamResult;
  57631. }
  57632. /*
  57633. We most definitely do not want to be calling ma_decoder_get_length_in_pcm_frames() directly. Instead we want to use a cached value that we
  57634. calculated when we initialized it on the job thread.
  57635. */
  57636. *pLength = pDataStream->totalLengthInPCMFrames;
  57637. if (*pLength == 0) {
  57638. return MA_NOT_IMPLEMENTED; /* Some decoders may not have a known length. */
  57639. }
  57640. return MA_SUCCESS;
  57641. }
  57642. MA_API ma_result ma_resource_manager_data_stream_result(const ma_resource_manager_data_stream* pDataStream)
  57643. {
  57644. if (pDataStream == NULL) {
  57645. return MA_INVALID_ARGS;
  57646. }
  57647. return (ma_result)c89atomic_load_i32(&pDataStream->result);
  57648. }
  57649. MA_API ma_result ma_resource_manager_data_stream_set_looping(ma_resource_manager_data_stream* pDataStream, ma_bool32 isLooping)
  57650. {
  57651. return ma_data_source_set_looping(pDataStream, isLooping);
  57652. }
  57653. MA_API ma_bool32 ma_resource_manager_data_stream_is_looping(const ma_resource_manager_data_stream* pDataStream)
  57654. {
  57655. if (pDataStream == NULL) {
  57656. return MA_FALSE;
  57657. }
  57658. return c89atomic_load_32((ma_bool32*)&pDataStream->isLooping); /* Naughty const-cast. Value won't change from here in practice (maybe from another thread). */
  57659. }
  57660. MA_API ma_result ma_resource_manager_data_stream_get_available_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pAvailableFrames)
  57661. {
  57662. ma_uint32 pageIndex0;
  57663. ma_uint32 pageIndex1;
  57664. ma_uint32 relativeCursor;
  57665. ma_uint64 availableFrames;
  57666. if (pAvailableFrames == NULL) {
  57667. return MA_INVALID_ARGS;
  57668. }
  57669. *pAvailableFrames = 0;
  57670. if (pDataStream == NULL) {
  57671. return MA_INVALID_ARGS;
  57672. }
  57673. pageIndex0 = pDataStream->currentPageIndex;
  57674. pageIndex1 = (pDataStream->currentPageIndex + 1) & 0x01;
  57675. relativeCursor = pDataStream->relativeCursor;
  57676. availableFrames = 0;
  57677. if (c89atomic_load_32(&pDataStream->isPageValid[pageIndex0])) {
  57678. availableFrames += c89atomic_load_32(&pDataStream->pageFrameCount[pageIndex0]) - relativeCursor;
  57679. if (c89atomic_load_32(&pDataStream->isPageValid[pageIndex1])) {
  57680. availableFrames += c89atomic_load_32(&pDataStream->pageFrameCount[pageIndex1]);
  57681. }
  57682. }
  57683. *pAvailableFrames = availableFrames;
  57684. return MA_SUCCESS;
  57685. }
  57686. static ma_result ma_resource_manager_data_source_preinit(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_source* pDataSource)
  57687. {
  57688. if (pDataSource == NULL) {
  57689. return MA_INVALID_ARGS;
  57690. }
  57691. MA_ZERO_OBJECT(pDataSource);
  57692. if (pConfig == NULL) {
  57693. return MA_INVALID_ARGS;
  57694. }
  57695. if (pResourceManager == NULL) {
  57696. return MA_INVALID_ARGS;
  57697. }
  57698. pDataSource->flags = pConfig->flags;
  57699. return MA_SUCCESS;
  57700. }
  57701. MA_API ma_result ma_resource_manager_data_source_init_ex(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source_config* pConfig, ma_resource_manager_data_source* pDataSource)
  57702. {
  57703. ma_result result;
  57704. result = ma_resource_manager_data_source_preinit(pResourceManager, pConfig, pDataSource);
  57705. if (result != MA_SUCCESS) {
  57706. return result;
  57707. }
  57708. /* The data source itself is just a data stream or a data buffer. */
  57709. if ((pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57710. return ma_resource_manager_data_stream_init_ex(pResourceManager, pConfig, &pDataSource->backend.stream);
  57711. } else {
  57712. return ma_resource_manager_data_buffer_init_ex(pResourceManager, pConfig, &pDataSource->backend.buffer);
  57713. }
  57714. }
  57715. MA_API ma_result ma_resource_manager_data_source_init(ma_resource_manager* pResourceManager, const char* pName, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_source* pDataSource)
  57716. {
  57717. ma_resource_manager_data_source_config config;
  57718. config = ma_resource_manager_data_source_config_init();
  57719. config.pFilePath = pName;
  57720. config.flags = flags;
  57721. config.pNotifications = pNotifications;
  57722. return ma_resource_manager_data_source_init_ex(pResourceManager, &config, pDataSource);
  57723. }
  57724. MA_API ma_result ma_resource_manager_data_source_init_w(ma_resource_manager* pResourceManager, const wchar_t* pName, ma_uint32 flags, const ma_resource_manager_pipeline_notifications* pNotifications, ma_resource_manager_data_source* pDataSource)
  57725. {
  57726. ma_resource_manager_data_source_config config;
  57727. config = ma_resource_manager_data_source_config_init();
  57728. config.pFilePathW = pName;
  57729. config.flags = flags;
  57730. config.pNotifications = pNotifications;
  57731. return ma_resource_manager_data_source_init_ex(pResourceManager, &config, pDataSource);
  57732. }
  57733. MA_API ma_result ma_resource_manager_data_source_init_copy(ma_resource_manager* pResourceManager, const ma_resource_manager_data_source* pExistingDataSource, ma_resource_manager_data_source* pDataSource)
  57734. {
  57735. ma_result result;
  57736. ma_resource_manager_data_source_config config;
  57737. if (pExistingDataSource == NULL) {
  57738. return MA_INVALID_ARGS;
  57739. }
  57740. config = ma_resource_manager_data_source_config_init();
  57741. config.flags = pExistingDataSource->flags;
  57742. result = ma_resource_manager_data_source_preinit(pResourceManager, &config, pDataSource);
  57743. if (result != MA_SUCCESS) {
  57744. return result;
  57745. }
  57746. /* Copying can only be done from data buffers. Streams cannot be copied. */
  57747. if ((pExistingDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57748. return MA_INVALID_OPERATION;
  57749. }
  57750. return ma_resource_manager_data_buffer_init_copy(pResourceManager, &pExistingDataSource->backend.buffer, &pDataSource->backend.buffer);
  57751. }
  57752. MA_API ma_result ma_resource_manager_data_source_uninit(ma_resource_manager_data_source* pDataSource)
  57753. {
  57754. if (pDataSource == NULL) {
  57755. return MA_INVALID_ARGS;
  57756. }
  57757. /* All we need to is uninitialize the underlying data buffer or data stream. */
  57758. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57759. return ma_resource_manager_data_stream_uninit(&pDataSource->backend.stream);
  57760. } else {
  57761. return ma_resource_manager_data_buffer_uninit(&pDataSource->backend.buffer);
  57762. }
  57763. }
  57764. MA_API ma_result ma_resource_manager_data_source_read_pcm_frames(ma_resource_manager_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  57765. {
  57766. /* Safety. */
  57767. if (pFramesRead != NULL) {
  57768. *pFramesRead = 0;
  57769. }
  57770. if (pDataSource == NULL) {
  57771. return MA_INVALID_ARGS;
  57772. }
  57773. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57774. return ma_resource_manager_data_stream_read_pcm_frames(&pDataSource->backend.stream, pFramesOut, frameCount, pFramesRead);
  57775. } else {
  57776. return ma_resource_manager_data_buffer_read_pcm_frames(&pDataSource->backend.buffer, pFramesOut, frameCount, pFramesRead);
  57777. }
  57778. }
  57779. MA_API ma_result ma_resource_manager_data_source_seek_to_pcm_frame(ma_resource_manager_data_source* pDataSource, ma_uint64 frameIndex)
  57780. {
  57781. if (pDataSource == NULL) {
  57782. return MA_INVALID_ARGS;
  57783. }
  57784. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57785. return ma_resource_manager_data_stream_seek_to_pcm_frame(&pDataSource->backend.stream, frameIndex);
  57786. } else {
  57787. return ma_resource_manager_data_buffer_seek_to_pcm_frame(&pDataSource->backend.buffer, frameIndex);
  57788. }
  57789. }
  57790. MA_API ma_result ma_resource_manager_data_source_map(ma_resource_manager_data_source* pDataSource, void** ppFramesOut, ma_uint64* pFrameCount)
  57791. {
  57792. if (pDataSource == NULL) {
  57793. return MA_INVALID_ARGS;
  57794. }
  57795. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57796. return ma_resource_manager_data_stream_map(&pDataSource->backend.stream, ppFramesOut, pFrameCount);
  57797. } else {
  57798. return MA_NOT_IMPLEMENTED; /* Mapping not supported with data buffers. */
  57799. }
  57800. }
  57801. MA_API ma_result ma_resource_manager_data_source_unmap(ma_resource_manager_data_source* pDataSource, ma_uint64 frameCount)
  57802. {
  57803. if (pDataSource == NULL) {
  57804. return MA_INVALID_ARGS;
  57805. }
  57806. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57807. return ma_resource_manager_data_stream_unmap(&pDataSource->backend.stream, frameCount);
  57808. } else {
  57809. return MA_NOT_IMPLEMENTED; /* Mapping not supported with data buffers. */
  57810. }
  57811. }
  57812. MA_API ma_result ma_resource_manager_data_source_get_data_format(ma_resource_manager_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  57813. {
  57814. if (pDataSource == NULL) {
  57815. return MA_INVALID_ARGS;
  57816. }
  57817. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57818. return ma_resource_manager_data_stream_get_data_format(&pDataSource->backend.stream, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  57819. } else {
  57820. return ma_resource_manager_data_buffer_get_data_format(&pDataSource->backend.buffer, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  57821. }
  57822. }
  57823. MA_API ma_result ma_resource_manager_data_source_get_cursor_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pCursor)
  57824. {
  57825. if (pDataSource == NULL) {
  57826. return MA_INVALID_ARGS;
  57827. }
  57828. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57829. return ma_resource_manager_data_stream_get_cursor_in_pcm_frames(&pDataSource->backend.stream, pCursor);
  57830. } else {
  57831. return ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(&pDataSource->backend.buffer, pCursor);
  57832. }
  57833. }
  57834. MA_API ma_result ma_resource_manager_data_source_get_length_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pLength)
  57835. {
  57836. if (pDataSource == NULL) {
  57837. return MA_INVALID_ARGS;
  57838. }
  57839. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57840. return ma_resource_manager_data_stream_get_length_in_pcm_frames(&pDataSource->backend.stream, pLength);
  57841. } else {
  57842. return ma_resource_manager_data_buffer_get_length_in_pcm_frames(&pDataSource->backend.buffer, pLength);
  57843. }
  57844. }
  57845. MA_API ma_result ma_resource_manager_data_source_result(const ma_resource_manager_data_source* pDataSource)
  57846. {
  57847. if (pDataSource == NULL) {
  57848. return MA_INVALID_ARGS;
  57849. }
  57850. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57851. return ma_resource_manager_data_stream_result(&pDataSource->backend.stream);
  57852. } else {
  57853. return ma_resource_manager_data_buffer_result(&pDataSource->backend.buffer);
  57854. }
  57855. }
  57856. MA_API ma_result ma_resource_manager_data_source_set_looping(ma_resource_manager_data_source* pDataSource, ma_bool32 isLooping)
  57857. {
  57858. if (pDataSource == NULL) {
  57859. return MA_INVALID_ARGS;
  57860. }
  57861. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57862. return ma_resource_manager_data_stream_set_looping(&pDataSource->backend.stream, isLooping);
  57863. } else {
  57864. return ma_resource_manager_data_buffer_set_looping(&pDataSource->backend.buffer, isLooping);
  57865. }
  57866. }
  57867. MA_API ma_bool32 ma_resource_manager_data_source_is_looping(const ma_resource_manager_data_source* pDataSource)
  57868. {
  57869. if (pDataSource == NULL) {
  57870. return MA_FALSE;
  57871. }
  57872. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57873. return ma_resource_manager_data_stream_is_looping(&pDataSource->backend.stream);
  57874. } else {
  57875. return ma_resource_manager_data_buffer_is_looping(&pDataSource->backend.buffer);
  57876. }
  57877. }
  57878. MA_API ma_result ma_resource_manager_data_source_get_available_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pAvailableFrames)
  57879. {
  57880. if (pAvailableFrames == NULL) {
  57881. return MA_INVALID_ARGS;
  57882. }
  57883. *pAvailableFrames = 0;
  57884. if (pDataSource == NULL) {
  57885. return MA_INVALID_ARGS;
  57886. }
  57887. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  57888. return ma_resource_manager_data_stream_get_available_frames(&pDataSource->backend.stream, pAvailableFrames);
  57889. } else {
  57890. return ma_resource_manager_data_buffer_get_available_frames(&pDataSource->backend.buffer, pAvailableFrames);
  57891. }
  57892. }
  57893. MA_API ma_result ma_resource_manager_post_job(ma_resource_manager* pResourceManager, const ma_job* pJob)
  57894. {
  57895. if (pResourceManager == NULL) {
  57896. return MA_INVALID_ARGS;
  57897. }
  57898. return ma_job_queue_post(&pResourceManager->jobQueue, pJob);
  57899. }
  57900. MA_API ma_result ma_resource_manager_post_job_quit(ma_resource_manager* pResourceManager)
  57901. {
  57902. ma_job job = ma_job_init(MA_JOB_TYPE_QUIT);
  57903. return ma_resource_manager_post_job(pResourceManager, &job);
  57904. }
  57905. MA_API ma_result ma_resource_manager_next_job(ma_resource_manager* pResourceManager, ma_job* pJob)
  57906. {
  57907. if (pResourceManager == NULL) {
  57908. return MA_INVALID_ARGS;
  57909. }
  57910. return ma_job_queue_next(&pResourceManager->jobQueue, pJob);
  57911. }
  57912. static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob)
  57913. {
  57914. ma_result result = MA_SUCCESS;
  57915. ma_resource_manager* pResourceManager;
  57916. ma_resource_manager_data_buffer_node* pDataBufferNode;
  57917. MA_ASSERT(pJob != NULL);
  57918. pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.loadDataBufferNode.pResourceManager;
  57919. MA_ASSERT(pResourceManager != NULL);
  57920. pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.loadDataBufferNode.pDataBufferNode;
  57921. MA_ASSERT(pDataBufferNode != NULL);
  57922. MA_ASSERT(pDataBufferNode->isDataOwnedByResourceManager == MA_TRUE); /* The data should always be owned by the resource manager. */
  57923. /* The data buffer is not getting deleted, but we may be getting executed out of order. If so, we need to push the job back onto the queue and return. */
  57924. if (pJob->order != c89atomic_load_32(&pDataBufferNode->executionPointer)) {
  57925. return ma_resource_manager_post_job(pResourceManager, pJob); /* Attempting to execute out of order. Probably interleaved with a MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER job. */
  57926. }
  57927. /* First thing we need to do is check whether or not the data buffer is getting deleted. If so we just abort. */
  57928. if (ma_resource_manager_data_buffer_node_result(pDataBufferNode) != MA_BUSY) {
  57929. result = ma_resource_manager_data_buffer_node_result(pDataBufferNode); /* The data buffer may be getting deleted before it's even been loaded. */
  57930. goto done;
  57931. }
  57932. /*
  57933. We're ready to start loading. Essentially what we're doing here is initializing the data supply
  57934. of the node. Once this is complete, data buffers can have their connectors initialized which
  57935. will allow then to have audio data read from them.
  57936. Note that when the data supply type has been moved away from "unknown", that is when other threads
  57937. will determine that the node is available for data delivery and the data buffer connectors can be
  57938. initialized. Therefore, it's important that it is set after the data supply has been initialized.
  57939. */
  57940. if ((pJob->data.resourceManager.loadDataBufferNode.flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE) != 0) {
  57941. /*
  57942. Decoding. This is the complex case because we're not going to be doing the entire decoding
  57943. process here. Instead it's going to be split of multiple jobs and loaded in pages. The
  57944. reason for this is to evenly distribute decoding time across multiple sounds, rather than
  57945. having one huge sound hog all the available processing resources.
  57946. The first thing we do is initialize a decoder. This is allocated on the heap and is passed
  57947. around to the paging jobs. When the last paging job has completed it's processing, it'll
  57948. free the decoder for us.
  57949. This job does not do any actual decoding. It instead just posts a PAGE_DATA_BUFFER_NODE job
  57950. which is where the actual decoding work will be done. However, once this job is complete,
  57951. the node will be in a state where data buffer connectors can be initialized.
  57952. */
  57953. ma_decoder* pDecoder; /* <-- Free'd on the last page decode. */
  57954. ma_job pageDataBufferNodeJob;
  57955. /* Allocate the decoder by initializing a decoded data supply. */
  57956. result = ma_resource_manager_data_buffer_node_init_supply_decoded(pResourceManager, pDataBufferNode, pJob->data.resourceManager.loadDataBufferNode.pFilePath, pJob->data.resourceManager.loadDataBufferNode.pFilePathW, pJob->data.resourceManager.loadDataBufferNode.flags, &pDecoder);
  57957. /*
  57958. Don't ever propagate an MA_BUSY result code or else the resource manager will think the
  57959. node is just busy decoding rather than in an error state. This should never happen, but
  57960. including this logic for safety just in case.
  57961. */
  57962. if (result == MA_BUSY) {
  57963. result = MA_ERROR;
  57964. }
  57965. if (result != MA_SUCCESS) {
  57966. if (pJob->data.resourceManager.loadDataBufferNode.pFilePath != NULL) {
  57967. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to initialize data supply for \"%s\". %s.\n", pJob->data.resourceManager.loadDataBufferNode.pFilePath, ma_result_description(result));
  57968. } else {
  57969. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
  57970. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_WARNING, "Failed to initialize data supply for \"%ls\", %s.\n", pJob->data.resourceManager.loadDataBufferNode.pFilePathW, ma_result_description(result));
  57971. #endif
  57972. }
  57973. goto done;
  57974. }
  57975. /*
  57976. At this point the node's data supply is initialized and other threads can start initializing
  57977. their data buffer connectors. However, no data will actually be available until we start to
  57978. actually decode it. To do this, we need to post a paging job which is where the decoding
  57979. work is done.
  57980. Note that if an error occurred at an earlier point, this section will have been skipped.
  57981. */
  57982. pageDataBufferNodeJob = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE);
  57983. pageDataBufferNodeJob.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode);
  57984. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pResourceManager = pResourceManager;
  57985. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDataBufferNode = pDataBufferNode;
  57986. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDecoder = pDecoder;
  57987. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDoneNotification = pJob->data.resourceManager.loadDataBufferNode.pDoneNotification;
  57988. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDoneFence = pJob->data.resourceManager.loadDataBufferNode.pDoneFence;
  57989. /* The job has been set up so it can now be posted. */
  57990. result = ma_resource_manager_post_job(pResourceManager, &pageDataBufferNodeJob);
  57991. /*
  57992. When we get here, we want to make sure the result code is set to MA_BUSY. The reason for
  57993. this is that the result will be copied over to the node's internal result variable. In
  57994. this case, since the decoding is still in-progress, we need to make sure the result code
  57995. is set to MA_BUSY.
  57996. */
  57997. if (result != MA_SUCCESS) {
  57998. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to post MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE job. %s\n", ma_result_description(result));
  57999. ma_decoder_uninit(pDecoder);
  58000. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  58001. } else {
  58002. result = MA_BUSY;
  58003. }
  58004. } else {
  58005. /* No decoding. This is the simple case. We need only read the file content into memory and we're done. */
  58006. result = ma_resource_manager_data_buffer_node_init_supply_encoded(pResourceManager, pDataBufferNode, pJob->data.resourceManager.loadDataBufferNode.pFilePath, pJob->data.resourceManager.loadDataBufferNode.pFilePathW);
  58007. }
  58008. done:
  58009. /* File paths are no longer needed. */
  58010. ma_free(pJob->data.resourceManager.loadDataBufferNode.pFilePath, &pResourceManager->config.allocationCallbacks);
  58011. ma_free(pJob->data.resourceManager.loadDataBufferNode.pFilePathW, &pResourceManager->config.allocationCallbacks);
  58012. /*
  58013. We need to set the result to at the very end to ensure no other threads try reading the data before we've fully initialized the object. Other threads
  58014. are going to be inspecting this variable to determine whether or not they're ready to read data. We can only change the result if it's set to MA_BUSY
  58015. because otherwise we may be changing away from an error code which would be bad. An example is if the application creates a data buffer, but then
  58016. immediately deletes it before we've got to this point. In this case, pDataBuffer->result will be MA_UNAVAILABLE, and setting it to MA_SUCCESS or any
  58017. other error code would cause the buffer to look like it's in a state that it's not.
  58018. */
  58019. c89atomic_compare_and_swap_i32(&pDataBufferNode->result, MA_BUSY, result);
  58020. /* At this point initialization is complete and we can signal the notification if any. */
  58021. if (pJob->data.resourceManager.loadDataBufferNode.pInitNotification != NULL) {
  58022. ma_async_notification_signal(pJob->data.resourceManager.loadDataBufferNode.pInitNotification);
  58023. }
  58024. if (pJob->data.resourceManager.loadDataBufferNode.pInitFence != NULL) {
  58025. ma_fence_release(pJob->data.resourceManager.loadDataBufferNode.pInitFence);
  58026. }
  58027. /* If we have a success result it means we've fully loaded the buffer. This will happen in the non-decoding case. */
  58028. if (result != MA_BUSY) {
  58029. if (pJob->data.resourceManager.loadDataBufferNode.pDoneNotification != NULL) {
  58030. ma_async_notification_signal(pJob->data.resourceManager.loadDataBufferNode.pDoneNotification);
  58031. }
  58032. if (pJob->data.resourceManager.loadDataBufferNode.pDoneFence != NULL) {
  58033. ma_fence_release(pJob->data.resourceManager.loadDataBufferNode.pDoneFence);
  58034. }
  58035. }
  58036. /* Increment the node's execution pointer so that the next jobs can be processed. This is how we keep decoding of pages in-order. */
  58037. c89atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1);
  58038. return result;
  58039. }
  58040. static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob)
  58041. {
  58042. ma_resource_manager* pResourceManager;
  58043. ma_resource_manager_data_buffer_node* pDataBufferNode;
  58044. MA_ASSERT(pJob != NULL);
  58045. pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.freeDataBufferNode.pResourceManager;
  58046. MA_ASSERT(pResourceManager != NULL);
  58047. pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.freeDataBufferNode.pDataBufferNode;
  58048. MA_ASSERT(pDataBufferNode != NULL);
  58049. if (pJob->order != c89atomic_load_32(&pDataBufferNode->executionPointer)) {
  58050. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58051. }
  58052. ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode);
  58053. /* The event needs to be signalled last. */
  58054. if (pJob->data.resourceManager.freeDataBufferNode.pDoneNotification != NULL) {
  58055. ma_async_notification_signal(pJob->data.resourceManager.freeDataBufferNode.pDoneNotification);
  58056. }
  58057. if (pJob->data.resourceManager.freeDataBufferNode.pDoneFence != NULL) {
  58058. ma_fence_release(pJob->data.resourceManager.freeDataBufferNode.pDoneFence);
  58059. }
  58060. c89atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1);
  58061. return MA_SUCCESS;
  58062. }
  58063. static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob)
  58064. {
  58065. ma_result result = MA_SUCCESS;
  58066. ma_resource_manager* pResourceManager;
  58067. ma_resource_manager_data_buffer_node* pDataBufferNode;
  58068. MA_ASSERT(pJob != NULL);
  58069. pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.pageDataBufferNode.pResourceManager;
  58070. MA_ASSERT(pResourceManager != NULL);
  58071. pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.pageDataBufferNode.pDataBufferNode;
  58072. MA_ASSERT(pDataBufferNode != NULL);
  58073. if (pJob->order != c89atomic_load_32(&pDataBufferNode->executionPointer)) {
  58074. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58075. }
  58076. /* Don't do any more decoding if the data buffer has started the uninitialization process. */
  58077. result = ma_resource_manager_data_buffer_node_result(pDataBufferNode);
  58078. if (result != MA_BUSY) {
  58079. goto done;
  58080. }
  58081. /* We're ready to decode the next page. */
  58082. result = ma_resource_manager_data_buffer_node_decode_next_page(pResourceManager, pDataBufferNode, (ma_decoder*)pJob->data.resourceManager.pageDataBufferNode.pDecoder);
  58083. /*
  58084. If we have a success code by this point, we want to post another job. We're going to set the
  58085. result back to MA_BUSY to make it clear that there's still more to load.
  58086. */
  58087. if (result == MA_SUCCESS) {
  58088. ma_job newJob;
  58089. newJob = *pJob; /* Everything is the same as the input job, except the execution order. */
  58090. newJob.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode); /* We need a fresh execution order. */
  58091. result = ma_resource_manager_post_job(pResourceManager, &newJob);
  58092. /* Since the sound isn't yet fully decoded we want the status to be set to busy. */
  58093. if (result == MA_SUCCESS) {
  58094. result = MA_BUSY;
  58095. }
  58096. }
  58097. done:
  58098. /* If there's still more to decode the result will be set to MA_BUSY. Otherwise we can free the decoder. */
  58099. if (result != MA_BUSY) {
  58100. ma_decoder_uninit((ma_decoder*)pJob->data.resourceManager.pageDataBufferNode.pDecoder);
  58101. ma_free(pJob->data.resourceManager.pageDataBufferNode.pDecoder, &pResourceManager->config.allocationCallbacks);
  58102. }
  58103. /* If we reached the end we need to treat it as successful. */
  58104. if (result == MA_AT_END) {
  58105. result = MA_SUCCESS;
  58106. }
  58107. /* Make sure we set the result of node in case some error occurred. */
  58108. c89atomic_compare_and_swap_i32(&pDataBufferNode->result, MA_BUSY, result);
  58109. /* Signal the notification after setting the result in case the notification callback wants to inspect the result code. */
  58110. if (result != MA_BUSY) {
  58111. if (pJob->data.resourceManager.pageDataBufferNode.pDoneNotification != NULL) {
  58112. ma_async_notification_signal(pJob->data.resourceManager.pageDataBufferNode.pDoneNotification);
  58113. }
  58114. if (pJob->data.resourceManager.pageDataBufferNode.pDoneFence != NULL) {
  58115. ma_fence_release(pJob->data.resourceManager.pageDataBufferNode.pDoneFence);
  58116. }
  58117. }
  58118. c89atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1);
  58119. return result;
  58120. }
  58121. static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob)
  58122. {
  58123. ma_result result = MA_SUCCESS;
  58124. ma_resource_manager* pResourceManager;
  58125. ma_resource_manager_data_buffer* pDataBuffer;
  58126. ma_resource_manager_data_supply_type dataSupplyType = ma_resource_manager_data_supply_type_unknown;
  58127. ma_bool32 isConnectorInitialized = MA_FALSE;
  58128. /*
  58129. All we're doing here is checking if the node has finished loading. If not, we just re-post the job
  58130. and keep waiting. Otherwise we increment the execution counter and set the buffer's result code.
  58131. */
  58132. MA_ASSERT(pJob != NULL);
  58133. pDataBuffer = (ma_resource_manager_data_buffer*)pJob->data.resourceManager.loadDataBuffer.pDataBuffer;
  58134. MA_ASSERT(pDataBuffer != NULL);
  58135. pResourceManager = pDataBuffer->pResourceManager;
  58136. if (pJob->order != c89atomic_load_32(&pDataBuffer->executionPointer)) {
  58137. return ma_resource_manager_post_job(pResourceManager, pJob); /* Attempting to execute out of order. Probably interleaved with a MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER job. */
  58138. }
  58139. /*
  58140. First thing we need to do is check whether or not the data buffer is getting deleted. If so we
  58141. just abort, but making sure we increment the execution pointer.
  58142. */
  58143. result = ma_resource_manager_data_buffer_result(pDataBuffer);
  58144. if (result != MA_BUSY) {
  58145. goto done; /* <-- This will ensure the exucution pointer is incremented. */
  58146. } else {
  58147. result = MA_SUCCESS; /* <-- Make sure this is reset. */
  58148. }
  58149. /* Try initializing the connector if we haven't already. */
  58150. isConnectorInitialized = ma_resource_manager_data_buffer_has_connector(pDataBuffer);
  58151. if (isConnectorInitialized == MA_FALSE) {
  58152. dataSupplyType = ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode);
  58153. if (dataSupplyType != ma_resource_manager_data_supply_type_unknown) {
  58154. /* We can now initialize the connector. If this fails, we need to abort. It's very rare for this to fail. */
  58155. ma_resource_manager_data_source_config dataSourceConfig; /* For setting initial looping state and range. */
  58156. dataSourceConfig = ma_resource_manager_data_source_config_init();
  58157. dataSourceConfig.rangeBegInPCMFrames = pJob->data.resourceManager.loadDataBuffer.rangeBegInPCMFrames;
  58158. dataSourceConfig.rangeEndInPCMFrames = pJob->data.resourceManager.loadDataBuffer.rangeEndInPCMFrames;
  58159. dataSourceConfig.loopPointBegInPCMFrames = pJob->data.resourceManager.loadDataBuffer.loopPointBegInPCMFrames;
  58160. dataSourceConfig.loopPointEndInPCMFrames = pJob->data.resourceManager.loadDataBuffer.loopPointEndInPCMFrames;
  58161. dataSourceConfig.isLooping = pJob->data.resourceManager.loadDataBuffer.isLooping;
  58162. result = ma_resource_manager_data_buffer_init_connector(pDataBuffer, &dataSourceConfig, pJob->data.resourceManager.loadDataBuffer.pInitNotification, pJob->data.resourceManager.loadDataBuffer.pInitFence);
  58163. if (result != MA_SUCCESS) {
  58164. ma_log_postf(ma_resource_manager_get_log(pResourceManager), MA_LOG_LEVEL_ERROR, "Failed to initialize connector for data buffer. %s.\n", ma_result_description(result));
  58165. goto done;
  58166. }
  58167. } else {
  58168. /* Don't have a known data supply type. Most likely the data buffer node is still loading, but it could be that an error occurred. */
  58169. }
  58170. } else {
  58171. /* The connector is already initialized. Nothing to do here. */
  58172. }
  58173. /*
  58174. If the data node is still loading, we need to repost the job and *not* increment the execution
  58175. pointer (i.e. we need to not fall through to the "done" label).
  58176. There is a hole between here and the where the data connector is initialized where the data
  58177. buffer node may have finished initializing. We need to check for this by checking the result of
  58178. the data buffer node and whether or not we had an unknown data supply type at the time of
  58179. trying to initialize the data connector.
  58180. */
  58181. result = ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode);
  58182. if (result == MA_BUSY || (result == MA_SUCCESS && isConnectorInitialized == MA_FALSE && dataSupplyType == ma_resource_manager_data_supply_type_unknown)) {
  58183. return ma_resource_manager_post_job(pResourceManager, pJob);
  58184. }
  58185. done:
  58186. /* Only move away from a busy code so that we don't trash any existing error codes. */
  58187. c89atomic_compare_and_swap_i32(&pDataBuffer->result, MA_BUSY, result);
  58188. /* Only signal the other threads after the result has been set just for cleanliness sake. */
  58189. if (pJob->data.resourceManager.loadDataBuffer.pDoneNotification != NULL) {
  58190. ma_async_notification_signal(pJob->data.resourceManager.loadDataBuffer.pDoneNotification);
  58191. }
  58192. if (pJob->data.resourceManager.loadDataBuffer.pDoneFence != NULL) {
  58193. ma_fence_release(pJob->data.resourceManager.loadDataBuffer.pDoneFence);
  58194. }
  58195. /*
  58196. If at this point the data buffer has not had it's connector initialized, it means the
  58197. notification event was never signalled which means we need to signal it here.
  58198. */
  58199. if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE && result != MA_SUCCESS) {
  58200. if (pJob->data.resourceManager.loadDataBuffer.pInitNotification != NULL) {
  58201. ma_async_notification_signal(pJob->data.resourceManager.loadDataBuffer.pInitNotification);
  58202. }
  58203. if (pJob->data.resourceManager.loadDataBuffer.pInitFence != NULL) {
  58204. ma_fence_release(pJob->data.resourceManager.loadDataBuffer.pInitFence);
  58205. }
  58206. }
  58207. c89atomic_fetch_add_32(&pDataBuffer->executionPointer, 1);
  58208. return result;
  58209. }
  58210. static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob)
  58211. {
  58212. ma_resource_manager* pResourceManager;
  58213. ma_resource_manager_data_buffer* pDataBuffer;
  58214. MA_ASSERT(pJob != NULL);
  58215. pDataBuffer = (ma_resource_manager_data_buffer*)pJob->data.resourceManager.freeDataBuffer.pDataBuffer;
  58216. MA_ASSERT(pDataBuffer != NULL);
  58217. pResourceManager = pDataBuffer->pResourceManager;
  58218. if (pJob->order != c89atomic_load_32(&pDataBuffer->executionPointer)) {
  58219. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58220. }
  58221. ma_resource_manager_data_buffer_uninit_internal(pDataBuffer);
  58222. /* The event needs to be signalled last. */
  58223. if (pJob->data.resourceManager.freeDataBuffer.pDoneNotification != NULL) {
  58224. ma_async_notification_signal(pJob->data.resourceManager.freeDataBuffer.pDoneNotification);
  58225. }
  58226. if (pJob->data.resourceManager.freeDataBuffer.pDoneFence != NULL) {
  58227. ma_fence_release(pJob->data.resourceManager.freeDataBuffer.pDoneFence);
  58228. }
  58229. c89atomic_fetch_add_32(&pDataBuffer->executionPointer, 1);
  58230. return MA_SUCCESS;
  58231. }
  58232. static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob)
  58233. {
  58234. ma_result result = MA_SUCCESS;
  58235. ma_decoder_config decoderConfig;
  58236. ma_uint32 pageBufferSizeInBytes;
  58237. ma_resource_manager* pResourceManager;
  58238. ma_resource_manager_data_stream* pDataStream;
  58239. MA_ASSERT(pJob != NULL);
  58240. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.loadDataStream.pDataStream;
  58241. MA_ASSERT(pDataStream != NULL);
  58242. pResourceManager = pDataStream->pResourceManager;
  58243. if (pJob->order != c89atomic_load_32(&pDataStream->executionPointer)) {
  58244. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58245. }
  58246. if (ma_resource_manager_data_stream_result(pDataStream) != MA_BUSY) {
  58247. result = MA_INVALID_OPERATION; /* Most likely the data stream is being uninitialized. */
  58248. goto done;
  58249. }
  58250. /* We need to initialize the decoder first so we can determine the size of the pages. */
  58251. decoderConfig = ma_resource_manager__init_decoder_config(pResourceManager);
  58252. if (pJob->data.resourceManager.loadDataStream.pFilePath != NULL) {
  58253. result = ma_decoder_init_vfs(pResourceManager->config.pVFS, pJob->data.resourceManager.loadDataStream.pFilePath, &decoderConfig, &pDataStream->decoder);
  58254. } else {
  58255. result = ma_decoder_init_vfs_w(pResourceManager->config.pVFS, pJob->data.resourceManager.loadDataStream.pFilePathW, &decoderConfig, &pDataStream->decoder);
  58256. }
  58257. if (result != MA_SUCCESS) {
  58258. goto done;
  58259. }
  58260. /* Retrieve the total length of the file before marking the decoder as loaded. */
  58261. if ((pDataStream->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH) == 0) {
  58262. result = ma_decoder_get_length_in_pcm_frames(&pDataStream->decoder, &pDataStream->totalLengthInPCMFrames);
  58263. if (result != MA_SUCCESS) {
  58264. goto done; /* Failed to retrieve the length. */
  58265. }
  58266. } else {
  58267. pDataStream->totalLengthInPCMFrames = 0;
  58268. }
  58269. /*
  58270. Only mark the decoder as initialized when the length of the decoder has been retrieved because that can possibly require a scan over the whole file
  58271. and we don't want to have another thread trying to access the decoder while it's scanning.
  58272. */
  58273. pDataStream->isDecoderInitialized = MA_TRUE;
  58274. /* We have the decoder so we can now initialize our page buffer. */
  58275. pageBufferSizeInBytes = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream) * 2 * ma_get_bytes_per_frame(pDataStream->decoder.outputFormat, pDataStream->decoder.outputChannels);
  58276. pDataStream->pPageData = ma_malloc(pageBufferSizeInBytes, &pResourceManager->config.allocationCallbacks);
  58277. if (pDataStream->pPageData == NULL) {
  58278. ma_decoder_uninit(&pDataStream->decoder);
  58279. result = MA_OUT_OF_MEMORY;
  58280. goto done;
  58281. }
  58282. /* Seek to our initial seek point before filling the initial pages. */
  58283. ma_decoder_seek_to_pcm_frame(&pDataStream->decoder, pJob->data.resourceManager.loadDataStream.initialSeekPoint);
  58284. /* We have our decoder and our page buffer, so now we need to fill our pages. */
  58285. ma_resource_manager_data_stream_fill_pages(pDataStream);
  58286. /* And now we're done. We want to make sure the result is MA_SUCCESS. */
  58287. result = MA_SUCCESS;
  58288. done:
  58289. ma_free(pJob->data.resourceManager.loadDataStream.pFilePath, &pResourceManager->config.allocationCallbacks);
  58290. ma_free(pJob->data.resourceManager.loadDataStream.pFilePathW, &pResourceManager->config.allocationCallbacks);
  58291. /* We can only change the status away from MA_BUSY. If it's set to anything else it means an error has occurred somewhere or the uninitialization process has started (most likely). */
  58292. c89atomic_compare_and_swap_i32(&pDataStream->result, MA_BUSY, result);
  58293. /* Only signal the other threads after the result has been set just for cleanliness sake. */
  58294. if (pJob->data.resourceManager.loadDataStream.pInitNotification != NULL) {
  58295. ma_async_notification_signal(pJob->data.resourceManager.loadDataStream.pInitNotification);
  58296. }
  58297. if (pJob->data.resourceManager.loadDataStream.pInitFence != NULL) {
  58298. ma_fence_release(pJob->data.resourceManager.loadDataStream.pInitFence);
  58299. }
  58300. c89atomic_fetch_add_32(&pDataStream->executionPointer, 1);
  58301. return result;
  58302. }
  58303. static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob)
  58304. {
  58305. ma_resource_manager* pResourceManager;
  58306. ma_resource_manager_data_stream* pDataStream;
  58307. MA_ASSERT(pJob != NULL);
  58308. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.freeDataStream.pDataStream;
  58309. MA_ASSERT(pDataStream != NULL);
  58310. pResourceManager = pDataStream->pResourceManager;
  58311. if (pJob->order != c89atomic_load_32(&pDataStream->executionPointer)) {
  58312. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58313. }
  58314. /* If our status is not MA_UNAVAILABLE we have a bug somewhere. */
  58315. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) == MA_UNAVAILABLE);
  58316. if (pDataStream->isDecoderInitialized) {
  58317. ma_decoder_uninit(&pDataStream->decoder);
  58318. }
  58319. if (pDataStream->pPageData != NULL) {
  58320. ma_free(pDataStream->pPageData, &pResourceManager->config.allocationCallbacks);
  58321. pDataStream->pPageData = NULL; /* Just in case... */
  58322. }
  58323. ma_data_source_uninit(&pDataStream->ds);
  58324. /* The event needs to be signalled last. */
  58325. if (pJob->data.resourceManager.freeDataStream.pDoneNotification != NULL) {
  58326. ma_async_notification_signal(pJob->data.resourceManager.freeDataStream.pDoneNotification);
  58327. }
  58328. if (pJob->data.resourceManager.freeDataStream.pDoneFence != NULL) {
  58329. ma_fence_release(pJob->data.resourceManager.freeDataStream.pDoneFence);
  58330. }
  58331. /*c89atomic_fetch_add_32(&pDataStream->executionPointer, 1);*/
  58332. return MA_SUCCESS;
  58333. }
  58334. static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob)
  58335. {
  58336. ma_result result = MA_SUCCESS;
  58337. ma_resource_manager* pResourceManager;
  58338. ma_resource_manager_data_stream* pDataStream;
  58339. MA_ASSERT(pJob != NULL);
  58340. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.pageDataStream.pDataStream;
  58341. MA_ASSERT(pDataStream != NULL);
  58342. pResourceManager = pDataStream->pResourceManager;
  58343. if (pJob->order != c89atomic_load_32(&pDataStream->executionPointer)) {
  58344. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58345. }
  58346. /* For streams, the status should be MA_SUCCESS. */
  58347. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  58348. result = MA_INVALID_OPERATION;
  58349. goto done;
  58350. }
  58351. ma_resource_manager_data_stream_fill_page(pDataStream, pJob->data.resourceManager.pageDataStream.pageIndex);
  58352. done:
  58353. c89atomic_fetch_add_32(&pDataStream->executionPointer, 1);
  58354. return result;
  58355. }
  58356. static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob)
  58357. {
  58358. ma_result result = MA_SUCCESS;
  58359. ma_resource_manager* pResourceManager;
  58360. ma_resource_manager_data_stream* pDataStream;
  58361. MA_ASSERT(pJob != NULL);
  58362. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.seekDataStream.pDataStream;
  58363. MA_ASSERT(pDataStream != NULL);
  58364. pResourceManager = pDataStream->pResourceManager;
  58365. if (pJob->order != c89atomic_load_32(&pDataStream->executionPointer)) {
  58366. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58367. }
  58368. /* For streams the status should be MA_SUCCESS for this to do anything. */
  58369. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS || pDataStream->isDecoderInitialized == MA_FALSE) {
  58370. result = MA_INVALID_OPERATION;
  58371. goto done;
  58372. }
  58373. /*
  58374. With seeking we just assume both pages are invalid and the relative frame cursor at position 0. This is basically exactly the same as loading, except
  58375. instead of initializing the decoder, we seek to a frame.
  58376. */
  58377. ma_decoder_seek_to_pcm_frame(&pDataStream->decoder, pJob->data.resourceManager.seekDataStream.frameIndex);
  58378. /* After seeking we'll need to reload the pages. */
  58379. ma_resource_manager_data_stream_fill_pages(pDataStream);
  58380. /* We need to let the public API know that we're done seeking. */
  58381. c89atomic_fetch_sub_32(&pDataStream->seekCounter, 1);
  58382. done:
  58383. c89atomic_fetch_add_32(&pDataStream->executionPointer, 1);
  58384. return result;
  58385. }
  58386. MA_API ma_result ma_resource_manager_process_job(ma_resource_manager* pResourceManager, ma_job* pJob)
  58387. {
  58388. if (pResourceManager == NULL || pJob == NULL) {
  58389. return MA_INVALID_ARGS;
  58390. }
  58391. return ma_job_process(pJob);
  58392. }
  58393. MA_API ma_result ma_resource_manager_process_next_job(ma_resource_manager* pResourceManager)
  58394. {
  58395. ma_result result;
  58396. ma_job job;
  58397. if (pResourceManager == NULL) {
  58398. return MA_INVALID_ARGS;
  58399. }
  58400. /* This will return MA_CANCELLED if the next job is a quit job. */
  58401. result = ma_resource_manager_next_job(pResourceManager, &job);
  58402. if (result != MA_SUCCESS) {
  58403. return result;
  58404. }
  58405. return ma_job_process(&job);
  58406. }
  58407. #else
  58408. /* We'll get here if the resource manager is being excluded from the build. We need to define the job processing callbacks as no-ops. */
  58409. static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58410. static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58411. static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58412. static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58413. static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58414. static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58415. static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58416. static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58417. static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58418. #endif /* MA_NO_RESOURCE_MANAGER */
  58419. #ifndef MA_NO_NODE_GRAPH
  58420. /* 10ms @ 48K = 480. Must never exceed 65535. */
  58421. #ifndef MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS
  58422. #define MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS 480
  58423. #endif
  58424. static ma_result ma_node_read_pcm_frames(ma_node* pNode, ma_uint32 outputBusIndex, float* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead, ma_uint64 globalTime);
  58425. MA_API void ma_debug_fill_pcm_frames_with_sine_wave(float* pFramesOut, ma_uint32 frameCount, ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  58426. {
  58427. #ifndef MA_NO_GENERATION
  58428. {
  58429. ma_waveform_config waveformConfig;
  58430. ma_waveform waveform;
  58431. waveformConfig = ma_waveform_config_init(format, channels, sampleRate, ma_waveform_type_sine, 1.0, 400);
  58432. ma_waveform_init(&waveformConfig, &waveform);
  58433. ma_waveform_read_pcm_frames(&waveform, pFramesOut, frameCount, NULL);
  58434. }
  58435. #else
  58436. {
  58437. (void)pFramesOut;
  58438. (void)frameCount;
  58439. (void)format;
  58440. (void)channels;
  58441. (void)sampleRate;
  58442. #if defined(MA_DEBUG_OUTPUT)
  58443. {
  58444. #if _MSC_VER
  58445. #pragma message ("ma_debug_fill_pcm_frames_with_sine_wave() will do nothing because MA_NO_GENERATION is enabled.")
  58446. #endif
  58447. }
  58448. #endif
  58449. }
  58450. #endif
  58451. }
  58452. MA_API ma_node_graph_config ma_node_graph_config_init(ma_uint32 channels)
  58453. {
  58454. ma_node_graph_config config;
  58455. MA_ZERO_OBJECT(&config);
  58456. config.channels = channels;
  58457. config.nodeCacheCapInFrames = MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS;
  58458. return config;
  58459. }
  58460. static void ma_node_graph_set_is_reading(ma_node_graph* pNodeGraph, ma_bool32 isReading)
  58461. {
  58462. MA_ASSERT(pNodeGraph != NULL);
  58463. c89atomic_exchange_32(&pNodeGraph->isReading, isReading);
  58464. }
  58465. #if 0
  58466. static ma_bool32 ma_node_graph_is_reading(ma_node_graph* pNodeGraph)
  58467. {
  58468. MA_ASSERT(pNodeGraph != NULL);
  58469. return c89atomic_load_32(&pNodeGraph->isReading);
  58470. }
  58471. #endif
  58472. static void ma_node_graph_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58473. {
  58474. ma_node_graph* pNodeGraph = (ma_node_graph*)pNode;
  58475. ma_uint64 framesRead;
  58476. ma_node_graph_read_pcm_frames(pNodeGraph, ppFramesOut[0], *pFrameCountOut, &framesRead);
  58477. *pFrameCountOut = (ma_uint32)framesRead; /* Safe cast. */
  58478. (void)ppFramesIn;
  58479. (void)pFrameCountIn;
  58480. }
  58481. static ma_node_vtable g_node_graph_node_vtable =
  58482. {
  58483. ma_node_graph_node_process_pcm_frames,
  58484. NULL, /* onGetRequiredInputFrameCount */
  58485. 0, /* 0 input buses. */
  58486. 1, /* 1 output bus. */
  58487. 0 /* Flags. */
  58488. };
  58489. static void ma_node_graph_endpoint_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58490. {
  58491. MA_ASSERT(pNode != NULL);
  58492. MA_ASSERT(ma_node_get_input_bus_count(pNode) == 1);
  58493. MA_ASSERT(ma_node_get_output_bus_count(pNode) == 1);
  58494. /* Input channel count needs to be the same as the output channel count. */
  58495. MA_ASSERT(ma_node_get_input_channels(pNode, 0) == ma_node_get_output_channels(pNode, 0));
  58496. /* We don't need to do anything here because it's a passthrough. */
  58497. (void)pNode;
  58498. (void)ppFramesIn;
  58499. (void)pFrameCountIn;
  58500. (void)ppFramesOut;
  58501. (void)pFrameCountOut;
  58502. #if 0
  58503. /* The data has already been mixed. We just need to move it to the output buffer. */
  58504. if (ppFramesIn != NULL) {
  58505. ma_copy_pcm_frames(ppFramesOut[0], ppFramesIn[0], *pFrameCountOut, ma_format_f32, ma_node_get_output_channels(pNode, 0));
  58506. }
  58507. #endif
  58508. }
  58509. static ma_node_vtable g_node_graph_endpoint_vtable =
  58510. {
  58511. ma_node_graph_endpoint_process_pcm_frames,
  58512. NULL, /* onGetRequiredInputFrameCount */
  58513. 1, /* 1 input bus. */
  58514. 1, /* 1 output bus. */
  58515. MA_NODE_FLAG_PASSTHROUGH /* Flags. The endpoint is a passthrough. */
  58516. };
  58517. MA_API ma_result ma_node_graph_init(const ma_node_graph_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node_graph* pNodeGraph)
  58518. {
  58519. ma_result result;
  58520. ma_node_config baseConfig;
  58521. ma_node_config endpointConfig;
  58522. if (pNodeGraph == NULL) {
  58523. return MA_INVALID_ARGS;
  58524. }
  58525. MA_ZERO_OBJECT(pNodeGraph);
  58526. pNodeGraph->nodeCacheCapInFrames = pConfig->nodeCacheCapInFrames;
  58527. if (pNodeGraph->nodeCacheCapInFrames == 0) {
  58528. pNodeGraph->nodeCacheCapInFrames = MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS;
  58529. }
  58530. /* Base node so we can use the node graph as a node into another graph. */
  58531. baseConfig = ma_node_config_init();
  58532. baseConfig.vtable = &g_node_graph_node_vtable;
  58533. baseConfig.pOutputChannels = &pConfig->channels;
  58534. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pNodeGraph->base);
  58535. if (result != MA_SUCCESS) {
  58536. return result;
  58537. }
  58538. /* Endpoint. */
  58539. endpointConfig = ma_node_config_init();
  58540. endpointConfig.vtable = &g_node_graph_endpoint_vtable;
  58541. endpointConfig.pInputChannels = &pConfig->channels;
  58542. endpointConfig.pOutputChannels = &pConfig->channels;
  58543. result = ma_node_init(pNodeGraph, &endpointConfig, pAllocationCallbacks, &pNodeGraph->endpoint);
  58544. if (result != MA_SUCCESS) {
  58545. ma_node_uninit(&pNodeGraph->base, pAllocationCallbacks);
  58546. return result;
  58547. }
  58548. return MA_SUCCESS;
  58549. }
  58550. MA_API void ma_node_graph_uninit(ma_node_graph* pNodeGraph, const ma_allocation_callbacks* pAllocationCallbacks)
  58551. {
  58552. if (pNodeGraph == NULL) {
  58553. return;
  58554. }
  58555. ma_node_uninit(&pNodeGraph->endpoint, pAllocationCallbacks);
  58556. }
  58557. MA_API ma_node* ma_node_graph_get_endpoint(ma_node_graph* pNodeGraph)
  58558. {
  58559. if (pNodeGraph == NULL) {
  58560. return NULL;
  58561. }
  58562. return &pNodeGraph->endpoint;
  58563. }
  58564. MA_API ma_result ma_node_graph_read_pcm_frames(ma_node_graph* pNodeGraph, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  58565. {
  58566. ma_result result = MA_SUCCESS;
  58567. ma_uint64 totalFramesRead;
  58568. ma_uint32 channels;
  58569. if (pFramesRead != NULL) {
  58570. *pFramesRead = 0; /* Safety. */
  58571. }
  58572. if (pNodeGraph == NULL) {
  58573. return MA_INVALID_ARGS;
  58574. }
  58575. channels = ma_node_get_output_channels(&pNodeGraph->endpoint, 0);
  58576. /* We'll be nice and try to do a full read of all frameCount frames. */
  58577. totalFramesRead = 0;
  58578. while (totalFramesRead < frameCount) {
  58579. ma_uint32 framesJustRead;
  58580. ma_uint64 framesToRead = frameCount - totalFramesRead;
  58581. if (framesToRead > 0xFFFFFFFF) {
  58582. framesToRead = 0xFFFFFFFF;
  58583. }
  58584. ma_node_graph_set_is_reading(pNodeGraph, MA_TRUE);
  58585. {
  58586. result = ma_node_read_pcm_frames(&pNodeGraph->endpoint, 0, (float*)ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, ma_format_f32, channels), (ma_uint32)framesToRead, &framesJustRead, ma_node_get_time(&pNodeGraph->endpoint));
  58587. }
  58588. ma_node_graph_set_is_reading(pNodeGraph, MA_FALSE);
  58589. totalFramesRead += framesJustRead;
  58590. if (result != MA_SUCCESS) {
  58591. break;
  58592. }
  58593. /* Abort if we weren't able to read any frames or else we risk getting stuck in a loop. */
  58594. if (framesJustRead == 0) {
  58595. break;
  58596. }
  58597. }
  58598. /* Let's go ahead and silence any leftover frames just for some added safety to ensure the caller doesn't try emitting garbage out of the speakers. */
  58599. if (totalFramesRead < frameCount) {
  58600. ma_silence_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, ma_format_f32, channels), (frameCount - totalFramesRead), ma_format_f32, channels);
  58601. }
  58602. if (pFramesRead != NULL) {
  58603. *pFramesRead = totalFramesRead;
  58604. }
  58605. return result;
  58606. }
  58607. MA_API ma_uint32 ma_node_graph_get_channels(const ma_node_graph* pNodeGraph)
  58608. {
  58609. if (pNodeGraph == NULL) {
  58610. return 0;
  58611. }
  58612. return ma_node_get_output_channels(&pNodeGraph->endpoint, 0);
  58613. }
  58614. MA_API ma_uint64 ma_node_graph_get_time(const ma_node_graph* pNodeGraph)
  58615. {
  58616. if (pNodeGraph == NULL) {
  58617. return 0;
  58618. }
  58619. return ma_node_get_time(&pNodeGraph->endpoint); /* Global time is just the local time of the endpoint. */
  58620. }
  58621. MA_API ma_result ma_node_graph_set_time(ma_node_graph* pNodeGraph, ma_uint64 globalTime)
  58622. {
  58623. if (pNodeGraph == NULL) {
  58624. return MA_INVALID_ARGS;
  58625. }
  58626. return ma_node_set_time(&pNodeGraph->endpoint, globalTime); /* Global time is just the local time of the endpoint. */
  58627. }
  58628. #define MA_NODE_OUTPUT_BUS_FLAG_HAS_READ 0x01 /* Whether or not this bus ready to read more data. Only used on nodes with multiple output buses. */
  58629. static ma_result ma_node_output_bus_init(ma_node* pNode, ma_uint32 outputBusIndex, ma_uint32 channels, ma_node_output_bus* pOutputBus)
  58630. {
  58631. MA_ASSERT(pOutputBus != NULL);
  58632. MA_ASSERT(outputBusIndex < MA_MAX_NODE_BUS_COUNT);
  58633. MA_ASSERT(outputBusIndex < ma_node_get_output_bus_count(pNode));
  58634. MA_ASSERT(channels < 256);
  58635. MA_ZERO_OBJECT(pOutputBus);
  58636. if (channels == 0) {
  58637. return MA_INVALID_ARGS;
  58638. }
  58639. pOutputBus->pNode = pNode;
  58640. pOutputBus->outputBusIndex = (ma_uint8)outputBusIndex;
  58641. pOutputBus->channels = (ma_uint8)channels;
  58642. pOutputBus->flags = MA_NODE_OUTPUT_BUS_FLAG_HAS_READ; /* <-- Important that this flag is set by default. */
  58643. pOutputBus->volume = 1;
  58644. return MA_SUCCESS;
  58645. }
  58646. static void ma_node_output_bus_lock(ma_node_output_bus* pOutputBus)
  58647. {
  58648. ma_spinlock_lock(&pOutputBus->lock);
  58649. }
  58650. static void ma_node_output_bus_unlock(ma_node_output_bus* pOutputBus)
  58651. {
  58652. ma_spinlock_unlock(&pOutputBus->lock);
  58653. }
  58654. static ma_uint32 ma_node_output_bus_get_channels(const ma_node_output_bus* pOutputBus)
  58655. {
  58656. return pOutputBus->channels;
  58657. }
  58658. static void ma_node_output_bus_set_has_read(ma_node_output_bus* pOutputBus, ma_bool32 hasRead)
  58659. {
  58660. if (hasRead) {
  58661. c89atomic_fetch_or_32(&pOutputBus->flags, MA_NODE_OUTPUT_BUS_FLAG_HAS_READ);
  58662. } else {
  58663. c89atomic_fetch_and_32(&pOutputBus->flags, (ma_uint32)~MA_NODE_OUTPUT_BUS_FLAG_HAS_READ);
  58664. }
  58665. }
  58666. static ma_bool32 ma_node_output_bus_has_read(ma_node_output_bus* pOutputBus)
  58667. {
  58668. return (c89atomic_load_32(&pOutputBus->flags) & MA_NODE_OUTPUT_BUS_FLAG_HAS_READ) != 0;
  58669. }
  58670. static void ma_node_output_bus_set_is_attached(ma_node_output_bus* pOutputBus, ma_bool32 isAttached)
  58671. {
  58672. c89atomic_exchange_32(&pOutputBus->isAttached, isAttached);
  58673. }
  58674. static ma_bool32 ma_node_output_bus_is_attached(ma_node_output_bus* pOutputBus)
  58675. {
  58676. return c89atomic_load_32(&pOutputBus->isAttached);
  58677. }
  58678. static ma_result ma_node_output_bus_set_volume(ma_node_output_bus* pOutputBus, float volume)
  58679. {
  58680. MA_ASSERT(pOutputBus != NULL);
  58681. if (volume < 0.0f) {
  58682. volume = 0.0f;
  58683. }
  58684. c89atomic_exchange_f32(&pOutputBus->volume, volume);
  58685. return MA_SUCCESS;
  58686. }
  58687. static float ma_node_output_bus_get_volume(const ma_node_output_bus* pOutputBus)
  58688. {
  58689. return c89atomic_load_f32((float*)&pOutputBus->volume);
  58690. }
  58691. static ma_result ma_node_input_bus_init(ma_uint32 channels, ma_node_input_bus* pInputBus)
  58692. {
  58693. MA_ASSERT(pInputBus != NULL);
  58694. MA_ASSERT(channels < 256);
  58695. MA_ZERO_OBJECT(pInputBus);
  58696. if (channels == 0) {
  58697. return MA_INVALID_ARGS;
  58698. }
  58699. pInputBus->channels = (ma_uint8)channels;
  58700. return MA_SUCCESS;
  58701. }
  58702. static void ma_node_input_bus_lock(ma_node_input_bus* pInputBus)
  58703. {
  58704. MA_ASSERT(pInputBus != NULL);
  58705. ma_spinlock_lock(&pInputBus->lock);
  58706. }
  58707. static void ma_node_input_bus_unlock(ma_node_input_bus* pInputBus)
  58708. {
  58709. MA_ASSERT(pInputBus != NULL);
  58710. ma_spinlock_unlock(&pInputBus->lock);
  58711. }
  58712. static void ma_node_input_bus_next_begin(ma_node_input_bus* pInputBus)
  58713. {
  58714. c89atomic_fetch_add_32(&pInputBus->nextCounter, 1);
  58715. }
  58716. static void ma_node_input_bus_next_end(ma_node_input_bus* pInputBus)
  58717. {
  58718. c89atomic_fetch_sub_32(&pInputBus->nextCounter, 1);
  58719. }
  58720. static ma_uint32 ma_node_input_bus_get_next_counter(ma_node_input_bus* pInputBus)
  58721. {
  58722. return c89atomic_load_32(&pInputBus->nextCounter);
  58723. }
  58724. static ma_uint32 ma_node_input_bus_get_channels(const ma_node_input_bus* pInputBus)
  58725. {
  58726. return pInputBus->channels;
  58727. }
  58728. static void ma_node_input_bus_detach__no_output_bus_lock(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus)
  58729. {
  58730. MA_ASSERT(pInputBus != NULL);
  58731. MA_ASSERT(pOutputBus != NULL);
  58732. /*
  58733. Mark the output bus as detached first. This will prevent future iterations on the audio thread
  58734. from iterating this output bus.
  58735. */
  58736. ma_node_output_bus_set_is_attached(pOutputBus, MA_FALSE);
  58737. /*
  58738. We cannot use the output bus lock here since it'll be getting used at a higher level, but we do
  58739. still need to use the input bus lock since we'll be updating pointers on two different output
  58740. buses. The same rules apply here as the attaching case. Although we're using a lock here, we're
  58741. *not* using a lock when iterating over the list in the audio thread. We therefore need to craft
  58742. this in a way such that the iteration on the audio thread doesn't break.
  58743. The the first thing to do is swap out the "next" pointer of the previous output bus with the
  58744. new "next" output bus. This is the operation that matters for iteration on the audio thread.
  58745. After that, the previous pointer on the new "next" pointer needs to be updated, after which
  58746. point the linked list will be in a good state.
  58747. */
  58748. ma_node_input_bus_lock(pInputBus);
  58749. {
  58750. ma_node_output_bus* pOldPrev = (ma_node_output_bus*)c89atomic_load_ptr(&pOutputBus->pPrev);
  58751. ma_node_output_bus* pOldNext = (ma_node_output_bus*)c89atomic_load_ptr(&pOutputBus->pNext);
  58752. if (pOldPrev != NULL) {
  58753. c89atomic_exchange_ptr(&pOldPrev->pNext, pOldNext); /* <-- This is where the output bus is detached from the list. */
  58754. }
  58755. if (pOldNext != NULL) {
  58756. c89atomic_exchange_ptr(&pOldNext->pPrev, pOldPrev); /* <-- This is required for detachment. */
  58757. }
  58758. }
  58759. ma_node_input_bus_unlock(pInputBus);
  58760. /* At this point the output bus is detached and the linked list is completely unaware of it. Reset some data for safety. */
  58761. c89atomic_exchange_ptr(&pOutputBus->pNext, NULL); /* Using atomic exchanges here, mainly for the benefit of analysis tools which don't always recognize spinlocks. */
  58762. c89atomic_exchange_ptr(&pOutputBus->pPrev, NULL); /* As above. */
  58763. pOutputBus->pInputNode = NULL;
  58764. pOutputBus->inputNodeInputBusIndex = 0;
  58765. /*
  58766. For thread-safety reasons, we don't want to be returning from this straight away. We need to
  58767. wait for the audio thread to finish with the output bus. There's two things we need to wait
  58768. for. The first is the part that selects the next output bus in the list, and the other is the
  58769. part that reads from the output bus. Basically all we're doing is waiting for the input bus
  58770. to stop referencing the output bus.
  58771. We're doing this part last because we want the section above to run while the audio thread
  58772. is finishing up with the output bus, just for efficiency reasons. We marked the output bus as
  58773. detached right at the top of this function which is going to prevent the audio thread from
  58774. iterating the output bus again.
  58775. */
  58776. /* Part 1: Wait for the current iteration to complete. */
  58777. while (ma_node_input_bus_get_next_counter(pInputBus) > 0) {
  58778. ma_yield();
  58779. }
  58780. /* Part 2: Wait for any reads to complete. */
  58781. while (c89atomic_load_32(&pOutputBus->refCount) > 0) {
  58782. ma_yield();
  58783. }
  58784. /*
  58785. At this point we're done detaching and we can be guaranteed that the audio thread is not going
  58786. to attempt to reference this output bus again (until attached again).
  58787. */
  58788. }
  58789. #if 0 /* Not used at the moment, but leaving here in case I need it later. */
  58790. static void ma_node_input_bus_detach(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus)
  58791. {
  58792. MA_ASSERT(pInputBus != NULL);
  58793. MA_ASSERT(pOutputBus != NULL);
  58794. ma_node_output_bus_lock(pOutputBus);
  58795. {
  58796. ma_node_input_bus_detach__no_output_bus_lock(pInputBus, pOutputBus);
  58797. }
  58798. ma_node_output_bus_unlock(pOutputBus);
  58799. }
  58800. #endif
  58801. static void ma_node_input_bus_attach(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus, ma_node* pNewInputNode, ma_uint32 inputNodeInputBusIndex)
  58802. {
  58803. MA_ASSERT(pInputBus != NULL);
  58804. MA_ASSERT(pOutputBus != NULL);
  58805. ma_node_output_bus_lock(pOutputBus);
  58806. {
  58807. ma_node_output_bus* pOldInputNode = (ma_node_output_bus*)c89atomic_load_ptr(&pOutputBus->pInputNode);
  58808. /* Detach from any existing attachment first if necessary. */
  58809. if (pOldInputNode != NULL) {
  58810. ma_node_input_bus_detach__no_output_bus_lock(pInputBus, pOutputBus);
  58811. }
  58812. /*
  58813. At this point we can be sure the output bus is not attached to anything. The linked list in the
  58814. old input bus has been updated so that pOutputBus will not get iterated again.
  58815. */
  58816. pOutputBus->pInputNode = pNewInputNode; /* No need for an atomic assignment here because modification of this variable always happens within a lock. */
  58817. pOutputBus->inputNodeInputBusIndex = (ma_uint8)inputNodeInputBusIndex;
  58818. /*
  58819. Now we need to attach the output bus to the linked list. This involves updating two pointers on
  58820. two different output buses so I'm going to go ahead and keep this simple and just use a lock.
  58821. There are ways to do this without a lock, but it's just too hard to maintain for it's value.
  58822. Although we're locking here, it's important to remember that we're *not* locking when iterating
  58823. and reading audio data since that'll be running on the audio thread. As a result we need to be
  58824. careful how we craft this so that we don't break iteration. What we're going to do is always
  58825. attach the new item so that it becomes the first item in the list. That way, as we're iterating
  58826. we won't break any links in the list and iteration will continue safely. The detaching case will
  58827. also be crafted in a way as to not break list iteration. It's important to remember to use
  58828. atomic exchanges here since no locking is happening on the audio thread during iteration.
  58829. */
  58830. ma_node_input_bus_lock(pInputBus);
  58831. {
  58832. ma_node_output_bus* pNewPrev = &pInputBus->head;
  58833. ma_node_output_bus* pNewNext = (ma_node_output_bus*)c89atomic_load_ptr(&pInputBus->head.pNext);
  58834. /* Update the local output bus. */
  58835. c89atomic_exchange_ptr(&pOutputBus->pPrev, pNewPrev);
  58836. c89atomic_exchange_ptr(&pOutputBus->pNext, pNewNext);
  58837. /* Update the other output buses to point back to the local output bus. */
  58838. c89atomic_exchange_ptr(&pInputBus->head.pNext, pOutputBus); /* <-- This is where the output bus is actually attached to the input bus. */
  58839. /* Do the previous pointer last. This is only used for detachment. */
  58840. if (pNewNext != NULL) {
  58841. c89atomic_exchange_ptr(&pNewNext->pPrev, pOutputBus);
  58842. }
  58843. }
  58844. ma_node_input_bus_unlock(pInputBus);
  58845. /*
  58846. Mark the node as attached last. This is used to controlling whether or the output bus will be
  58847. iterated on the audio thread. Mainly required for detachment purposes.
  58848. */
  58849. ma_node_output_bus_set_is_attached(pOutputBus, MA_TRUE);
  58850. }
  58851. ma_node_output_bus_unlock(pOutputBus);
  58852. }
  58853. static ma_node_output_bus* ma_node_input_bus_next(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus)
  58854. {
  58855. ma_node_output_bus* pNext;
  58856. MA_ASSERT(pInputBus != NULL);
  58857. if (pOutputBus == NULL) {
  58858. return NULL;
  58859. }
  58860. ma_node_input_bus_next_begin(pInputBus);
  58861. {
  58862. pNext = pOutputBus;
  58863. for (;;) {
  58864. pNext = (ma_node_output_bus*)c89atomic_load_ptr(&pNext->pNext);
  58865. if (pNext == NULL) {
  58866. break; /* Reached the end. */
  58867. }
  58868. if (ma_node_output_bus_is_attached(pNext) == MA_FALSE) {
  58869. continue; /* The node is not attached. Keep checking. */
  58870. }
  58871. /* The next node has been selected. */
  58872. break;
  58873. }
  58874. /* We need to increment the reference count of the selected node. */
  58875. if (pNext != NULL) {
  58876. c89atomic_fetch_add_32(&pNext->refCount, 1);
  58877. }
  58878. /* The previous node is no longer being referenced. */
  58879. c89atomic_fetch_sub_32(&pOutputBus->refCount, 1);
  58880. }
  58881. ma_node_input_bus_next_end(pInputBus);
  58882. return pNext;
  58883. }
  58884. static ma_node_output_bus* ma_node_input_bus_first(ma_node_input_bus* pInputBus)
  58885. {
  58886. return ma_node_input_bus_next(pInputBus, &pInputBus->head);
  58887. }
  58888. static ma_result ma_node_input_bus_read_pcm_frames(ma_node* pInputNode, ma_node_input_bus* pInputBus, float* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead, ma_uint64 globalTime)
  58889. {
  58890. ma_result result = MA_SUCCESS;
  58891. ma_node_output_bus* pOutputBus;
  58892. ma_node_output_bus* pFirst;
  58893. ma_uint32 inputChannels;
  58894. ma_bool32 doesOutputBufferHaveContent = MA_FALSE;
  58895. (void)pInputNode; /* Not currently used. */
  58896. /*
  58897. This will be called from the audio thread which means we can't be doing any locking. Basically,
  58898. this function will not perfom any locking, whereas attaching and detaching will, but crafted in
  58899. such a way that we don't need to perform any locking here. The important thing to remember is
  58900. to always iterate in a forward direction.
  58901. In order to process any data we need to first read from all input buses. That's where this
  58902. function comes in. This iterates over each of the attachments and accumulates/mixes them. We
  58903. also convert the channels to the nodes output channel count before mixing. We want to do this
  58904. channel conversion so that the caller of this function can invoke the processing callback
  58905. without having to do it themselves.
  58906. When we iterate over each of the attachments on the input bus, we need to read as much data as
  58907. we can from each of them so that we don't end up with holes between each of the attachments. To
  58908. do this, we need to read from each attachment in a loop and read as many frames as we can, up
  58909. to `frameCount`.
  58910. */
  58911. MA_ASSERT(pInputNode != NULL);
  58912. MA_ASSERT(pFramesRead != NULL); /* pFramesRead is critical and must always be specified. On input it's undefined and on output it'll be set to the number of frames actually read. */
  58913. *pFramesRead = 0; /* Safety. */
  58914. inputChannels = ma_node_input_bus_get_channels(pInputBus);
  58915. /*
  58916. We need to be careful with how we call ma_node_input_bus_first() and ma_node_input_bus_next(). They
  58917. are both critical to our lock-free thread-safety system. We can only call ma_node_input_bus_first()
  58918. once per iteration, however we have an optimization to checks whether or not it's the first item in
  58919. the list. We therefore need to store a pointer to the first item rather than repeatedly calling
  58920. ma_node_input_bus_first(). It's safe to keep hold of this pointer, so long as we don't dereference it
  58921. after calling ma_node_input_bus_next(), which we won't be.
  58922. */
  58923. pFirst = ma_node_input_bus_first(pInputBus);
  58924. if (pFirst == NULL) {
  58925. return MA_SUCCESS; /* No attachments. Read nothing. */
  58926. }
  58927. for (pOutputBus = pFirst; pOutputBus != NULL; pOutputBus = ma_node_input_bus_next(pInputBus, pOutputBus)) {
  58928. ma_uint32 framesProcessed = 0;
  58929. ma_bool32 isSilentOutput = MA_FALSE;
  58930. MA_ASSERT(pOutputBus->pNode != NULL);
  58931. MA_ASSERT(((ma_node_base*)pOutputBus->pNode)->vtable != NULL);
  58932. isSilentOutput = (((ma_node_base*)pOutputBus->pNode)->vtable->flags & MA_NODE_FLAG_SILENT_OUTPUT) != 0;
  58933. if (pFramesOut != NULL) {
  58934. /* Read. */
  58935. float temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE / sizeof(float)];
  58936. ma_uint32 tempCapInFrames = ma_countof(temp) / inputChannels;
  58937. while (framesProcessed < frameCount) {
  58938. float* pRunningFramesOut;
  58939. ma_uint32 framesToRead;
  58940. ma_uint32 framesJustRead;
  58941. framesToRead = frameCount - framesProcessed;
  58942. if (framesToRead > tempCapInFrames) {
  58943. framesToRead = tempCapInFrames;
  58944. }
  58945. pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(pFramesOut, framesProcessed, inputChannels);
  58946. if (doesOutputBufferHaveContent == MA_FALSE) {
  58947. /* Fast path. First attachment. We just read straight into the output buffer (no mixing required). */
  58948. result = ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, pRunningFramesOut, framesToRead, &framesJustRead, globalTime + framesProcessed);
  58949. } else {
  58950. /* Slow path. Not the first attachment. Mixing required. */
  58951. result = ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, temp, framesToRead, &framesJustRead, globalTime + framesProcessed);
  58952. if (result == MA_SUCCESS || result == MA_AT_END) {
  58953. if (isSilentOutput == MA_FALSE) { /* Don't mix if the node outputs silence. */
  58954. ma_mix_pcm_frames_f32(pRunningFramesOut, temp, framesJustRead, inputChannels, /*volume*/1);
  58955. }
  58956. }
  58957. }
  58958. framesProcessed += framesJustRead;
  58959. /* If we reached the end or otherwise failed to read any data we need to finish up with this output node. */
  58960. if (result != MA_SUCCESS) {
  58961. break;
  58962. }
  58963. /* If we didn't read anything, abort so we don't get stuck in a loop. */
  58964. if (framesJustRead == 0) {
  58965. break;
  58966. }
  58967. }
  58968. /* If it's the first attachment we didn't do any mixing. Any leftover samples need to be silenced. */
  58969. if (pOutputBus == pFirst && framesProcessed < frameCount) {
  58970. ma_silence_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, framesProcessed, ma_format_f32, inputChannels), (frameCount - framesProcessed), ma_format_f32, inputChannels);
  58971. }
  58972. if (isSilentOutput == MA_FALSE) {
  58973. doesOutputBufferHaveContent = MA_TRUE;
  58974. }
  58975. } else {
  58976. /* Seek. */
  58977. ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, NULL, frameCount, &framesProcessed, globalTime);
  58978. }
  58979. }
  58980. /* If we didn't output anything, output silence. */
  58981. if (doesOutputBufferHaveContent == MA_FALSE && pFramesOut != NULL) {
  58982. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, inputChannels);
  58983. }
  58984. /* In this path we always "process" the entire amount. */
  58985. *pFramesRead = frameCount;
  58986. return result;
  58987. }
  58988. MA_API ma_node_config ma_node_config_init(void)
  58989. {
  58990. ma_node_config config;
  58991. MA_ZERO_OBJECT(&config);
  58992. config.initialState = ma_node_state_started; /* Nodes are started by default. */
  58993. config.inputBusCount = MA_NODE_BUS_COUNT_UNKNOWN;
  58994. config.outputBusCount = MA_NODE_BUS_COUNT_UNKNOWN;
  58995. return config;
  58996. }
  58997. static ma_result ma_node_detach_full(ma_node* pNode);
  58998. static float* ma_node_get_cached_input_ptr(ma_node* pNode, ma_uint32 inputBusIndex)
  58999. {
  59000. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59001. ma_uint32 iInputBus;
  59002. float* pBasePtr;
  59003. MA_ASSERT(pNodeBase != NULL);
  59004. /* Input data is stored at the front of the buffer. */
  59005. pBasePtr = pNodeBase->pCachedData;
  59006. for (iInputBus = 0; iInputBus < inputBusIndex; iInputBus += 1) {
  59007. pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iInputBus]);
  59008. }
  59009. return pBasePtr;
  59010. }
  59011. static float* ma_node_get_cached_output_ptr(ma_node* pNode, ma_uint32 outputBusIndex)
  59012. {
  59013. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59014. ma_uint32 iInputBus;
  59015. ma_uint32 iOutputBus;
  59016. float* pBasePtr;
  59017. MA_ASSERT(pNodeBase != NULL);
  59018. /* Cached output data starts after the input data. */
  59019. pBasePtr = pNodeBase->pCachedData;
  59020. for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNodeBase); iInputBus += 1) {
  59021. pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iInputBus]);
  59022. }
  59023. for (iOutputBus = 0; iOutputBus < outputBusIndex; iOutputBus += 1) {
  59024. pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[iOutputBus]);
  59025. }
  59026. return pBasePtr;
  59027. }
  59028. typedef struct
  59029. {
  59030. size_t sizeInBytes;
  59031. size_t inputBusOffset;
  59032. size_t outputBusOffset;
  59033. size_t cachedDataOffset;
  59034. ma_uint32 inputBusCount; /* So it doesn't have to be calculated twice. */
  59035. ma_uint32 outputBusCount; /* So it doesn't have to be calculated twice. */
  59036. } ma_node_heap_layout;
  59037. static ma_result ma_node_translate_bus_counts(const ma_node_config* pConfig, ma_uint32* pInputBusCount, ma_uint32* pOutputBusCount)
  59038. {
  59039. ma_uint32 inputBusCount;
  59040. ma_uint32 outputBusCount;
  59041. MA_ASSERT(pConfig != NULL);
  59042. MA_ASSERT(pInputBusCount != NULL);
  59043. MA_ASSERT(pOutputBusCount != NULL);
  59044. /* Bus counts are determined by the vtable, unless they're set to `MA_NODE_BUS_COUNT_UNKNWON`, in which case they're taken from the config. */
  59045. if (pConfig->vtable->inputBusCount == MA_NODE_BUS_COUNT_UNKNOWN) {
  59046. inputBusCount = pConfig->inputBusCount;
  59047. } else {
  59048. inputBusCount = pConfig->vtable->inputBusCount;
  59049. if (pConfig->inputBusCount != MA_NODE_BUS_COUNT_UNKNOWN && pConfig->inputBusCount != pConfig->vtable->inputBusCount) {
  59050. return MA_INVALID_ARGS; /* Invalid configuration. You must not specify a conflicting bus count between the node's config and the vtable. */
  59051. }
  59052. }
  59053. if (pConfig->vtable->outputBusCount == MA_NODE_BUS_COUNT_UNKNOWN) {
  59054. outputBusCount = pConfig->outputBusCount;
  59055. } else {
  59056. outputBusCount = pConfig->vtable->outputBusCount;
  59057. if (pConfig->outputBusCount != MA_NODE_BUS_COUNT_UNKNOWN && pConfig->outputBusCount != pConfig->vtable->outputBusCount) {
  59058. return MA_INVALID_ARGS; /* Invalid configuration. You must not specify a conflicting bus count between the node's config and the vtable. */
  59059. }
  59060. }
  59061. /* Bus counts must be within limits. */
  59062. if (inputBusCount > MA_MAX_NODE_BUS_COUNT || outputBusCount > MA_MAX_NODE_BUS_COUNT) {
  59063. return MA_INVALID_ARGS;
  59064. }
  59065. /* We must have channel counts for each bus. */
  59066. if ((inputBusCount > 0 && pConfig->pInputChannels == NULL) || (outputBusCount > 0 && pConfig->pOutputChannels == NULL)) {
  59067. return MA_INVALID_ARGS; /* You must specify channel counts for each input and output bus. */
  59068. }
  59069. /* Some special rules for passthrough nodes. */
  59070. if ((pConfig->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) {
  59071. if ((pConfig->vtable->inputBusCount != 0 && pConfig->vtable->inputBusCount != 1) || pConfig->vtable->outputBusCount != 1) {
  59072. return MA_INVALID_ARGS; /* Passthrough nodes must have exactly 1 output bus and either 0 or 1 input bus. */
  59073. }
  59074. if (pConfig->pInputChannels[0] != pConfig->pOutputChannels[0]) {
  59075. return MA_INVALID_ARGS; /* Passthrough nodes must have the same number of channels between input and output nodes. */
  59076. }
  59077. }
  59078. *pInputBusCount = inputBusCount;
  59079. *pOutputBusCount = outputBusCount;
  59080. return MA_SUCCESS;
  59081. }
  59082. static ma_result ma_node_get_heap_layout(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, ma_node_heap_layout* pHeapLayout)
  59083. {
  59084. ma_result result;
  59085. ma_uint32 inputBusCount;
  59086. ma_uint32 outputBusCount;
  59087. MA_ASSERT(pHeapLayout != NULL);
  59088. MA_ZERO_OBJECT(pHeapLayout);
  59089. if (pConfig == NULL || pConfig->vtable == NULL || pConfig->vtable->onProcess == NULL) {
  59090. return MA_INVALID_ARGS;
  59091. }
  59092. result = ma_node_translate_bus_counts(pConfig, &inputBusCount, &outputBusCount);
  59093. if (result != MA_SUCCESS) {
  59094. return result;
  59095. }
  59096. pHeapLayout->sizeInBytes = 0;
  59097. /* Input buses. */
  59098. if (inputBusCount > MA_MAX_NODE_LOCAL_BUS_COUNT) {
  59099. pHeapLayout->inputBusOffset = pHeapLayout->sizeInBytes;
  59100. pHeapLayout->sizeInBytes += ma_align_64(sizeof(ma_node_input_bus) * inputBusCount);
  59101. } else {
  59102. pHeapLayout->inputBusOffset = MA_SIZE_MAX; /* MA_SIZE_MAX indicates that no heap allocation is required for the input bus. */
  59103. }
  59104. /* Output buses. */
  59105. if (outputBusCount > MA_MAX_NODE_LOCAL_BUS_COUNT) {
  59106. pHeapLayout->outputBusOffset = pHeapLayout->sizeInBytes;
  59107. pHeapLayout->sizeInBytes += ma_align_64(sizeof(ma_node_output_bus) * outputBusCount);
  59108. } else {
  59109. pHeapLayout->outputBusOffset = MA_SIZE_MAX;
  59110. }
  59111. /*
  59112. Cached audio data.
  59113. We need to allocate memory for a caching both input and output data. We have an optimization
  59114. where no caching is necessary for specific conditions:
  59115. - The node has 0 inputs and 1 output.
  59116. When a node meets the above conditions, no cache is allocated.
  59117. The size choice for this buffer is a little bit finicky. We don't want to be too wasteful by
  59118. allocating too much, but at the same time we want it be large enough so that enough frames can
  59119. be processed for each call to ma_node_read_pcm_frames() so that it keeps things efficient. For
  59120. now I'm going with 10ms @ 48K which is 480 frames per bus. This is configurable at compile
  59121. time. It might also be worth investigating whether or not this can be configured at run time.
  59122. */
  59123. if (inputBusCount == 0 && outputBusCount == 1) {
  59124. /* Fast path. No cache needed. */
  59125. pHeapLayout->cachedDataOffset = MA_SIZE_MAX;
  59126. } else {
  59127. /* Slow path. Cache needed. */
  59128. size_t cachedDataSizeInBytes = 0;
  59129. ma_uint32 iBus;
  59130. for (iBus = 0; iBus < inputBusCount; iBus += 1) {
  59131. cachedDataSizeInBytes += pNodeGraph->nodeCacheCapInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->pInputChannels[iBus]);
  59132. }
  59133. for (iBus = 0; iBus < outputBusCount; iBus += 1) {
  59134. cachedDataSizeInBytes += pNodeGraph->nodeCacheCapInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->pOutputChannels[iBus]);
  59135. }
  59136. pHeapLayout->cachedDataOffset = pHeapLayout->sizeInBytes;
  59137. pHeapLayout->sizeInBytes += ma_align_64(cachedDataSizeInBytes);
  59138. }
  59139. /*
  59140. Not technically part of the heap, but we can output the input and output bus counts so we can
  59141. avoid a redundant call to ma_node_translate_bus_counts().
  59142. */
  59143. pHeapLayout->inputBusCount = inputBusCount;
  59144. pHeapLayout->outputBusCount = outputBusCount;
  59145. /* Make sure allocation size is aligned. */
  59146. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  59147. return MA_SUCCESS;
  59148. }
  59149. MA_API ma_result ma_node_get_heap_size(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, size_t* pHeapSizeInBytes)
  59150. {
  59151. ma_result result;
  59152. ma_node_heap_layout heapLayout;
  59153. if (pHeapSizeInBytes == NULL) {
  59154. return MA_INVALID_ARGS;
  59155. }
  59156. *pHeapSizeInBytes = 0;
  59157. result = ma_node_get_heap_layout(pNodeGraph, pConfig, &heapLayout);
  59158. if (result != MA_SUCCESS) {
  59159. return result;
  59160. }
  59161. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  59162. return MA_SUCCESS;
  59163. }
  59164. MA_API ma_result ma_node_init_preallocated(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, void* pHeap, ma_node* pNode)
  59165. {
  59166. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59167. ma_result result;
  59168. ma_node_heap_layout heapLayout;
  59169. ma_uint32 iInputBus;
  59170. ma_uint32 iOutputBus;
  59171. if (pNodeBase == NULL) {
  59172. return MA_INVALID_ARGS;
  59173. }
  59174. MA_ZERO_OBJECT(pNodeBase);
  59175. result = ma_node_get_heap_layout(pNodeGraph, pConfig, &heapLayout);
  59176. if (result != MA_SUCCESS) {
  59177. return result;
  59178. }
  59179. pNodeBase->_pHeap = pHeap;
  59180. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  59181. pNodeBase->pNodeGraph = pNodeGraph;
  59182. pNodeBase->vtable = pConfig->vtable;
  59183. pNodeBase->state = pConfig->initialState;
  59184. pNodeBase->stateTimes[ma_node_state_started] = 0;
  59185. pNodeBase->stateTimes[ma_node_state_stopped] = (ma_uint64)(ma_int64)-1; /* Weird casting for VC6 compatibility. */
  59186. pNodeBase->inputBusCount = heapLayout.inputBusCount;
  59187. pNodeBase->outputBusCount = heapLayout.outputBusCount;
  59188. if (heapLayout.inputBusOffset != MA_SIZE_MAX) {
  59189. pNodeBase->pInputBuses = (ma_node_input_bus*)ma_offset_ptr(pHeap, heapLayout.inputBusOffset);
  59190. } else {
  59191. pNodeBase->pInputBuses = pNodeBase->_inputBuses;
  59192. }
  59193. if (heapLayout.outputBusOffset != MA_SIZE_MAX) {
  59194. pNodeBase->pOutputBuses = (ma_node_output_bus*)ma_offset_ptr(pHeap, heapLayout.inputBusOffset);
  59195. } else {
  59196. pNodeBase->pOutputBuses = pNodeBase->_outputBuses;
  59197. }
  59198. if (heapLayout.cachedDataOffset != MA_SIZE_MAX) {
  59199. pNodeBase->pCachedData = (float*)ma_offset_ptr(pHeap, heapLayout.cachedDataOffset);
  59200. pNodeBase->cachedDataCapInFramesPerBus = pNodeGraph->nodeCacheCapInFrames;
  59201. } else {
  59202. pNodeBase->pCachedData = NULL;
  59203. }
  59204. /* We need to run an initialization step for each input and output bus. */
  59205. for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNodeBase); iInputBus += 1) {
  59206. result = ma_node_input_bus_init(pConfig->pInputChannels[iInputBus], &pNodeBase->pInputBuses[iInputBus]);
  59207. if (result != MA_SUCCESS) {
  59208. return result;
  59209. }
  59210. }
  59211. for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNodeBase); iOutputBus += 1) {
  59212. result = ma_node_output_bus_init(pNodeBase, iOutputBus, pConfig->pOutputChannels[iOutputBus], &pNodeBase->pOutputBuses[iOutputBus]);
  59213. if (result != MA_SUCCESS) {
  59214. return result;
  59215. }
  59216. }
  59217. /* The cached data needs to be initialized to silence (or a sine wave tone if we're debugging). */
  59218. if (pNodeBase->pCachedData != NULL) {
  59219. ma_uint32 iBus;
  59220. #if 1 /* Toggle this between 0 and 1 to turn debugging on or off. 1 = fill with a sine wave for debugging; 0 = fill with silence. */
  59221. /* For safety we'll go ahead and default the buffer to silence. */
  59222. for (iBus = 0; iBus < ma_node_get_input_bus_count(pNodeBase); iBus += 1) {
  59223. ma_silence_pcm_frames(ma_node_get_cached_input_ptr(pNode, iBus), pNodeBase->cachedDataCapInFramesPerBus, ma_format_f32, ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iBus]));
  59224. }
  59225. for (iBus = 0; iBus < ma_node_get_output_bus_count(pNodeBase); iBus += 1) {
  59226. ma_silence_pcm_frames(ma_node_get_cached_output_ptr(pNode, iBus), pNodeBase->cachedDataCapInFramesPerBus, ma_format_f32, ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[iBus]));
  59227. }
  59228. #else
  59229. /* For debugging. Default to a sine wave. */
  59230. for (iBus = 0; iBus < ma_node_get_input_bus_count(pNodeBase); iBus += 1) {
  59231. ma_debug_fill_pcm_frames_with_sine_wave(ma_node_get_cached_input_ptr(pNode, iBus), pNodeBase->cachedDataCapInFramesPerBus, ma_format_f32, ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iBus]), 48000);
  59232. }
  59233. for (iBus = 0; iBus < ma_node_get_output_bus_count(pNodeBase); iBus += 1) {
  59234. ma_debug_fill_pcm_frames_with_sine_wave(ma_node_get_cached_output_ptr(pNode, iBus), pNodeBase->cachedDataCapInFramesPerBus, ma_format_f32, ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[iBus]), 48000);
  59235. }
  59236. #endif
  59237. }
  59238. return MA_SUCCESS;
  59239. }
  59240. MA_API ma_result ma_node_init(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node* pNode)
  59241. {
  59242. ma_result result;
  59243. size_t heapSizeInBytes;
  59244. void* pHeap;
  59245. result = ma_node_get_heap_size(pNodeGraph, pConfig, &heapSizeInBytes);
  59246. if (result != MA_SUCCESS) {
  59247. return result;
  59248. }
  59249. if (heapSizeInBytes > 0) {
  59250. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  59251. if (pHeap == NULL) {
  59252. return MA_OUT_OF_MEMORY;
  59253. }
  59254. } else {
  59255. pHeap = NULL;
  59256. }
  59257. result = ma_node_init_preallocated(pNodeGraph, pConfig, pHeap, pNode);
  59258. if (result != MA_SUCCESS) {
  59259. ma_free(pHeap, pAllocationCallbacks);
  59260. return result;
  59261. }
  59262. ((ma_node_base*)pNode)->_ownsHeap = MA_TRUE;
  59263. return MA_SUCCESS;
  59264. }
  59265. MA_API void ma_node_uninit(ma_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  59266. {
  59267. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59268. if (pNodeBase == NULL) {
  59269. return;
  59270. }
  59271. /*
  59272. The first thing we need to do is fully detach the node. This will detach all inputs and
  59273. outputs. We need to do this first because it will sever the connection with the node graph and
  59274. allow us to complete uninitialization without needing to worry about thread-safety with the
  59275. audio thread. The detachment process will wait for any local processing of the node to finish.
  59276. */
  59277. ma_node_detach_full(pNode);
  59278. /*
  59279. At this point the node should be completely unreferenced by the node graph and we can finish up
  59280. the uninitialization process without needing to worry about thread-safety.
  59281. */
  59282. if (pNodeBase->_ownsHeap) {
  59283. ma_free(pNodeBase->_pHeap, pAllocationCallbacks);
  59284. }
  59285. }
  59286. MA_API ma_node_graph* ma_node_get_node_graph(const ma_node* pNode)
  59287. {
  59288. if (pNode == NULL) {
  59289. return NULL;
  59290. }
  59291. return ((const ma_node_base*)pNode)->pNodeGraph;
  59292. }
  59293. MA_API ma_uint32 ma_node_get_input_bus_count(const ma_node* pNode)
  59294. {
  59295. if (pNode == NULL) {
  59296. return 0;
  59297. }
  59298. return ((ma_node_base*)pNode)->inputBusCount;
  59299. }
  59300. MA_API ma_uint32 ma_node_get_output_bus_count(const ma_node* pNode)
  59301. {
  59302. if (pNode == NULL) {
  59303. return 0;
  59304. }
  59305. return ((ma_node_base*)pNode)->outputBusCount;
  59306. }
  59307. MA_API ma_uint32 ma_node_get_input_channels(const ma_node* pNode, ma_uint32 inputBusIndex)
  59308. {
  59309. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  59310. if (pNode == NULL) {
  59311. return 0;
  59312. }
  59313. if (inputBusIndex >= ma_node_get_input_bus_count(pNode)) {
  59314. return 0; /* Invalid bus index. */
  59315. }
  59316. return ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[inputBusIndex]);
  59317. }
  59318. MA_API ma_uint32 ma_node_get_output_channels(const ma_node* pNode, ma_uint32 outputBusIndex)
  59319. {
  59320. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  59321. if (pNode == NULL) {
  59322. return 0;
  59323. }
  59324. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  59325. return 0; /* Invalid bus index. */
  59326. }
  59327. return ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[outputBusIndex]);
  59328. }
  59329. static ma_result ma_node_detach_full(ma_node* pNode)
  59330. {
  59331. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59332. ma_uint32 iInputBus;
  59333. if (pNodeBase == NULL) {
  59334. return MA_INVALID_ARGS;
  59335. }
  59336. /*
  59337. Make sure the node is completely detached first. This will not return until the output bus is
  59338. guaranteed to no longer be referenced by the audio thread.
  59339. */
  59340. ma_node_detach_all_output_buses(pNode);
  59341. /*
  59342. At this point all output buses will have been detached from the graph and we can be guaranteed
  59343. that none of it's input nodes will be getting processed by the graph. We can detach these
  59344. without needing to worry about the audio thread touching them.
  59345. */
  59346. for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNode); iInputBus += 1) {
  59347. ma_node_input_bus* pInputBus;
  59348. ma_node_output_bus* pOutputBus;
  59349. pInputBus = &pNodeBase->pInputBuses[iInputBus];
  59350. /*
  59351. This is important. We cannot be using ma_node_input_bus_first() or ma_node_input_bus_next(). Those
  59352. functions are specifically for the audio thread. We'll instead just manually iterate using standard
  59353. linked list logic. We don't need to worry about the audio thread referencing these because the step
  59354. above severed the connection to the graph.
  59355. */
  59356. for (pOutputBus = (ma_node_output_bus*)c89atomic_load_ptr(&pInputBus->head.pNext); pOutputBus != NULL; pOutputBus = (ma_node_output_bus*)c89atomic_load_ptr(&pOutputBus->pNext)) {
  59357. ma_node_detach_output_bus(pOutputBus->pNode, pOutputBus->outputBusIndex); /* This won't do any waiting in practice and should be efficient. */
  59358. }
  59359. }
  59360. return MA_SUCCESS;
  59361. }
  59362. MA_API ma_result ma_node_detach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex)
  59363. {
  59364. ma_result result = MA_SUCCESS;
  59365. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59366. ma_node_base* pInputNodeBase;
  59367. if (pNode == NULL) {
  59368. return MA_INVALID_ARGS;
  59369. }
  59370. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  59371. return MA_INVALID_ARGS; /* Invalid output bus index. */
  59372. }
  59373. /* We need to lock the output bus because we need to inspect the input node and grab it's input bus. */
  59374. ma_node_output_bus_lock(&pNodeBase->pOutputBuses[outputBusIndex]);
  59375. {
  59376. pInputNodeBase = (ma_node_base*)pNodeBase->pOutputBuses[outputBusIndex].pInputNode;
  59377. if (pInputNodeBase != NULL) {
  59378. ma_node_input_bus_detach__no_output_bus_lock(&pInputNodeBase->pInputBuses[pNodeBase->pOutputBuses[outputBusIndex].inputNodeInputBusIndex], &pNodeBase->pOutputBuses[outputBusIndex]);
  59379. }
  59380. }
  59381. ma_node_output_bus_unlock(&pNodeBase->pOutputBuses[outputBusIndex]);
  59382. return result;
  59383. }
  59384. MA_API ma_result ma_node_detach_all_output_buses(ma_node* pNode)
  59385. {
  59386. ma_uint32 iOutputBus;
  59387. if (pNode == NULL) {
  59388. return MA_INVALID_ARGS;
  59389. }
  59390. for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNode); iOutputBus += 1) {
  59391. ma_node_detach_output_bus(pNode, iOutputBus);
  59392. }
  59393. return MA_SUCCESS;
  59394. }
  59395. MA_API ma_result ma_node_attach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex, ma_node* pOtherNode, ma_uint32 otherNodeInputBusIndex)
  59396. {
  59397. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59398. ma_node_base* pOtherNodeBase = (ma_node_base*)pOtherNode;
  59399. if (pNodeBase == NULL || pOtherNodeBase == NULL) {
  59400. return MA_INVALID_ARGS;
  59401. }
  59402. if (pNodeBase == pOtherNodeBase) {
  59403. return MA_INVALID_OPERATION; /* Cannot attach a node to itself. */
  59404. }
  59405. if (outputBusIndex >= ma_node_get_output_bus_count(pNode) || otherNodeInputBusIndex >= ma_node_get_input_bus_count(pOtherNode)) {
  59406. return MA_INVALID_OPERATION; /* Invalid bus index. */
  59407. }
  59408. /* The output channel count of the output node must be the same as the input channel count of the input node. */
  59409. if (ma_node_get_output_channels(pNode, outputBusIndex) != ma_node_get_input_channels(pOtherNode, otherNodeInputBusIndex)) {
  59410. return MA_INVALID_OPERATION; /* Channel count is incompatible. */
  59411. }
  59412. /* This will deal with detaching if the output bus is already attached to something. */
  59413. ma_node_input_bus_attach(&pOtherNodeBase->pInputBuses[otherNodeInputBusIndex], &pNodeBase->pOutputBuses[outputBusIndex], pOtherNode, otherNodeInputBusIndex);
  59414. return MA_SUCCESS;
  59415. }
  59416. MA_API ma_result ma_node_set_output_bus_volume(ma_node* pNode, ma_uint32 outputBusIndex, float volume)
  59417. {
  59418. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59419. if (pNodeBase == NULL) {
  59420. return MA_INVALID_ARGS;
  59421. }
  59422. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  59423. return MA_INVALID_ARGS; /* Invalid bus index. */
  59424. }
  59425. return ma_node_output_bus_set_volume(&pNodeBase->pOutputBuses[outputBusIndex], volume);
  59426. }
  59427. MA_API float ma_node_get_output_bus_volume(const ma_node* pNode, ma_uint32 outputBusIndex)
  59428. {
  59429. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  59430. if (pNodeBase == NULL) {
  59431. return 0;
  59432. }
  59433. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  59434. return 0; /* Invalid bus index. */
  59435. }
  59436. return ma_node_output_bus_get_volume(&pNodeBase->pOutputBuses[outputBusIndex]);
  59437. }
  59438. MA_API ma_result ma_node_set_state(ma_node* pNode, ma_node_state state)
  59439. {
  59440. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59441. if (pNodeBase == NULL) {
  59442. return MA_INVALID_ARGS;
  59443. }
  59444. c89atomic_exchange_i32(&pNodeBase->state, state);
  59445. return MA_SUCCESS;
  59446. }
  59447. MA_API ma_node_state ma_node_get_state(const ma_node* pNode)
  59448. {
  59449. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  59450. if (pNodeBase == NULL) {
  59451. return ma_node_state_stopped;
  59452. }
  59453. return (ma_node_state)c89atomic_load_i32(&pNodeBase->state);
  59454. }
  59455. MA_API ma_result ma_node_set_state_time(ma_node* pNode, ma_node_state state, ma_uint64 globalTime)
  59456. {
  59457. if (pNode == NULL) {
  59458. return MA_INVALID_ARGS;
  59459. }
  59460. /* Validation check for safety since we'll be using this as an index into stateTimes[]. */
  59461. if (state != ma_node_state_started && state != ma_node_state_stopped) {
  59462. return MA_INVALID_ARGS;
  59463. }
  59464. c89atomic_exchange_64(&((ma_node_base*)pNode)->stateTimes[state], globalTime);
  59465. return MA_SUCCESS;
  59466. }
  59467. MA_API ma_uint64 ma_node_get_state_time(const ma_node* pNode, ma_node_state state)
  59468. {
  59469. if (pNode == NULL) {
  59470. return 0;
  59471. }
  59472. /* Validation check for safety since we'll be using this as an index into stateTimes[]. */
  59473. if (state != ma_node_state_started && state != ma_node_state_stopped) {
  59474. return 0;
  59475. }
  59476. return c89atomic_load_64(&((ma_node_base*)pNode)->stateTimes[state]);
  59477. }
  59478. MA_API ma_node_state ma_node_get_state_by_time(const ma_node* pNode, ma_uint64 globalTime)
  59479. {
  59480. if (pNode == NULL) {
  59481. return ma_node_state_stopped;
  59482. }
  59483. return ma_node_get_state_by_time_range(pNode, globalTime, globalTime);
  59484. }
  59485. MA_API ma_node_state ma_node_get_state_by_time_range(const ma_node* pNode, ma_uint64 globalTimeBeg, ma_uint64 globalTimeEnd)
  59486. {
  59487. ma_node_state state;
  59488. if (pNode == NULL) {
  59489. return ma_node_state_stopped;
  59490. }
  59491. state = ma_node_get_state(pNode);
  59492. /* An explicitly stopped node is always stopped. */
  59493. if (state == ma_node_state_stopped) {
  59494. return ma_node_state_stopped;
  59495. }
  59496. /*
  59497. Getting here means the node is marked as started, but it may still not be truly started due to
  59498. it's start time not having been reached yet. Also, the stop time may have also been reached in
  59499. which case it'll be considered stopped.
  59500. */
  59501. if (ma_node_get_state_time(pNode, ma_node_state_started) > globalTimeBeg) {
  59502. return ma_node_state_stopped; /* Start time has not yet been reached. */
  59503. }
  59504. if (ma_node_get_state_time(pNode, ma_node_state_stopped) <= globalTimeEnd) {
  59505. return ma_node_state_stopped; /* Stop time has been reached. */
  59506. }
  59507. /* Getting here means the node is marked as started and is within it's start/stop times. */
  59508. return ma_node_state_started;
  59509. }
  59510. MA_API ma_uint64 ma_node_get_time(const ma_node* pNode)
  59511. {
  59512. if (pNode == NULL) {
  59513. return 0;
  59514. }
  59515. return c89atomic_load_64(&((ma_node_base*)pNode)->localTime);
  59516. }
  59517. MA_API ma_result ma_node_set_time(ma_node* pNode, ma_uint64 localTime)
  59518. {
  59519. if (pNode == NULL) {
  59520. return MA_INVALID_ARGS;
  59521. }
  59522. c89atomic_exchange_64(&((ma_node_base*)pNode)->localTime, localTime);
  59523. return MA_SUCCESS;
  59524. }
  59525. static void ma_node_process_pcm_frames_internal(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  59526. {
  59527. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59528. MA_ASSERT(pNode != NULL);
  59529. if (pNodeBase->vtable->onProcess) {
  59530. pNodeBase->vtable->onProcess(pNode, ppFramesIn, pFrameCountIn, ppFramesOut, pFrameCountOut);
  59531. }
  59532. }
  59533. static ma_result ma_node_read_pcm_frames(ma_node* pNode, ma_uint32 outputBusIndex, float* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead, ma_uint64 globalTime)
  59534. {
  59535. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59536. ma_result result = MA_SUCCESS;
  59537. ma_uint32 iInputBus;
  59538. ma_uint32 iOutputBus;
  59539. ma_uint32 inputBusCount;
  59540. ma_uint32 outputBusCount;
  59541. ma_uint32 totalFramesRead = 0;
  59542. float* ppFramesIn[MA_MAX_NODE_BUS_COUNT];
  59543. float* ppFramesOut[MA_MAX_NODE_BUS_COUNT];
  59544. ma_uint64 globalTimeBeg;
  59545. ma_uint64 globalTimeEnd;
  59546. ma_uint64 startTime;
  59547. ma_uint64 stopTime;
  59548. ma_uint32 timeOffsetBeg;
  59549. ma_uint32 timeOffsetEnd;
  59550. ma_uint32 frameCountIn;
  59551. ma_uint32 frameCountOut;
  59552. /*
  59553. pFramesRead is mandatory. It must be used to determine how many frames were read. It's normal and
  59554. expected that the number of frames read may be different to that requested. Therefore, the caller
  59555. must look at this value to correctly determine how many frames were read.
  59556. */
  59557. MA_ASSERT(pFramesRead != NULL); /* <-- If you've triggered this assert, you're using this function wrong. You *must* use this variable and inspect it after the call returns. */
  59558. if (pFramesRead == NULL) {
  59559. return MA_INVALID_ARGS;
  59560. }
  59561. *pFramesRead = 0; /* Safety. */
  59562. if (pNodeBase == NULL) {
  59563. return MA_INVALID_ARGS;
  59564. }
  59565. if (outputBusIndex >= ma_node_get_output_bus_count(pNodeBase)) {
  59566. return MA_INVALID_ARGS; /* Invalid output bus index. */
  59567. }
  59568. /* Don't do anything if we're in a stopped state. */
  59569. if (ma_node_get_state_by_time_range(pNode, globalTime, globalTime + frameCount) != ma_node_state_started) {
  59570. return MA_SUCCESS; /* We're in a stopped state. This is not an error - we just need to not read anything. */
  59571. }
  59572. globalTimeBeg = globalTime;
  59573. globalTimeEnd = globalTime + frameCount;
  59574. startTime = ma_node_get_state_time(pNode, ma_node_state_started);
  59575. stopTime = ma_node_get_state_time(pNode, ma_node_state_stopped);
  59576. /*
  59577. At this point we know that we are inside our start/stop times. However, we may need to adjust
  59578. our frame count and output pointer to accomodate since we could be straddling the time period
  59579. that this function is getting called for.
  59580. It's possible (and likely) that the start time does not line up with the output buffer. We
  59581. therefore need to offset it by a number of frames to accomodate. The same thing applies for
  59582. the stop time.
  59583. */
  59584. timeOffsetBeg = (globalTimeBeg < startTime) ? (ma_uint32)(globalTimeEnd - startTime) : 0;
  59585. timeOffsetEnd = (globalTimeEnd > stopTime) ? (ma_uint32)(globalTimeEnd - stopTime) : 0;
  59586. /* Trim based on the start offset. We need to silence the start of the buffer. */
  59587. if (timeOffsetBeg > 0) {
  59588. ma_silence_pcm_frames(pFramesOut, timeOffsetBeg, ma_format_f32, ma_node_get_output_channels(pNode, outputBusIndex));
  59589. pFramesOut += timeOffsetBeg * ma_node_get_output_channels(pNode, outputBusIndex);
  59590. frameCount -= timeOffsetBeg;
  59591. }
  59592. /* Trim based on the end offset. We don't need to silence the tail section because we'll just have a reduced value written to pFramesRead. */
  59593. if (timeOffsetEnd > 0) {
  59594. frameCount -= timeOffsetEnd;
  59595. }
  59596. /* We run on different paths depending on the bus counts. */
  59597. inputBusCount = ma_node_get_input_bus_count(pNode);
  59598. outputBusCount = ma_node_get_output_bus_count(pNode);
  59599. /*
  59600. Run a simplified path when there are no inputs and one output. In this case there's nothing to
  59601. actually read and we can go straight to output. This is a very common scenario because the vast
  59602. majority of data source nodes will use this setup so this optimization I think is worthwhile.
  59603. */
  59604. if (inputBusCount == 0 && outputBusCount == 1) {
  59605. /* Fast path. No need to read from input and no need for any caching. */
  59606. frameCountIn = 0;
  59607. frameCountOut = frameCount; /* Just read as much as we can. The callback will return what was actually read. */
  59608. ppFramesOut[0] = pFramesOut;
  59609. /*
  59610. If it's a passthrough we won't be expecting the callback to output anything, so we'll
  59611. need to pre-silence the output buffer.
  59612. */
  59613. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) {
  59614. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, ma_node_get_output_channels(pNode, outputBusIndex));
  59615. }
  59616. ma_node_process_pcm_frames_internal(pNode, NULL, &frameCountIn, ppFramesOut, &frameCountOut);
  59617. totalFramesRead = frameCountOut;
  59618. } else {
  59619. /* Slow path. Need to read input data. */
  59620. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) {
  59621. /*
  59622. Fast path. We're running a passthrough. We need to read directly into the output buffer, but
  59623. still fire the callback so that event handling and trigger nodes can do their thing. Since
  59624. it's a passthrough there's no need for any kind of caching logic.
  59625. */
  59626. MA_ASSERT(outputBusCount == inputBusCount);
  59627. MA_ASSERT(outputBusCount == 1);
  59628. MA_ASSERT(outputBusIndex == 0);
  59629. /* We just read directly from input bus to output buffer, and then afterwards fire the callback. */
  59630. ppFramesOut[0] = pFramesOut;
  59631. ppFramesIn[0] = ppFramesOut[0];
  59632. result = ma_node_input_bus_read_pcm_frames(pNodeBase, &pNodeBase->pInputBuses[0], ppFramesIn[0], frameCount, &totalFramesRead, globalTime);
  59633. if (result == MA_SUCCESS) {
  59634. /* Even though it's a passthrough, we still need to fire the callback. */
  59635. frameCountIn = totalFramesRead;
  59636. frameCountOut = totalFramesRead;
  59637. if (totalFramesRead > 0) {
  59638. ma_node_process_pcm_frames_internal(pNode, (const float**)ppFramesIn, &frameCountIn, ppFramesOut, &frameCountOut); /* From GCC: expected 'const float **' but argument is of type 'float **'. Shouldn't this be implicit? Excplicit cast to silence the warning. */
  59639. }
  59640. /*
  59641. A passthrough should never have modified the input and output frame counts. If you're
  59642. triggering these assers you need to fix your processing callback.
  59643. */
  59644. MA_ASSERT(frameCountIn == totalFramesRead);
  59645. MA_ASSERT(frameCountOut == totalFramesRead);
  59646. }
  59647. } else {
  59648. /* Slow path. Need to do caching. */
  59649. ma_uint32 framesToProcessIn;
  59650. ma_uint32 framesToProcessOut;
  59651. ma_bool32 consumeNullInput = MA_FALSE;
  59652. /*
  59653. We use frameCount as a basis for the number of frames to read since that's what's being
  59654. requested, however we still need to clamp it to whatever can fit in the cache.
  59655. This will also be used as the basis for determining how many input frames to read. This is
  59656. not ideal because it can result in too many input frames being read which introduces latency.
  59657. To solve this, nodes can implement an optional callback called onGetRequiredInputFrameCount
  59658. which is used as hint to miniaudio as to how many input frames it needs to read at a time. This
  59659. callback is completely optional, and if it's not set, miniaudio will assume `frameCount`.
  59660. This function will be called multiple times for each period of time, once for each output node.
  59661. We cannot read from each input node each time this function is called. Instead we need to check
  59662. whether or not this is first output bus to be read from for this time period, and if so, read
  59663. from our input data.
  59664. To determine whether or not we're ready to read data, we check a flag. There will be one flag
  59665. for each output. When the flag is set, it means data has been read previously and that we're
  59666. ready to advance time forward for our input nodes by reading fresh data.
  59667. */
  59668. framesToProcessOut = frameCount;
  59669. if (framesToProcessOut > pNodeBase->cachedDataCapInFramesPerBus) {
  59670. framesToProcessOut = pNodeBase->cachedDataCapInFramesPerBus;
  59671. }
  59672. framesToProcessIn = frameCount;
  59673. if (pNodeBase->vtable->onGetRequiredInputFrameCount) {
  59674. pNodeBase->vtable->onGetRequiredInputFrameCount(pNode, framesToProcessOut, &framesToProcessIn); /* <-- It does not matter if this fails. */
  59675. }
  59676. if (framesToProcessIn > pNodeBase->cachedDataCapInFramesPerBus) {
  59677. framesToProcessIn = pNodeBase->cachedDataCapInFramesPerBus;
  59678. }
  59679. MA_ASSERT(framesToProcessIn <= 0xFFFF);
  59680. MA_ASSERT(framesToProcessOut <= 0xFFFF);
  59681. if (ma_node_output_bus_has_read(&pNodeBase->pOutputBuses[outputBusIndex])) {
  59682. /* Getting here means we need to do another round of processing. */
  59683. pNodeBase->cachedFrameCountOut = 0;
  59684. for (;;) {
  59685. frameCountOut = 0;
  59686. /*
  59687. We need to prepare our output frame pointers for processing. In the same iteration we need
  59688. to mark every output bus as unread so that future calls to this function for different buses
  59689. for the current time period don't pull in data when they should instead be reading from cache.
  59690. */
  59691. for (iOutputBus = 0; iOutputBus < outputBusCount; iOutputBus += 1) {
  59692. ma_node_output_bus_set_has_read(&pNodeBase->pOutputBuses[iOutputBus], MA_FALSE); /* <-- This is what tells the next calls to this function for other output buses for this time period to read from cache instead of pulling in more data. */
  59693. ppFramesOut[iOutputBus] = ma_node_get_cached_output_ptr(pNode, iOutputBus);
  59694. }
  59695. /* We only need to read from input buses if there isn't already some data in the cache. */
  59696. if (pNodeBase->cachedFrameCountIn == 0) {
  59697. ma_uint32 maxFramesReadIn = 0;
  59698. /* Here is where we pull in data from the input buses. This is what will trigger an advance in time. */
  59699. for (iInputBus = 0; iInputBus < inputBusCount; iInputBus += 1) {
  59700. ma_uint32 framesRead;
  59701. /* The first thing to do is get the offset within our bulk allocation to store this input data. */
  59702. ppFramesIn[iInputBus] = ma_node_get_cached_input_ptr(pNode, iInputBus);
  59703. /* Once we've determined our destination pointer we can read. Note that we must inspect the number of frames read and fill any leftovers with silence for safety. */
  59704. result = ma_node_input_bus_read_pcm_frames(pNodeBase, &pNodeBase->pInputBuses[iInputBus], ppFramesIn[iInputBus], framesToProcessIn, &framesRead, globalTime);
  59705. if (result != MA_SUCCESS) {
  59706. /* It doesn't really matter if we fail because we'll just fill with silence. */
  59707. framesRead = 0; /* Just for safety, but I don't think it's really needed. */
  59708. }
  59709. /* TODO: Minor optimization opportunity here. If no frames were read and the buffer is already filled with silence, no need to re-silence it. */
  59710. /* Any leftover frames need to silenced for safety. */
  59711. if (framesRead < framesToProcessIn) {
  59712. ma_silence_pcm_frames(ppFramesIn[iInputBus] + (framesRead * ma_node_get_input_channels(pNodeBase, iInputBus)), (framesToProcessIn - framesRead), ma_format_f32, ma_node_get_input_channels(pNodeBase, iInputBus));
  59713. }
  59714. maxFramesReadIn = ma_max(maxFramesReadIn, framesRead);
  59715. }
  59716. /* This was a fresh load of input data so reset our consumption counter. */
  59717. pNodeBase->consumedFrameCountIn = 0;
  59718. /*
  59719. We don't want to keep processing if there's nothing to process, so set the number of cached
  59720. input frames to the maximum number we read from each attachment (the lesser will be padded
  59721. with silence). If we didn't read anything, this will be set to 0 and the entire buffer will
  59722. have been assigned to silence. This being equal to 0 is an important property for us because
  59723. it allows us to detect when NULL can be passed into the processing callback for the input
  59724. buffer for the purpose of continuous processing.
  59725. */
  59726. pNodeBase->cachedFrameCountIn = (ma_uint16)maxFramesReadIn;
  59727. } else {
  59728. /* We don't need to read anything, but we do need to prepare our input frame pointers. */
  59729. for (iInputBus = 0; iInputBus < inputBusCount; iInputBus += 1) {
  59730. ppFramesIn[iInputBus] = ma_node_get_cached_input_ptr(pNode, iInputBus) + (pNodeBase->consumedFrameCountIn * ma_node_get_input_channels(pNodeBase, iInputBus));
  59731. }
  59732. }
  59733. /*
  59734. At this point we have our input data so now we need to do some processing. Sneaky little
  59735. optimization here - we can set the pointer to the output buffer for this output bus so
  59736. that the final copy into the output buffer is done directly by onProcess().
  59737. */
  59738. if (pFramesOut != NULL) {
  59739. ppFramesOut[outputBusIndex] = ma_offset_pcm_frames_ptr_f32(pFramesOut, pNodeBase->cachedFrameCountOut, ma_node_get_output_channels(pNode, outputBusIndex));
  59740. }
  59741. /* Give the processing function the entire capacity of the output buffer. */
  59742. frameCountOut = (framesToProcessOut - pNodeBase->cachedFrameCountOut);
  59743. /*
  59744. We need to treat nodes with continuous processing a little differently. For these ones,
  59745. we always want to fire the callback with the requested number of frames, regardless of
  59746. pNodeBase->cachedFrameCountIn, which could be 0. Also, we want to check if we can pass
  59747. in NULL for the input buffer to the callback.
  59748. */
  59749. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_CONTINUOUS_PROCESSING) != 0) {
  59750. /* We're using continuous processing. Make sure we specify the whole frame count at all times. */
  59751. frameCountIn = framesToProcessIn; /* Give the processing function as much input data as we've got in the buffer, including any silenced padding from short reads. */
  59752. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_ALLOW_NULL_INPUT) != 0 && pNodeBase->consumedFrameCountIn == 0 && pNodeBase->cachedFrameCountIn == 0) {
  59753. consumeNullInput = MA_TRUE;
  59754. } else {
  59755. consumeNullInput = MA_FALSE;
  59756. }
  59757. /*
  59758. Since we're using continuous processing we're always passing in a full frame count
  59759. regardless of how much input data was read. If this is greater than what we read as
  59760. input, we'll end up with an underflow. We instead need to make sure our cached frame
  59761. count is set to the number of frames we'll be passing to the data callback. Not
  59762. doing this will result in an underflow when we "consume" the cached data later on.
  59763. Note that this check needs to be done after the "consumeNullInput" check above because
  59764. we use the property of cachedFrameCountIn being 0 to determine whether or not we
  59765. should be passing in a null pointer to the processing callback for when the node is
  59766. configured with MA_NODE_FLAG_ALLOW_NULL_INPUT.
  59767. */
  59768. if (pNodeBase->cachedFrameCountIn < (ma_uint16)frameCountIn) {
  59769. pNodeBase->cachedFrameCountIn = (ma_uint16)frameCountIn;
  59770. }
  59771. } else {
  59772. frameCountIn = pNodeBase->cachedFrameCountIn; /* Give the processing function as much valid input data as we've got. */
  59773. consumeNullInput = MA_FALSE;
  59774. }
  59775. /*
  59776. Process data slightly differently depending on whether or not we're consuming NULL
  59777. input (checked just above).
  59778. */
  59779. if (consumeNullInput) {
  59780. ma_node_process_pcm_frames_internal(pNode, NULL, &frameCountIn, ppFramesOut, &frameCountOut);
  59781. } else {
  59782. /*
  59783. We want to skip processing if there's no input data, but we can only do that safely if
  59784. we know that there is no chance of any output frames being produced. If continuous
  59785. processing is being used, this won't be a problem because the input frame count will
  59786. always be non-0. However, if continuous processing is *not* enabled and input and output
  59787. data is processed at different rates, we still need to process that last input frame
  59788. because there could be a few excess output frames needing to be produced from cached
  59789. data. The `MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES` flag is used as the indicator for
  59790. determining whether or not we need to process the node even when there are no input
  59791. frames available right now.
  59792. */
  59793. if (frameCountIn > 0 || (pNodeBase->vtable->flags & MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES) != 0) {
  59794. ma_node_process_pcm_frames_internal(pNode, (const float**)ppFramesIn, &frameCountIn, ppFramesOut, &frameCountOut); /* From GCC: expected 'const float **' but argument is of type 'float **'. Shouldn't this be implicit? Excplicit cast to silence the warning. */
  59795. } else {
  59796. frameCountOut = 0; /* No data was processed. */
  59797. }
  59798. }
  59799. /*
  59800. Thanks to our sneaky optimization above we don't need to do any data copying directly into
  59801. the output buffer - the onProcess() callback just did that for us. We do, however, need to
  59802. apply the number of input and output frames that were processed. Note that due to continuous
  59803. processing above, we need to do explicit checks here. If we just consumed a NULL input
  59804. buffer it means that no actual input data was processed from the internal buffers and we
  59805. don't want to be modifying any counters.
  59806. */
  59807. if (consumeNullInput == MA_FALSE) {
  59808. pNodeBase->consumedFrameCountIn += (ma_uint16)frameCountIn;
  59809. pNodeBase->cachedFrameCountIn -= (ma_uint16)frameCountIn;
  59810. }
  59811. /* The cached output frame count is always equal to what we just read. */
  59812. pNodeBase->cachedFrameCountOut += (ma_uint16)frameCountOut;
  59813. /* If we couldn't process any data, we're done. The loop needs to be terminated here or else we'll get stuck in a loop. */
  59814. if (pNodeBase->cachedFrameCountOut == framesToProcessOut || (frameCountOut == 0 && frameCountIn == 0)) {
  59815. break;
  59816. }
  59817. }
  59818. } else {
  59819. /*
  59820. We're not needing to read anything from the input buffer so just read directly from our
  59821. already-processed data.
  59822. */
  59823. if (pFramesOut != NULL) {
  59824. ma_copy_pcm_frames(pFramesOut, ma_node_get_cached_output_ptr(pNodeBase, outputBusIndex), pNodeBase->cachedFrameCountOut, ma_format_f32, ma_node_get_output_channels(pNodeBase, outputBusIndex));
  59825. }
  59826. }
  59827. /* The number of frames read is always equal to the number of cached output frames. */
  59828. totalFramesRead = pNodeBase->cachedFrameCountOut;
  59829. /* Now that we've read the data, make sure our read flag is set. */
  59830. ma_node_output_bus_set_has_read(&pNodeBase->pOutputBuses[outputBusIndex], MA_TRUE);
  59831. }
  59832. }
  59833. /* Apply volume, if necessary. */
  59834. ma_apply_volume_factor_f32(pFramesOut, totalFramesRead * ma_node_get_output_channels(pNodeBase, outputBusIndex), ma_node_output_bus_get_volume(&pNodeBase->pOutputBuses[outputBusIndex]));
  59835. /* Advance our local time forward. */
  59836. c89atomic_fetch_add_64(&pNodeBase->localTime, (ma_uint64)totalFramesRead);
  59837. *pFramesRead = totalFramesRead + timeOffsetBeg; /* Must include the silenced section at the start of the buffer. */
  59838. return result;
  59839. }
  59840. /* Data source node. */
  59841. MA_API ma_data_source_node_config ma_data_source_node_config_init(ma_data_source* pDataSource)
  59842. {
  59843. ma_data_source_node_config config;
  59844. MA_ZERO_OBJECT(&config);
  59845. config.nodeConfig = ma_node_config_init();
  59846. config.pDataSource = pDataSource;
  59847. return config;
  59848. }
  59849. static void ma_data_source_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  59850. {
  59851. ma_data_source_node* pDataSourceNode = (ma_data_source_node*)pNode;
  59852. ma_format format;
  59853. ma_uint32 channels;
  59854. ma_uint32 frameCount;
  59855. ma_uint64 framesRead = 0;
  59856. MA_ASSERT(pDataSourceNode != NULL);
  59857. MA_ASSERT(pDataSourceNode->pDataSource != NULL);
  59858. MA_ASSERT(ma_node_get_input_bus_count(pDataSourceNode) == 0);
  59859. MA_ASSERT(ma_node_get_output_bus_count(pDataSourceNode) == 1);
  59860. /* We don't want to read from ppFramesIn at all. Instead we read from the data source. */
  59861. (void)ppFramesIn;
  59862. (void)pFrameCountIn;
  59863. frameCount = *pFrameCountOut;
  59864. /* miniaudio should never be calling this with a frame count of zero. */
  59865. MA_ASSERT(frameCount > 0);
  59866. if (ma_data_source_get_data_format(pDataSourceNode->pDataSource, &format, &channels, NULL, NULL, 0) == MA_SUCCESS) { /* <-- Don't care about sample rate here. */
  59867. /* The node graph system requires samples be in floating point format. This is checked in ma_data_source_node_init(). */
  59868. MA_ASSERT(format == ma_format_f32);
  59869. (void)format; /* Just to silence some static analysis tools. */
  59870. ma_data_source_read_pcm_frames(pDataSourceNode->pDataSource, ppFramesOut[0], frameCount, &framesRead);
  59871. }
  59872. *pFrameCountOut = (ma_uint32)framesRead;
  59873. }
  59874. static ma_node_vtable g_ma_data_source_node_vtable =
  59875. {
  59876. ma_data_source_node_process_pcm_frames,
  59877. NULL, /* onGetRequiredInputFrameCount */
  59878. 0, /* 0 input buses. */
  59879. 1, /* 1 output bus. */
  59880. 0
  59881. };
  59882. MA_API ma_result ma_data_source_node_init(ma_node_graph* pNodeGraph, const ma_data_source_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source_node* pDataSourceNode)
  59883. {
  59884. ma_result result;
  59885. ma_format format; /* For validating the format, which must be ma_format_f32. */
  59886. ma_uint32 channels; /* For specifying the channel count of the output bus. */
  59887. ma_node_config baseConfig;
  59888. if (pDataSourceNode == NULL) {
  59889. return MA_INVALID_ARGS;
  59890. }
  59891. MA_ZERO_OBJECT(pDataSourceNode);
  59892. if (pConfig == NULL) {
  59893. return MA_INVALID_ARGS;
  59894. }
  59895. result = ma_data_source_get_data_format(pConfig->pDataSource, &format, &channels, NULL, NULL, 0); /* Don't care about sample rate. This will check pDataSource for NULL. */
  59896. if (result != MA_SUCCESS) {
  59897. return result;
  59898. }
  59899. MA_ASSERT(format == ma_format_f32); /* <-- If you've triggered this it means your data source is not outputting floating-point samples. You must configure your data source to use ma_format_f32. */
  59900. if (format != ma_format_f32) {
  59901. return MA_INVALID_ARGS; /* Invalid format. */
  59902. }
  59903. /* The channel count is defined by the data source. If the caller has manually changed the channels we just ignore it. */
  59904. baseConfig = pConfig->nodeConfig;
  59905. baseConfig.vtable = &g_ma_data_source_node_vtable; /* Explicitly set the vtable here to prevent callers from setting it incorrectly. */
  59906. /*
  59907. The channel count is defined by the data source. It is invalid for the caller to manually set
  59908. the channel counts in the config. `ma_data_source_node_config_init()` will have defaulted the
  59909. channel count pointer to NULL which is how it must remain. If you trigger any of these asserts
  59910. it means you're explicitly setting the channel count. Instead, configure the output channel
  59911. count of your data source to be the necessary channel count.
  59912. */
  59913. if (baseConfig.pOutputChannels != NULL) {
  59914. return MA_INVALID_ARGS;
  59915. }
  59916. baseConfig.pOutputChannels = &channels;
  59917. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pDataSourceNode->base);
  59918. if (result != MA_SUCCESS) {
  59919. return result;
  59920. }
  59921. pDataSourceNode->pDataSource = pConfig->pDataSource;
  59922. return MA_SUCCESS;
  59923. }
  59924. MA_API void ma_data_source_node_uninit(ma_data_source_node* pDataSourceNode, const ma_allocation_callbacks* pAllocationCallbacks)
  59925. {
  59926. ma_node_uninit(&pDataSourceNode->base, pAllocationCallbacks);
  59927. }
  59928. MA_API ma_result ma_data_source_node_set_looping(ma_data_source_node* pDataSourceNode, ma_bool32 isLooping)
  59929. {
  59930. if (pDataSourceNode == NULL) {
  59931. return MA_INVALID_ARGS;
  59932. }
  59933. return ma_data_source_set_looping(pDataSourceNode->pDataSource, isLooping);
  59934. }
  59935. MA_API ma_bool32 ma_data_source_node_is_looping(ma_data_source_node* pDataSourceNode)
  59936. {
  59937. if (pDataSourceNode == NULL) {
  59938. return MA_FALSE;
  59939. }
  59940. return ma_data_source_is_looping(pDataSourceNode->pDataSource);
  59941. }
  59942. /* Splitter Node. */
  59943. MA_API ma_splitter_node_config ma_splitter_node_config_init(ma_uint32 channels)
  59944. {
  59945. ma_splitter_node_config config;
  59946. MA_ZERO_OBJECT(&config);
  59947. config.nodeConfig = ma_node_config_init();
  59948. config.channels = channels;
  59949. config.outputBusCount = 2;
  59950. return config;
  59951. }
  59952. static void ma_splitter_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  59953. {
  59954. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59955. ma_uint32 iOutputBus;
  59956. ma_uint32 channels;
  59957. MA_ASSERT(pNodeBase != NULL);
  59958. MA_ASSERT(ma_node_get_input_bus_count(pNodeBase) == 1);
  59959. /* We don't need to consider the input frame count - it'll be the same as the output frame count and we process everything. */
  59960. (void)pFrameCountIn;
  59961. /* NOTE: This assumes the same number of channels for all inputs and outputs. This was checked in ma_splitter_node_init(). */
  59962. channels = ma_node_get_input_channels(pNodeBase, 0);
  59963. /* Splitting is just copying the first input bus and copying it over to each output bus. */
  59964. for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNodeBase); iOutputBus += 1) {
  59965. ma_copy_pcm_frames(ppFramesOut[iOutputBus], ppFramesIn[0], *pFrameCountOut, ma_format_f32, channels);
  59966. }
  59967. }
  59968. static ma_node_vtable g_ma_splitter_node_vtable =
  59969. {
  59970. ma_splitter_node_process_pcm_frames,
  59971. NULL, /* onGetRequiredInputFrameCount */
  59972. 1, /* 1 input bus. */
  59973. MA_NODE_BUS_COUNT_UNKNOWN, /* The output bus count is specified on a per-node basis. */
  59974. 0
  59975. };
  59976. MA_API ma_result ma_splitter_node_init(ma_node_graph* pNodeGraph, const ma_splitter_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_splitter_node* pSplitterNode)
  59977. {
  59978. ma_result result;
  59979. ma_node_config baseConfig;
  59980. ma_uint32 pInputChannels[1];
  59981. ma_uint32 pOutputChannels[MA_MAX_NODE_BUS_COUNT];
  59982. ma_uint32 iOutputBus;
  59983. if (pSplitterNode == NULL) {
  59984. return MA_INVALID_ARGS;
  59985. }
  59986. MA_ZERO_OBJECT(pSplitterNode);
  59987. if (pConfig == NULL) {
  59988. return MA_INVALID_ARGS;
  59989. }
  59990. if (pConfig->outputBusCount > MA_MAX_NODE_BUS_COUNT) {
  59991. return MA_INVALID_ARGS; /* Too many output buses. */
  59992. }
  59993. /* Splitters require the same number of channels between inputs and outputs. */
  59994. pInputChannels[0] = pConfig->channels;
  59995. for (iOutputBus = 0; iOutputBus < pConfig->outputBusCount; iOutputBus += 1) {
  59996. pOutputChannels[iOutputBus] = pConfig->channels;
  59997. }
  59998. baseConfig = pConfig->nodeConfig;
  59999. baseConfig.vtable = &g_ma_splitter_node_vtable;
  60000. baseConfig.pInputChannels = pInputChannels;
  60001. baseConfig.pOutputChannels = pOutputChannels;
  60002. baseConfig.outputBusCount = pConfig->outputBusCount;
  60003. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pSplitterNode->base);
  60004. if (result != MA_SUCCESS) {
  60005. return result; /* Failed to initialize the base node. */
  60006. }
  60007. return MA_SUCCESS;
  60008. }
  60009. MA_API void ma_splitter_node_uninit(ma_splitter_node* pSplitterNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60010. {
  60011. ma_node_uninit(pSplitterNode, pAllocationCallbacks);
  60012. }
  60013. /*
  60014. Biquad Node
  60015. */
  60016. MA_API ma_biquad_node_config ma_biquad_node_config_init(ma_uint32 channels, float b0, float b1, float b2, float a0, float a1, float a2)
  60017. {
  60018. ma_biquad_node_config config;
  60019. config.nodeConfig = ma_node_config_init();
  60020. config.biquad = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2);
  60021. return config;
  60022. }
  60023. static void ma_biquad_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60024. {
  60025. ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode;
  60026. MA_ASSERT(pNode != NULL);
  60027. (void)pFrameCountIn;
  60028. ma_biquad_process_pcm_frames(&pLPFNode->biquad, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60029. }
  60030. static ma_node_vtable g_ma_biquad_node_vtable =
  60031. {
  60032. ma_biquad_node_process_pcm_frames,
  60033. NULL, /* onGetRequiredInputFrameCount */
  60034. 1, /* One input. */
  60035. 1, /* One output. */
  60036. 0 /* Default flags. */
  60037. };
  60038. MA_API ma_result ma_biquad_node_init(ma_node_graph* pNodeGraph, const ma_biquad_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad_node* pNode)
  60039. {
  60040. ma_result result;
  60041. ma_node_config baseNodeConfig;
  60042. if (pNode == NULL) {
  60043. return MA_INVALID_ARGS;
  60044. }
  60045. MA_ZERO_OBJECT(pNode);
  60046. if (pConfig == NULL) {
  60047. return MA_INVALID_ARGS;
  60048. }
  60049. if (pConfig->biquad.format != ma_format_f32) {
  60050. return MA_INVALID_ARGS; /* The format must be f32. */
  60051. }
  60052. result = ma_biquad_init(&pConfig->biquad, pAllocationCallbacks, &pNode->biquad);
  60053. if (result != MA_SUCCESS) {
  60054. return result;
  60055. }
  60056. baseNodeConfig = ma_node_config_init();
  60057. baseNodeConfig.vtable = &g_ma_biquad_node_vtable;
  60058. baseNodeConfig.pInputChannels = &pConfig->biquad.channels;
  60059. baseNodeConfig.pOutputChannels = &pConfig->biquad.channels;
  60060. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60061. if (result != MA_SUCCESS) {
  60062. return result;
  60063. }
  60064. return result;
  60065. }
  60066. MA_API ma_result ma_biquad_node_reinit(const ma_biquad_config* pConfig, ma_biquad_node* pNode)
  60067. {
  60068. ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode;
  60069. MA_ASSERT(pNode != NULL);
  60070. return ma_biquad_reinit(pConfig, &pLPFNode->biquad);
  60071. }
  60072. MA_API void ma_biquad_node_uninit(ma_biquad_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60073. {
  60074. ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode;
  60075. if (pNode == NULL) {
  60076. return;
  60077. }
  60078. ma_node_uninit(pNode, pAllocationCallbacks);
  60079. ma_biquad_uninit(&pLPFNode->biquad, pAllocationCallbacks);
  60080. }
  60081. /*
  60082. Low Pass Filter Node
  60083. */
  60084. MA_API ma_lpf_node_config ma_lpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  60085. {
  60086. ma_lpf_node_config config;
  60087. config.nodeConfig = ma_node_config_init();
  60088. config.lpf = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  60089. return config;
  60090. }
  60091. static void ma_lpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60092. {
  60093. ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode;
  60094. MA_ASSERT(pNode != NULL);
  60095. (void)pFrameCountIn;
  60096. ma_lpf_process_pcm_frames(&pLPFNode->lpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60097. }
  60098. static ma_node_vtable g_ma_lpf_node_vtable =
  60099. {
  60100. ma_lpf_node_process_pcm_frames,
  60101. NULL, /* onGetRequiredInputFrameCount */
  60102. 1, /* One input. */
  60103. 1, /* One output. */
  60104. 0 /* Default flags. */
  60105. };
  60106. MA_API ma_result ma_lpf_node_init(ma_node_graph* pNodeGraph, const ma_lpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf_node* pNode)
  60107. {
  60108. ma_result result;
  60109. ma_node_config baseNodeConfig;
  60110. if (pNode == NULL) {
  60111. return MA_INVALID_ARGS;
  60112. }
  60113. MA_ZERO_OBJECT(pNode);
  60114. if (pConfig == NULL) {
  60115. return MA_INVALID_ARGS;
  60116. }
  60117. if (pConfig->lpf.format != ma_format_f32) {
  60118. return MA_INVALID_ARGS; /* The format must be f32. */
  60119. }
  60120. result = ma_lpf_init(&pConfig->lpf, pAllocationCallbacks, &pNode->lpf);
  60121. if (result != MA_SUCCESS) {
  60122. return result;
  60123. }
  60124. baseNodeConfig = ma_node_config_init();
  60125. baseNodeConfig.vtable = &g_ma_lpf_node_vtable;
  60126. baseNodeConfig.pInputChannels = &pConfig->lpf.channels;
  60127. baseNodeConfig.pOutputChannels = &pConfig->lpf.channels;
  60128. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60129. if (result != MA_SUCCESS) {
  60130. return result;
  60131. }
  60132. return result;
  60133. }
  60134. MA_API ma_result ma_lpf_node_reinit(const ma_lpf_config* pConfig, ma_lpf_node* pNode)
  60135. {
  60136. ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode;
  60137. if (pNode == NULL) {
  60138. return MA_INVALID_ARGS;
  60139. }
  60140. return ma_lpf_reinit(pConfig, &pLPFNode->lpf);
  60141. }
  60142. MA_API void ma_lpf_node_uninit(ma_lpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60143. {
  60144. ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode;
  60145. if (pNode == NULL) {
  60146. return;
  60147. }
  60148. ma_node_uninit(pNode, pAllocationCallbacks);
  60149. ma_lpf_uninit(&pLPFNode->lpf, pAllocationCallbacks);
  60150. }
  60151. /*
  60152. High Pass Filter Node
  60153. */
  60154. MA_API ma_hpf_node_config ma_hpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  60155. {
  60156. ma_hpf_node_config config;
  60157. config.nodeConfig = ma_node_config_init();
  60158. config.hpf = ma_hpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  60159. return config;
  60160. }
  60161. static void ma_hpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60162. {
  60163. ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode;
  60164. MA_ASSERT(pNode != NULL);
  60165. (void)pFrameCountIn;
  60166. ma_hpf_process_pcm_frames(&pHPFNode->hpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60167. }
  60168. static ma_node_vtable g_ma_hpf_node_vtable =
  60169. {
  60170. ma_hpf_node_process_pcm_frames,
  60171. NULL, /* onGetRequiredInputFrameCount */
  60172. 1, /* One input. */
  60173. 1, /* One output. */
  60174. 0 /* Default flags. */
  60175. };
  60176. MA_API ma_result ma_hpf_node_init(ma_node_graph* pNodeGraph, const ma_hpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf_node* pNode)
  60177. {
  60178. ma_result result;
  60179. ma_node_config baseNodeConfig;
  60180. if (pNode == NULL) {
  60181. return MA_INVALID_ARGS;
  60182. }
  60183. MA_ZERO_OBJECT(pNode);
  60184. if (pConfig == NULL) {
  60185. return MA_INVALID_ARGS;
  60186. }
  60187. if (pConfig->hpf.format != ma_format_f32) {
  60188. return MA_INVALID_ARGS; /* The format must be f32. */
  60189. }
  60190. result = ma_hpf_init(&pConfig->hpf, pAllocationCallbacks, &pNode->hpf);
  60191. if (result != MA_SUCCESS) {
  60192. return result;
  60193. }
  60194. baseNodeConfig = ma_node_config_init();
  60195. baseNodeConfig.vtable = &g_ma_hpf_node_vtable;
  60196. baseNodeConfig.pInputChannels = &pConfig->hpf.channels;
  60197. baseNodeConfig.pOutputChannels = &pConfig->hpf.channels;
  60198. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60199. if (result != MA_SUCCESS) {
  60200. return result;
  60201. }
  60202. return result;
  60203. }
  60204. MA_API ma_result ma_hpf_node_reinit(const ma_hpf_config* pConfig, ma_hpf_node* pNode)
  60205. {
  60206. ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode;
  60207. if (pNode == NULL) {
  60208. return MA_INVALID_ARGS;
  60209. }
  60210. return ma_hpf_reinit(pConfig, &pHPFNode->hpf);
  60211. }
  60212. MA_API void ma_hpf_node_uninit(ma_hpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60213. {
  60214. ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode;
  60215. if (pNode == NULL) {
  60216. return;
  60217. }
  60218. ma_node_uninit(pNode, pAllocationCallbacks);
  60219. ma_hpf_uninit(&pHPFNode->hpf, pAllocationCallbacks);
  60220. }
  60221. /*
  60222. Band Pass Filter Node
  60223. */
  60224. MA_API ma_bpf_node_config ma_bpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  60225. {
  60226. ma_bpf_node_config config;
  60227. config.nodeConfig = ma_node_config_init();
  60228. config.bpf = ma_bpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  60229. return config;
  60230. }
  60231. static void ma_bpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60232. {
  60233. ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode;
  60234. MA_ASSERT(pNode != NULL);
  60235. (void)pFrameCountIn;
  60236. ma_bpf_process_pcm_frames(&pBPFNode->bpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60237. }
  60238. static ma_node_vtable g_ma_bpf_node_vtable =
  60239. {
  60240. ma_bpf_node_process_pcm_frames,
  60241. NULL, /* onGetRequiredInputFrameCount */
  60242. 1, /* One input. */
  60243. 1, /* One output. */
  60244. 0 /* Default flags. */
  60245. };
  60246. MA_API ma_result ma_bpf_node_init(ma_node_graph* pNodeGraph, const ma_bpf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf_node* pNode)
  60247. {
  60248. ma_result result;
  60249. ma_node_config baseNodeConfig;
  60250. if (pNode == NULL) {
  60251. return MA_INVALID_ARGS;
  60252. }
  60253. MA_ZERO_OBJECT(pNode);
  60254. if (pConfig == NULL) {
  60255. return MA_INVALID_ARGS;
  60256. }
  60257. if (pConfig->bpf.format != ma_format_f32) {
  60258. return MA_INVALID_ARGS; /* The format must be f32. */
  60259. }
  60260. result = ma_bpf_init(&pConfig->bpf, pAllocationCallbacks, &pNode->bpf);
  60261. if (result != MA_SUCCESS) {
  60262. return result;
  60263. }
  60264. baseNodeConfig = ma_node_config_init();
  60265. baseNodeConfig.vtable = &g_ma_bpf_node_vtable;
  60266. baseNodeConfig.pInputChannels = &pConfig->bpf.channels;
  60267. baseNodeConfig.pOutputChannels = &pConfig->bpf.channels;
  60268. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60269. if (result != MA_SUCCESS) {
  60270. return result;
  60271. }
  60272. return result;
  60273. }
  60274. MA_API ma_result ma_bpf_node_reinit(const ma_bpf_config* pConfig, ma_bpf_node* pNode)
  60275. {
  60276. ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode;
  60277. if (pNode == NULL) {
  60278. return MA_INVALID_ARGS;
  60279. }
  60280. return ma_bpf_reinit(pConfig, &pBPFNode->bpf);
  60281. }
  60282. MA_API void ma_bpf_node_uninit(ma_bpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60283. {
  60284. ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode;
  60285. if (pNode == NULL) {
  60286. return;
  60287. }
  60288. ma_node_uninit(pNode, pAllocationCallbacks);
  60289. ma_bpf_uninit(&pBPFNode->bpf, pAllocationCallbacks);
  60290. }
  60291. /*
  60292. Notching Filter Node
  60293. */
  60294. MA_API ma_notch_node_config ma_notch_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency)
  60295. {
  60296. ma_notch_node_config config;
  60297. config.nodeConfig = ma_node_config_init();
  60298. config.notch = ma_notch2_config_init(ma_format_f32, channels, sampleRate, q, frequency);
  60299. return config;
  60300. }
  60301. static void ma_notch_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60302. {
  60303. ma_notch_node* pBPFNode = (ma_notch_node*)pNode;
  60304. MA_ASSERT(pNode != NULL);
  60305. (void)pFrameCountIn;
  60306. ma_notch2_process_pcm_frames(&pBPFNode->notch, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60307. }
  60308. static ma_node_vtable g_ma_notch_node_vtable =
  60309. {
  60310. ma_notch_node_process_pcm_frames,
  60311. NULL, /* onGetRequiredInputFrameCount */
  60312. 1, /* One input. */
  60313. 1, /* One output. */
  60314. 0 /* Default flags. */
  60315. };
  60316. MA_API ma_result ma_notch_node_init(ma_node_graph* pNodeGraph, const ma_notch_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch_node* pNode)
  60317. {
  60318. ma_result result;
  60319. ma_node_config baseNodeConfig;
  60320. if (pNode == NULL) {
  60321. return MA_INVALID_ARGS;
  60322. }
  60323. MA_ZERO_OBJECT(pNode);
  60324. if (pConfig == NULL) {
  60325. return MA_INVALID_ARGS;
  60326. }
  60327. if (pConfig->notch.format != ma_format_f32) {
  60328. return MA_INVALID_ARGS; /* The format must be f32. */
  60329. }
  60330. result = ma_notch2_init(&pConfig->notch, pAllocationCallbacks, &pNode->notch);
  60331. if (result != MA_SUCCESS) {
  60332. return result;
  60333. }
  60334. baseNodeConfig = ma_node_config_init();
  60335. baseNodeConfig.vtable = &g_ma_notch_node_vtable;
  60336. baseNodeConfig.pInputChannels = &pConfig->notch.channels;
  60337. baseNodeConfig.pOutputChannels = &pConfig->notch.channels;
  60338. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60339. if (result != MA_SUCCESS) {
  60340. return result;
  60341. }
  60342. return result;
  60343. }
  60344. MA_API ma_result ma_notch_node_reinit(const ma_notch_config* pConfig, ma_notch_node* pNode)
  60345. {
  60346. ma_notch_node* pNotchNode = (ma_notch_node*)pNode;
  60347. if (pNode == NULL) {
  60348. return MA_INVALID_ARGS;
  60349. }
  60350. return ma_notch2_reinit(pConfig, &pNotchNode->notch);
  60351. }
  60352. MA_API void ma_notch_node_uninit(ma_notch_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60353. {
  60354. ma_notch_node* pNotchNode = (ma_notch_node*)pNode;
  60355. if (pNode == NULL) {
  60356. return;
  60357. }
  60358. ma_node_uninit(pNode, pAllocationCallbacks);
  60359. ma_notch2_uninit(&pNotchNode->notch, pAllocationCallbacks);
  60360. }
  60361. /*
  60362. Peaking Filter Node
  60363. */
  60364. MA_API ma_peak_node_config ma_peak_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  60365. {
  60366. ma_peak_node_config config;
  60367. config.nodeConfig = ma_node_config_init();
  60368. config.peak = ma_peak2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency);
  60369. return config;
  60370. }
  60371. static void ma_peak_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60372. {
  60373. ma_peak_node* pBPFNode = (ma_peak_node*)pNode;
  60374. MA_ASSERT(pNode != NULL);
  60375. (void)pFrameCountIn;
  60376. ma_peak2_process_pcm_frames(&pBPFNode->peak, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60377. }
  60378. static ma_node_vtable g_ma_peak_node_vtable =
  60379. {
  60380. ma_peak_node_process_pcm_frames,
  60381. NULL, /* onGetRequiredInputFrameCount */
  60382. 1, /* One input. */
  60383. 1, /* One output. */
  60384. 0 /* Default flags. */
  60385. };
  60386. MA_API ma_result ma_peak_node_init(ma_node_graph* pNodeGraph, const ma_peak_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak_node* pNode)
  60387. {
  60388. ma_result result;
  60389. ma_node_config baseNodeConfig;
  60390. if (pNode == NULL) {
  60391. return MA_INVALID_ARGS;
  60392. }
  60393. MA_ZERO_OBJECT(pNode);
  60394. if (pConfig == NULL) {
  60395. return MA_INVALID_ARGS;
  60396. }
  60397. if (pConfig->peak.format != ma_format_f32) {
  60398. return MA_INVALID_ARGS; /* The format must be f32. */
  60399. }
  60400. result = ma_peak2_init(&pConfig->peak, pAllocationCallbacks, &pNode->peak);
  60401. if (result != MA_SUCCESS) {
  60402. ma_node_uninit(pNode, pAllocationCallbacks);
  60403. return result;
  60404. }
  60405. baseNodeConfig = ma_node_config_init();
  60406. baseNodeConfig.vtable = &g_ma_peak_node_vtable;
  60407. baseNodeConfig.pInputChannels = &pConfig->peak.channels;
  60408. baseNodeConfig.pOutputChannels = &pConfig->peak.channels;
  60409. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60410. if (result != MA_SUCCESS) {
  60411. return result;
  60412. }
  60413. return result;
  60414. }
  60415. MA_API ma_result ma_peak_node_reinit(const ma_peak_config* pConfig, ma_peak_node* pNode)
  60416. {
  60417. ma_peak_node* pPeakNode = (ma_peak_node*)pNode;
  60418. if (pNode == NULL) {
  60419. return MA_INVALID_ARGS;
  60420. }
  60421. return ma_peak2_reinit(pConfig, &pPeakNode->peak);
  60422. }
  60423. MA_API void ma_peak_node_uninit(ma_peak_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60424. {
  60425. ma_peak_node* pPeakNode = (ma_peak_node*)pNode;
  60426. if (pNode == NULL) {
  60427. return;
  60428. }
  60429. ma_node_uninit(pNode, pAllocationCallbacks);
  60430. ma_peak2_uninit(&pPeakNode->peak, pAllocationCallbacks);
  60431. }
  60432. /*
  60433. Low Shelf Filter Node
  60434. */
  60435. MA_API ma_loshelf_node_config ma_loshelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  60436. {
  60437. ma_loshelf_node_config config;
  60438. config.nodeConfig = ma_node_config_init();
  60439. config.loshelf = ma_loshelf2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency);
  60440. return config;
  60441. }
  60442. static void ma_loshelf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60443. {
  60444. ma_loshelf_node* pBPFNode = (ma_loshelf_node*)pNode;
  60445. MA_ASSERT(pNode != NULL);
  60446. (void)pFrameCountIn;
  60447. ma_loshelf2_process_pcm_frames(&pBPFNode->loshelf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60448. }
  60449. static ma_node_vtable g_ma_loshelf_node_vtable =
  60450. {
  60451. ma_loshelf_node_process_pcm_frames,
  60452. NULL, /* onGetRequiredInputFrameCount */
  60453. 1, /* One input. */
  60454. 1, /* One output. */
  60455. 0 /* Default flags. */
  60456. };
  60457. MA_API ma_result ma_loshelf_node_init(ma_node_graph* pNodeGraph, const ma_loshelf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf_node* pNode)
  60458. {
  60459. ma_result result;
  60460. ma_node_config baseNodeConfig;
  60461. if (pNode == NULL) {
  60462. return MA_INVALID_ARGS;
  60463. }
  60464. MA_ZERO_OBJECT(pNode);
  60465. if (pConfig == NULL) {
  60466. return MA_INVALID_ARGS;
  60467. }
  60468. if (pConfig->loshelf.format != ma_format_f32) {
  60469. return MA_INVALID_ARGS; /* The format must be f32. */
  60470. }
  60471. result = ma_loshelf2_init(&pConfig->loshelf, pAllocationCallbacks, &pNode->loshelf);
  60472. if (result != MA_SUCCESS) {
  60473. return result;
  60474. }
  60475. baseNodeConfig = ma_node_config_init();
  60476. baseNodeConfig.vtable = &g_ma_loshelf_node_vtable;
  60477. baseNodeConfig.pInputChannels = &pConfig->loshelf.channels;
  60478. baseNodeConfig.pOutputChannels = &pConfig->loshelf.channels;
  60479. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60480. if (result != MA_SUCCESS) {
  60481. return result;
  60482. }
  60483. return result;
  60484. }
  60485. MA_API ma_result ma_loshelf_node_reinit(const ma_loshelf_config* pConfig, ma_loshelf_node* pNode)
  60486. {
  60487. ma_loshelf_node* pLoshelfNode = (ma_loshelf_node*)pNode;
  60488. if (pNode == NULL) {
  60489. return MA_INVALID_ARGS;
  60490. }
  60491. return ma_loshelf2_reinit(pConfig, &pLoshelfNode->loshelf);
  60492. }
  60493. MA_API void ma_loshelf_node_uninit(ma_loshelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60494. {
  60495. ma_loshelf_node* pLoshelfNode = (ma_loshelf_node*)pNode;
  60496. if (pNode == NULL) {
  60497. return;
  60498. }
  60499. ma_node_uninit(pNode, pAllocationCallbacks);
  60500. ma_loshelf2_uninit(&pLoshelfNode->loshelf, pAllocationCallbacks);
  60501. }
  60502. /*
  60503. High Shelf Filter Node
  60504. */
  60505. MA_API ma_hishelf_node_config ma_hishelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  60506. {
  60507. ma_hishelf_node_config config;
  60508. config.nodeConfig = ma_node_config_init();
  60509. config.hishelf = ma_hishelf2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency);
  60510. return config;
  60511. }
  60512. static void ma_hishelf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60513. {
  60514. ma_hishelf_node* pBPFNode = (ma_hishelf_node*)pNode;
  60515. MA_ASSERT(pNode != NULL);
  60516. (void)pFrameCountIn;
  60517. ma_hishelf2_process_pcm_frames(&pBPFNode->hishelf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60518. }
  60519. static ma_node_vtable g_ma_hishelf_node_vtable =
  60520. {
  60521. ma_hishelf_node_process_pcm_frames,
  60522. NULL, /* onGetRequiredInputFrameCount */
  60523. 1, /* One input. */
  60524. 1, /* One output. */
  60525. 0 /* Default flags. */
  60526. };
  60527. MA_API ma_result ma_hishelf_node_init(ma_node_graph* pNodeGraph, const ma_hishelf_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf_node* pNode)
  60528. {
  60529. ma_result result;
  60530. ma_node_config baseNodeConfig;
  60531. if (pNode == NULL) {
  60532. return MA_INVALID_ARGS;
  60533. }
  60534. MA_ZERO_OBJECT(pNode);
  60535. if (pConfig == NULL) {
  60536. return MA_INVALID_ARGS;
  60537. }
  60538. if (pConfig->hishelf.format != ma_format_f32) {
  60539. return MA_INVALID_ARGS; /* The format must be f32. */
  60540. }
  60541. result = ma_hishelf2_init(&pConfig->hishelf, pAllocationCallbacks, &pNode->hishelf);
  60542. if (result != MA_SUCCESS) {
  60543. return result;
  60544. }
  60545. baseNodeConfig = ma_node_config_init();
  60546. baseNodeConfig.vtable = &g_ma_hishelf_node_vtable;
  60547. baseNodeConfig.pInputChannels = &pConfig->hishelf.channels;
  60548. baseNodeConfig.pOutputChannels = &pConfig->hishelf.channels;
  60549. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60550. if (result != MA_SUCCESS) {
  60551. return result;
  60552. }
  60553. return result;
  60554. }
  60555. MA_API ma_result ma_hishelf_node_reinit(const ma_hishelf_config* pConfig, ma_hishelf_node* pNode)
  60556. {
  60557. ma_hishelf_node* pHishelfNode = (ma_hishelf_node*)pNode;
  60558. if (pNode == NULL) {
  60559. return MA_INVALID_ARGS;
  60560. }
  60561. return ma_hishelf2_reinit(pConfig, &pHishelfNode->hishelf);
  60562. }
  60563. MA_API void ma_hishelf_node_uninit(ma_hishelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60564. {
  60565. ma_hishelf_node* pHishelfNode = (ma_hishelf_node*)pNode;
  60566. if (pNode == NULL) {
  60567. return;
  60568. }
  60569. ma_node_uninit(pNode, pAllocationCallbacks);
  60570. ma_hishelf2_uninit(&pHishelfNode->hishelf, pAllocationCallbacks);
  60571. }
  60572. MA_API ma_delay_node_config ma_delay_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay)
  60573. {
  60574. ma_delay_node_config config;
  60575. config.nodeConfig = ma_node_config_init();
  60576. config.delay = ma_delay_config_init(channels, sampleRate, delayInFrames, decay);
  60577. return config;
  60578. }
  60579. static void ma_delay_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60580. {
  60581. ma_delay_node* pDelayNode = (ma_delay_node*)pNode;
  60582. (void)pFrameCountIn;
  60583. ma_delay_process_pcm_frames(&pDelayNode->delay, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60584. }
  60585. static ma_node_vtable g_ma_delay_node_vtable =
  60586. {
  60587. ma_delay_node_process_pcm_frames,
  60588. NULL,
  60589. 1, /* 1 input channels. */
  60590. 1, /* 1 output channel. */
  60591. MA_NODE_FLAG_CONTINUOUS_PROCESSING /* Delay requires continuous processing to ensure the tail get's processed. */
  60592. };
  60593. MA_API ma_result ma_delay_node_init(ma_node_graph* pNodeGraph, const ma_delay_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay_node* pDelayNode)
  60594. {
  60595. ma_result result;
  60596. ma_node_config baseConfig;
  60597. if (pDelayNode == NULL) {
  60598. return MA_INVALID_ARGS;
  60599. }
  60600. MA_ZERO_OBJECT(pDelayNode);
  60601. result = ma_delay_init(&pConfig->delay, pAllocationCallbacks, &pDelayNode->delay);
  60602. if (result != MA_SUCCESS) {
  60603. return result;
  60604. }
  60605. baseConfig = pConfig->nodeConfig;
  60606. baseConfig.vtable = &g_ma_delay_node_vtable;
  60607. baseConfig.pInputChannels = &pConfig->delay.channels;
  60608. baseConfig.pOutputChannels = &pConfig->delay.channels;
  60609. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pDelayNode->baseNode);
  60610. if (result != MA_SUCCESS) {
  60611. ma_delay_uninit(&pDelayNode->delay, pAllocationCallbacks);
  60612. return result;
  60613. }
  60614. return result;
  60615. }
  60616. MA_API void ma_delay_node_uninit(ma_delay_node* pDelayNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60617. {
  60618. if (pDelayNode == NULL) {
  60619. return;
  60620. }
  60621. /* The base node is always uninitialized first. */
  60622. ma_node_uninit(pDelayNode, pAllocationCallbacks);
  60623. ma_delay_uninit(&pDelayNode->delay, pAllocationCallbacks);
  60624. }
  60625. MA_API void ma_delay_node_set_wet(ma_delay_node* pDelayNode, float value)
  60626. {
  60627. if (pDelayNode == NULL) {
  60628. return;
  60629. }
  60630. ma_delay_set_wet(&pDelayNode->delay, value);
  60631. }
  60632. MA_API float ma_delay_node_get_wet(const ma_delay_node* pDelayNode)
  60633. {
  60634. if (pDelayNode == NULL) {
  60635. return 0;
  60636. }
  60637. return ma_delay_get_wet(&pDelayNode->delay);
  60638. }
  60639. MA_API void ma_delay_node_set_dry(ma_delay_node* pDelayNode, float value)
  60640. {
  60641. if (pDelayNode == NULL) {
  60642. return;
  60643. }
  60644. ma_delay_set_dry(&pDelayNode->delay, value);
  60645. }
  60646. MA_API float ma_delay_node_get_dry(const ma_delay_node* pDelayNode)
  60647. {
  60648. if (pDelayNode == NULL) {
  60649. return 0;
  60650. }
  60651. return ma_delay_get_dry(&pDelayNode->delay);
  60652. }
  60653. MA_API void ma_delay_node_set_decay(ma_delay_node* pDelayNode, float value)
  60654. {
  60655. if (pDelayNode == NULL) {
  60656. return;
  60657. }
  60658. ma_delay_set_decay(&pDelayNode->delay, value);
  60659. }
  60660. MA_API float ma_delay_node_get_decay(const ma_delay_node* pDelayNode)
  60661. {
  60662. if (pDelayNode == NULL) {
  60663. return 0;
  60664. }
  60665. return ma_delay_get_decay(&pDelayNode->delay);
  60666. }
  60667. #endif /* MA_NO_NODE_GRAPH */
  60668. /* SECTION: miniaudio_engine.c */
  60669. #if !defined(MA_NO_ENGINE) && !defined(MA_NO_NODE_GRAPH)
  60670. /**************************************************************************************************************************************************************
  60671. Engine
  60672. **************************************************************************************************************************************************************/
  60673. #define MA_SEEK_TARGET_NONE (~(ma_uint64)0)
  60674. static void ma_sound_set_at_end(ma_sound* pSound, ma_bool32 atEnd)
  60675. {
  60676. MA_ASSERT(pSound != NULL);
  60677. c89atomic_exchange_32(&pSound->atEnd, atEnd);
  60678. /* Fire any callbacks or events. */
  60679. if (atEnd) {
  60680. if (pSound->endCallback != NULL) {
  60681. pSound->endCallback(pSound->pEndCallbackUserData, pSound);
  60682. }
  60683. }
  60684. }
  60685. static ma_bool32 ma_sound_get_at_end(const ma_sound* pSound)
  60686. {
  60687. MA_ASSERT(pSound != NULL);
  60688. return c89atomic_load_32(&pSound->atEnd);
  60689. }
  60690. MA_API ma_engine_node_config ma_engine_node_config_init(ma_engine* pEngine, ma_engine_node_type type, ma_uint32 flags)
  60691. {
  60692. ma_engine_node_config config;
  60693. MA_ZERO_OBJECT(&config);
  60694. config.pEngine = pEngine;
  60695. config.type = type;
  60696. config.isPitchDisabled = (flags & MA_SOUND_FLAG_NO_PITCH) != 0;
  60697. config.isSpatializationDisabled = (flags & MA_SOUND_FLAG_NO_SPATIALIZATION) != 0;
  60698. config.monoExpansionMode = pEngine->monoExpansionMode;
  60699. return config;
  60700. }
  60701. static void ma_engine_node_update_pitch_if_required(ma_engine_node* pEngineNode)
  60702. {
  60703. ma_bool32 isUpdateRequired = MA_FALSE;
  60704. float newPitch;
  60705. MA_ASSERT(pEngineNode != NULL);
  60706. newPitch = c89atomic_load_explicit_f32(&pEngineNode->pitch, c89atomic_memory_order_acquire);
  60707. if (pEngineNode->oldPitch != newPitch) {
  60708. pEngineNode->oldPitch = newPitch;
  60709. isUpdateRequired = MA_TRUE;
  60710. }
  60711. if (pEngineNode->oldDopplerPitch != pEngineNode->spatializer.dopplerPitch) {
  60712. pEngineNode->oldDopplerPitch = pEngineNode->spatializer.dopplerPitch;
  60713. isUpdateRequired = MA_TRUE;
  60714. }
  60715. if (isUpdateRequired) {
  60716. float basePitch = (float)pEngineNode->sampleRate / ma_engine_get_sample_rate(pEngineNode->pEngine);
  60717. ma_linear_resampler_set_rate_ratio(&pEngineNode->resampler, basePitch * pEngineNode->oldPitch * pEngineNode->oldDopplerPitch);
  60718. }
  60719. }
  60720. static ma_bool32 ma_engine_node_is_pitching_enabled(const ma_engine_node* pEngineNode)
  60721. {
  60722. MA_ASSERT(pEngineNode != NULL);
  60723. /* Don't try to be clever by skiping resampling in the pitch=1 case or else you'll glitch when moving away from 1. */
  60724. return !c89atomic_load_explicit_32(&pEngineNode->isPitchDisabled, c89atomic_memory_order_acquire);
  60725. }
  60726. static ma_bool32 ma_engine_node_is_spatialization_enabled(const ma_engine_node* pEngineNode)
  60727. {
  60728. MA_ASSERT(pEngineNode != NULL);
  60729. return !c89atomic_load_explicit_32(&pEngineNode->isSpatializationDisabled, c89atomic_memory_order_acquire);
  60730. }
  60731. static ma_uint64 ma_engine_node_get_required_input_frame_count(const ma_engine_node* pEngineNode, ma_uint64 outputFrameCount)
  60732. {
  60733. ma_uint64 inputFrameCount = 0;
  60734. if (ma_engine_node_is_pitching_enabled(pEngineNode)) {
  60735. ma_result result = ma_linear_resampler_get_required_input_frame_count(&pEngineNode->resampler, outputFrameCount, &inputFrameCount);
  60736. if (result != MA_SUCCESS) {
  60737. inputFrameCount = 0;
  60738. }
  60739. } else {
  60740. inputFrameCount = outputFrameCount; /* No resampling, so 1:1. */
  60741. }
  60742. return inputFrameCount;
  60743. }
  60744. static ma_result ma_engine_node_set_volume(ma_engine_node* pEngineNode, float volume)
  60745. {
  60746. if (pEngineNode == NULL) {
  60747. return MA_INVALID_ARGS;
  60748. }
  60749. ma_atomic_float_set(&pEngineNode->volume, volume);
  60750. /* If we're not smoothing we should bypass the volume gainer entirely. */
  60751. if (pEngineNode->volumeSmoothTimeInPCMFrames == 0) {
  60752. /* We should always have an active spatializer because it can be enabled and disabled dynamically. We can just use that for hodling our volume. */
  60753. ma_spatializer_set_master_volume(&pEngineNode->spatializer, volume);
  60754. } else {
  60755. /* We're using volume smoothing, so apply the master volume to the gainer. */
  60756. ma_gainer_set_gain(&pEngineNode->volumeGainer, volume);
  60757. }
  60758. return MA_SUCCESS;
  60759. }
  60760. static ma_result ma_engine_node_get_volume(const ma_engine_node* pEngineNode, float* pVolume)
  60761. {
  60762. if (pVolume == NULL) {
  60763. return MA_INVALID_ARGS;
  60764. }
  60765. *pVolume = 0.0f;
  60766. if (pEngineNode == NULL) {
  60767. return MA_INVALID_ARGS;
  60768. }
  60769. *pVolume = ma_atomic_float_get((ma_atomic_float*)&pEngineNode->volume);
  60770. return MA_SUCCESS;
  60771. }
  60772. static void ma_engine_node_process_pcm_frames__general(ma_engine_node* pEngineNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60773. {
  60774. ma_uint32 frameCountIn;
  60775. ma_uint32 frameCountOut;
  60776. ma_uint32 totalFramesProcessedIn;
  60777. ma_uint32 totalFramesProcessedOut;
  60778. ma_uint32 channelsIn;
  60779. ma_uint32 channelsOut;
  60780. ma_bool32 isPitchingEnabled;
  60781. ma_bool32 isFadingEnabled;
  60782. ma_bool32 isSpatializationEnabled;
  60783. ma_bool32 isPanningEnabled;
  60784. ma_bool32 isVolumeSmoothingEnabled;
  60785. frameCountIn = *pFrameCountIn;
  60786. frameCountOut = *pFrameCountOut;
  60787. channelsIn = ma_spatializer_get_input_channels(&pEngineNode->spatializer);
  60788. channelsOut = ma_spatializer_get_output_channels(&pEngineNode->spatializer);
  60789. totalFramesProcessedIn = 0;
  60790. totalFramesProcessedOut = 0;
  60791. isPitchingEnabled = ma_engine_node_is_pitching_enabled(pEngineNode);
  60792. isFadingEnabled = pEngineNode->fader.volumeBeg != 1 || pEngineNode->fader.volumeEnd != 1;
  60793. isSpatializationEnabled = ma_engine_node_is_spatialization_enabled(pEngineNode);
  60794. isPanningEnabled = pEngineNode->panner.pan != 0 && channelsOut != 1;
  60795. isVolumeSmoothingEnabled = pEngineNode->volumeSmoothTimeInPCMFrames > 0;
  60796. /* Keep going while we've still got data available for processing. */
  60797. while (totalFramesProcessedOut < frameCountOut) {
  60798. /*
  60799. We need to process in a specific order. We always do resampling first because it's likely
  60800. we're going to be increasing the channel count after spatialization. Also, I want to do
  60801. fading based on the output sample rate.
  60802. We'll first read into a buffer from the resampler. Then we'll do all processing that
  60803. operates on the on the input channel count. We'll then get the spatializer to output to
  60804. the output buffer and then do all effects from that point directly in the output buffer
  60805. in-place.
  60806. Note that we're always running the resampler. If we try to be clever and skip resampling
  60807. when the pitch is 1, we'll get a glitch when we move away from 1, back to 1, and then
  60808. away from 1 again. We'll want to implement any pitch=1 optimizations in the resampler
  60809. itself.
  60810. There's a small optimization here that we'll utilize since it might be a fairly common
  60811. case. When the input and output channel counts are the same, we'll read straight into the
  60812. output buffer from the resampler and do everything in-place.
  60813. */
  60814. const float* pRunningFramesIn;
  60815. float* pRunningFramesOut;
  60816. float* pWorkingBuffer; /* This is the buffer that we'll be processing frames in. This is in input channels. */
  60817. float temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE / sizeof(float)];
  60818. ma_uint32 tempCapInFrames = ma_countof(temp) / channelsIn;
  60819. ma_uint32 framesAvailableIn;
  60820. ma_uint32 framesAvailableOut;
  60821. ma_uint32 framesJustProcessedIn;
  60822. ma_uint32 framesJustProcessedOut;
  60823. ma_bool32 isWorkingBufferValid = MA_FALSE;
  60824. framesAvailableIn = frameCountIn - totalFramesProcessedIn;
  60825. framesAvailableOut = frameCountOut - totalFramesProcessedOut;
  60826. pRunningFramesIn = ma_offset_pcm_frames_const_ptr_f32(ppFramesIn[0], totalFramesProcessedIn, channelsIn);
  60827. pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(ppFramesOut[0], totalFramesProcessedOut, channelsOut);
  60828. if (channelsIn == channelsOut) {
  60829. /* Fast path. Channel counts are the same. No need for an intermediary input buffer. */
  60830. pWorkingBuffer = pRunningFramesOut;
  60831. } else {
  60832. /* Slow path. Channel counts are different. Need to use an intermediary input buffer. */
  60833. pWorkingBuffer = temp;
  60834. if (framesAvailableOut > tempCapInFrames) {
  60835. framesAvailableOut = tempCapInFrames;
  60836. }
  60837. }
  60838. /* First is resampler. */
  60839. if (isPitchingEnabled) {
  60840. ma_uint64 resampleFrameCountIn = framesAvailableIn;
  60841. ma_uint64 resampleFrameCountOut = framesAvailableOut;
  60842. ma_linear_resampler_process_pcm_frames(&pEngineNode->resampler, pRunningFramesIn, &resampleFrameCountIn, pWorkingBuffer, &resampleFrameCountOut);
  60843. isWorkingBufferValid = MA_TRUE;
  60844. framesJustProcessedIn = (ma_uint32)resampleFrameCountIn;
  60845. framesJustProcessedOut = (ma_uint32)resampleFrameCountOut;
  60846. } else {
  60847. framesJustProcessedIn = ma_min(framesAvailableIn, framesAvailableOut);
  60848. framesJustProcessedOut = framesJustProcessedIn; /* When no resampling is being performed, the number of output frames is the same as input frames. */
  60849. }
  60850. /* Fading. */
  60851. if (isFadingEnabled) {
  60852. if (isWorkingBufferValid) {
  60853. ma_fader_process_pcm_frames(&pEngineNode->fader, pWorkingBuffer, pWorkingBuffer, framesJustProcessedOut); /* In-place processing. */
  60854. } else {
  60855. ma_fader_process_pcm_frames(&pEngineNode->fader, pWorkingBuffer, pRunningFramesIn, framesJustProcessedOut);
  60856. isWorkingBufferValid = MA_TRUE;
  60857. }
  60858. }
  60859. /*
  60860. If we're using smoothing, we won't be applying volume via the spatializer, but instead from a ma_gainer. In this case
  60861. we'll want to apply our volume now.
  60862. */
  60863. if (isVolumeSmoothingEnabled) {
  60864. if (isWorkingBufferValid) {
  60865. ma_gainer_process_pcm_frames(&pEngineNode->volumeGainer, pWorkingBuffer, pWorkingBuffer, framesJustProcessedOut);
  60866. } else {
  60867. ma_gainer_process_pcm_frames(&pEngineNode->volumeGainer, pWorkingBuffer, pRunningFramesIn, framesJustProcessedOut);
  60868. isWorkingBufferValid = MA_TRUE;
  60869. }
  60870. }
  60871. /*
  60872. If at this point we still haven't actually done anything with the working buffer we need
  60873. to just read straight from the input buffer.
  60874. */
  60875. if (isWorkingBufferValid == MA_FALSE) {
  60876. pWorkingBuffer = (float*)pRunningFramesIn; /* Naughty const cast, but it's safe at this point because we won't ever be writing to it from this point out. */
  60877. }
  60878. /* Spatialization. */
  60879. if (isSpatializationEnabled) {
  60880. ma_uint32 iListener;
  60881. /*
  60882. When determining the listener to use, we first check to see if the sound is pinned to a
  60883. specific listener. If so, we use that. Otherwise we just use the closest listener.
  60884. */
  60885. if (pEngineNode->pinnedListenerIndex != MA_LISTENER_INDEX_CLOSEST && pEngineNode->pinnedListenerIndex < ma_engine_get_listener_count(pEngineNode->pEngine)) {
  60886. iListener = pEngineNode->pinnedListenerIndex;
  60887. } else {
  60888. ma_vec3f spatializerPosition = ma_spatializer_get_position(&pEngineNode->spatializer);
  60889. iListener = ma_engine_find_closest_listener(pEngineNode->pEngine, spatializerPosition.x, spatializerPosition.y, spatializerPosition.z);
  60890. }
  60891. ma_spatializer_process_pcm_frames(&pEngineNode->spatializer, &pEngineNode->pEngine->listeners[iListener], pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut);
  60892. } else {
  60893. /* No spatialization, but we still need to do channel conversion and master volume. */
  60894. float volume;
  60895. ma_engine_node_get_volume(pEngineNode, &volume); /* Should never fail. */
  60896. if (channelsIn == channelsOut) {
  60897. /* No channel conversion required. Just copy straight to the output buffer. */
  60898. if (isVolumeSmoothingEnabled) {
  60899. /* Volume has already been applied. Just copy straight to the output buffer. */
  60900. ma_copy_pcm_frames(pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut * channelsOut, ma_format_f32, channelsOut);
  60901. } else {
  60902. /* Volume has not been applied yet. Copy and apply volume in the same pass. */
  60903. ma_copy_and_apply_volume_factor_f32(pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut * channelsOut, volume);
  60904. }
  60905. } else {
  60906. /* Channel conversion required. TODO: Add support for channel maps here. */
  60907. ma_channel_map_apply_f32(pRunningFramesOut, NULL, channelsOut, pWorkingBuffer, NULL, channelsIn, framesJustProcessedOut, ma_channel_mix_mode_simple, pEngineNode->monoExpansionMode);
  60908. /* If we're using smoothing, the volume will have already been applied. */
  60909. if (!isVolumeSmoothingEnabled) {
  60910. ma_apply_volume_factor_f32(pRunningFramesOut, framesJustProcessedOut * channelsOut, volume);
  60911. }
  60912. }
  60913. }
  60914. /* At this point we can guarantee that the output buffer contains valid data. We can process everything in place now. */
  60915. /* Panning. */
  60916. if (isPanningEnabled) {
  60917. ma_panner_process_pcm_frames(&pEngineNode->panner, pRunningFramesOut, pRunningFramesOut, framesJustProcessedOut); /* In-place processing. */
  60918. }
  60919. /* We're done for this chunk. */
  60920. totalFramesProcessedIn += framesJustProcessedIn;
  60921. totalFramesProcessedOut += framesJustProcessedOut;
  60922. /* If we didn't process any output frames this iteration it means we've either run out of input data, or run out of room in the output buffer. */
  60923. if (framesJustProcessedOut == 0) {
  60924. break;
  60925. }
  60926. }
  60927. /* At this point we're done processing. */
  60928. *pFrameCountIn = totalFramesProcessedIn;
  60929. *pFrameCountOut = totalFramesProcessedOut;
  60930. }
  60931. static void ma_engine_node_process_pcm_frames__sound(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60932. {
  60933. /* For sounds, we need to first read from the data source. Then we need to apply the engine effects (pan, pitch, fades, etc.). */
  60934. ma_result result = MA_SUCCESS;
  60935. ma_sound* pSound = (ma_sound*)pNode;
  60936. ma_uint32 frameCount = *pFrameCountOut;
  60937. ma_uint32 totalFramesRead = 0;
  60938. ma_format dataSourceFormat;
  60939. ma_uint32 dataSourceChannels;
  60940. ma_uint8 temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  60941. ma_uint32 tempCapInFrames;
  60942. ma_uint64 seekTarget;
  60943. /* This is a data source node which means no input buses. */
  60944. (void)ppFramesIn;
  60945. (void)pFrameCountIn;
  60946. /* If we're marked at the end we need to stop the sound and do nothing. */
  60947. if (ma_sound_at_end(pSound)) {
  60948. ma_sound_stop(pSound);
  60949. *pFrameCountOut = 0;
  60950. return;
  60951. }
  60952. /* If we're seeking, do so now before reading. */
  60953. seekTarget = c89atomic_load_64(&pSound->seekTarget);
  60954. if (seekTarget != MA_SEEK_TARGET_NONE) {
  60955. ma_data_source_seek_to_pcm_frame(pSound->pDataSource, seekTarget);
  60956. /* Any time-dependant effects need to have their times updated. */
  60957. ma_node_set_time(pSound, seekTarget);
  60958. c89atomic_exchange_64(&pSound->seekTarget, MA_SEEK_TARGET_NONE);
  60959. }
  60960. /*
  60961. We want to update the pitch once. For sounds, this can be either at the start or at the end. If
  60962. we don't force this to only ever be updating once, we could end up in a situation where
  60963. retrieving the required input frame count ends up being different to what we actually retrieve.
  60964. What could happen is that the required input frame count is calculated, the pitch is update,
  60965. and then this processing function is called resulting in a different number of input frames
  60966. being processed. Do not call this in ma_engine_node_process_pcm_frames__general() or else
  60967. you'll hit the aforementioned bug.
  60968. */
  60969. ma_engine_node_update_pitch_if_required(&pSound->engineNode);
  60970. /*
  60971. For the convenience of the caller, we're doing to allow data sources to use non-floating-point formats and channel counts that differ
  60972. from the main engine.
  60973. */
  60974. result = ma_data_source_get_data_format(pSound->pDataSource, &dataSourceFormat, &dataSourceChannels, NULL, NULL, 0);
  60975. if (result == MA_SUCCESS) {
  60976. tempCapInFrames = sizeof(temp) / ma_get_bytes_per_frame(dataSourceFormat, dataSourceChannels);
  60977. /* Keep reading until we've read as much as was requested or we reach the end of the data source. */
  60978. while (totalFramesRead < frameCount) {
  60979. ma_uint32 framesRemaining = frameCount - totalFramesRead;
  60980. ma_uint32 framesToRead;
  60981. ma_uint64 framesJustRead;
  60982. ma_uint32 frameCountIn;
  60983. ma_uint32 frameCountOut;
  60984. const float* pRunningFramesIn;
  60985. float* pRunningFramesOut;
  60986. /*
  60987. The first thing we need to do is read into the temporary buffer. We can calculate exactly
  60988. how many input frames we'll need after resampling.
  60989. */
  60990. framesToRead = (ma_uint32)ma_engine_node_get_required_input_frame_count(&pSound->engineNode, framesRemaining);
  60991. if (framesToRead > tempCapInFrames) {
  60992. framesToRead = tempCapInFrames;
  60993. }
  60994. result = ma_data_source_read_pcm_frames(pSound->pDataSource, temp, framesToRead, &framesJustRead);
  60995. /* If we reached the end of the sound we'll want to mark it as at the end and stop it. This should never be returned for looping sounds. */
  60996. if (result == MA_AT_END) {
  60997. ma_sound_set_at_end(pSound, MA_TRUE); /* This will be set to false in ma_sound_start(). */
  60998. }
  60999. pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(ppFramesOut[0], totalFramesRead, ma_engine_get_channels(ma_sound_get_engine(pSound)));
  61000. frameCountIn = (ma_uint32)framesJustRead;
  61001. frameCountOut = framesRemaining;
  61002. /* Convert if necessary. */
  61003. if (dataSourceFormat == ma_format_f32) {
  61004. /* Fast path. No data conversion necessary. */
  61005. pRunningFramesIn = (float*)temp;
  61006. ma_engine_node_process_pcm_frames__general(&pSound->engineNode, &pRunningFramesIn, &frameCountIn, &pRunningFramesOut, &frameCountOut);
  61007. } else {
  61008. /* Slow path. Need to do sample format conversion to f32. If we give the f32 buffer the same count as the first temp buffer, we're guaranteed it'll be large enough. */
  61009. float tempf32[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* Do not do `MA_DATA_CONVERTER_STACK_BUFFER_SIZE/sizeof(float)` here like we've done in other places. */
  61010. ma_convert_pcm_frames_format(tempf32, ma_format_f32, temp, dataSourceFormat, framesJustRead, dataSourceChannels, ma_dither_mode_none);
  61011. /* Now that we have our samples in f32 format we can process like normal. */
  61012. pRunningFramesIn = tempf32;
  61013. ma_engine_node_process_pcm_frames__general(&pSound->engineNode, &pRunningFramesIn, &frameCountIn, &pRunningFramesOut, &frameCountOut);
  61014. }
  61015. /* We should have processed all of our input frames since we calculated the required number of input frames at the top. */
  61016. MA_ASSERT(frameCountIn == framesJustRead);
  61017. totalFramesRead += (ma_uint32)frameCountOut; /* Safe cast. */
  61018. if (result != MA_SUCCESS || ma_sound_at_end(pSound)) {
  61019. break; /* Might have reached the end. */
  61020. }
  61021. }
  61022. }
  61023. *pFrameCountOut = totalFramesRead;
  61024. }
  61025. static void ma_engine_node_process_pcm_frames__group(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  61026. {
  61027. /*
  61028. Make sure the pitch is updated before trying to read anything. It's important that this is done
  61029. only once and not in ma_engine_node_process_pcm_frames__general(). The reason for this is that
  61030. ma_engine_node_process_pcm_frames__general() will call ma_engine_node_get_required_input_frame_count(),
  61031. and if another thread modifies the pitch just after that call it can result in a glitch due to
  61032. the input rate changing.
  61033. */
  61034. ma_engine_node_update_pitch_if_required((ma_engine_node*)pNode);
  61035. /* For groups, the input data has already been read and we just need to apply the effect. */
  61036. ma_engine_node_process_pcm_frames__general((ma_engine_node*)pNode, ppFramesIn, pFrameCountIn, ppFramesOut, pFrameCountOut);
  61037. }
  61038. static ma_result ma_engine_node_get_required_input_frame_count__group(ma_node* pNode, ma_uint32 outputFrameCount, ma_uint32* pInputFrameCount)
  61039. {
  61040. ma_uint64 inputFrameCount;
  61041. MA_ASSERT(pInputFrameCount != NULL);
  61042. /* Our pitch will affect this calculation. We need to update it. */
  61043. ma_engine_node_update_pitch_if_required((ma_engine_node*)pNode);
  61044. inputFrameCount = ma_engine_node_get_required_input_frame_count((ma_engine_node*)pNode, outputFrameCount);
  61045. if (inputFrameCount > 0xFFFFFFFF) {
  61046. inputFrameCount = 0xFFFFFFFF; /* Will never happen because miniaudio will only ever process in relatively small chunks. */
  61047. }
  61048. *pInputFrameCount = (ma_uint32)inputFrameCount;
  61049. return MA_SUCCESS;
  61050. }
  61051. static ma_node_vtable g_ma_engine_node_vtable__sound =
  61052. {
  61053. ma_engine_node_process_pcm_frames__sound,
  61054. NULL, /* onGetRequiredInputFrameCount */
  61055. 0, /* Sounds are data source nodes which means they have zero inputs (their input is drawn from the data source itself). */
  61056. 1, /* Sounds have one output bus. */
  61057. 0 /* Default flags. */
  61058. };
  61059. static ma_node_vtable g_ma_engine_node_vtable__group =
  61060. {
  61061. ma_engine_node_process_pcm_frames__group,
  61062. ma_engine_node_get_required_input_frame_count__group,
  61063. 1, /* Groups have one input bus. */
  61064. 1, /* Groups have one output bus. */
  61065. MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES /* The engine node does resampling so should let miniaudio know about it. */
  61066. };
  61067. static ma_node_config ma_engine_node_base_node_config_init(const ma_engine_node_config* pConfig)
  61068. {
  61069. ma_node_config baseNodeConfig;
  61070. if (pConfig->type == ma_engine_node_type_sound) {
  61071. /* Sound. */
  61072. baseNodeConfig = ma_node_config_init();
  61073. baseNodeConfig.vtable = &g_ma_engine_node_vtable__sound;
  61074. baseNodeConfig.initialState = ma_node_state_stopped; /* Sounds are stopped by default. */
  61075. } else {
  61076. /* Group. */
  61077. baseNodeConfig = ma_node_config_init();
  61078. baseNodeConfig.vtable = &g_ma_engine_node_vtable__group;
  61079. baseNodeConfig.initialState = ma_node_state_started; /* Groups are started by default. */
  61080. }
  61081. return baseNodeConfig;
  61082. }
  61083. static ma_spatializer_config ma_engine_node_spatializer_config_init(const ma_node_config* pBaseNodeConfig)
  61084. {
  61085. return ma_spatializer_config_init(pBaseNodeConfig->pInputChannels[0], pBaseNodeConfig->pOutputChannels[0]);
  61086. }
  61087. typedef struct
  61088. {
  61089. size_t sizeInBytes;
  61090. size_t baseNodeOffset;
  61091. size_t resamplerOffset;
  61092. size_t spatializerOffset;
  61093. size_t gainerOffset;
  61094. } ma_engine_node_heap_layout;
  61095. static ma_result ma_engine_node_get_heap_layout(const ma_engine_node_config* pConfig, ma_engine_node_heap_layout* pHeapLayout)
  61096. {
  61097. ma_result result;
  61098. size_t tempHeapSize;
  61099. ma_node_config baseNodeConfig;
  61100. ma_linear_resampler_config resamplerConfig;
  61101. ma_spatializer_config spatializerConfig;
  61102. ma_gainer_config gainerConfig;
  61103. ma_uint32 channelsIn;
  61104. ma_uint32 channelsOut;
  61105. ma_channel defaultStereoChannelMap[2] = {MA_CHANNEL_SIDE_LEFT, MA_CHANNEL_SIDE_RIGHT}; /* <-- Consistent with the default channel map of a stereo listener. Means channel conversion can run on a fast path. */
  61106. MA_ASSERT(pHeapLayout);
  61107. MA_ZERO_OBJECT(pHeapLayout);
  61108. if (pConfig == NULL) {
  61109. return MA_INVALID_ARGS;
  61110. }
  61111. if (pConfig->pEngine == NULL) {
  61112. return MA_INVALID_ARGS; /* An engine must be specified. */
  61113. }
  61114. pHeapLayout->sizeInBytes = 0;
  61115. channelsIn = (pConfig->channelsIn != 0) ? pConfig->channelsIn : ma_engine_get_channels(pConfig->pEngine);
  61116. channelsOut = (pConfig->channelsOut != 0) ? pConfig->channelsOut : ma_engine_get_channels(pConfig->pEngine);
  61117. /* Base node. */
  61118. baseNodeConfig = ma_engine_node_base_node_config_init(pConfig);
  61119. baseNodeConfig.pInputChannels = &channelsIn;
  61120. baseNodeConfig.pOutputChannels = &channelsOut;
  61121. result = ma_node_get_heap_size(ma_engine_get_node_graph(pConfig->pEngine), &baseNodeConfig, &tempHeapSize);
  61122. if (result != MA_SUCCESS) {
  61123. return result; /* Failed to retrieve the size of the heap for the base node. */
  61124. }
  61125. pHeapLayout->baseNodeOffset = pHeapLayout->sizeInBytes;
  61126. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  61127. /* Resmapler. */
  61128. resamplerConfig = ma_linear_resampler_config_init(ma_format_f32, channelsIn, 1, 1); /* Input and output sample rates don't affect the calculation of the heap size. */
  61129. resamplerConfig.lpfOrder = 0;
  61130. result = ma_linear_resampler_get_heap_size(&resamplerConfig, &tempHeapSize);
  61131. if (result != MA_SUCCESS) {
  61132. return result; /* Failed to retrieve the size of the heap for the resampler. */
  61133. }
  61134. pHeapLayout->resamplerOffset = pHeapLayout->sizeInBytes;
  61135. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  61136. /* Spatializer. */
  61137. spatializerConfig = ma_engine_node_spatializer_config_init(&baseNodeConfig);
  61138. if (spatializerConfig.channelsIn == 2) {
  61139. spatializerConfig.pChannelMapIn = defaultStereoChannelMap;
  61140. }
  61141. result = ma_spatializer_get_heap_size(&spatializerConfig, &tempHeapSize);
  61142. if (result != MA_SUCCESS) {
  61143. return result; /* Failed to retrieve the size of the heap for the spatializer. */
  61144. }
  61145. pHeapLayout->spatializerOffset = pHeapLayout->sizeInBytes;
  61146. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  61147. /* Gainer. Will not be used if we are not using smoothing. */
  61148. if (pConfig->volumeSmoothTimeInPCMFrames > 0) {
  61149. gainerConfig = ma_gainer_config_init(channelsIn, pConfig->volumeSmoothTimeInPCMFrames);
  61150. result = ma_gainer_get_heap_size(&gainerConfig, &tempHeapSize);
  61151. if (result != MA_SUCCESS) {
  61152. return result;
  61153. }
  61154. pHeapLayout->gainerOffset = pHeapLayout->sizeInBytes;
  61155. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  61156. }
  61157. return MA_SUCCESS;
  61158. }
  61159. MA_API ma_result ma_engine_node_get_heap_size(const ma_engine_node_config* pConfig, size_t* pHeapSizeInBytes)
  61160. {
  61161. ma_result result;
  61162. ma_engine_node_heap_layout heapLayout;
  61163. if (pHeapSizeInBytes == NULL) {
  61164. return MA_INVALID_ARGS;
  61165. }
  61166. *pHeapSizeInBytes = 0;
  61167. result = ma_engine_node_get_heap_layout(pConfig, &heapLayout);
  61168. if (result != MA_SUCCESS) {
  61169. return result;
  61170. }
  61171. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  61172. return MA_SUCCESS;
  61173. }
  61174. MA_API ma_result ma_engine_node_init_preallocated(const ma_engine_node_config* pConfig, void* pHeap, ma_engine_node* pEngineNode)
  61175. {
  61176. ma_result result;
  61177. ma_engine_node_heap_layout heapLayout;
  61178. ma_node_config baseNodeConfig;
  61179. ma_linear_resampler_config resamplerConfig;
  61180. ma_fader_config faderConfig;
  61181. ma_spatializer_config spatializerConfig;
  61182. ma_panner_config pannerConfig;
  61183. ma_gainer_config gainerConfig;
  61184. ma_uint32 channelsIn;
  61185. ma_uint32 channelsOut;
  61186. ma_channel defaultStereoChannelMap[2] = {MA_CHANNEL_SIDE_LEFT, MA_CHANNEL_SIDE_RIGHT}; /* <-- Consistent with the default channel map of a stereo listener. Means channel conversion can run on a fast path. */
  61187. if (pEngineNode == NULL) {
  61188. return MA_INVALID_ARGS;
  61189. }
  61190. MA_ZERO_OBJECT(pEngineNode);
  61191. result = ma_engine_node_get_heap_layout(pConfig, &heapLayout);
  61192. if (result != MA_SUCCESS) {
  61193. return result;
  61194. }
  61195. if (pConfig->pinnedListenerIndex != MA_LISTENER_INDEX_CLOSEST && pConfig->pinnedListenerIndex >= ma_engine_get_listener_count(pConfig->pEngine)) {
  61196. return MA_INVALID_ARGS; /* Invalid listener. */
  61197. }
  61198. pEngineNode->_pHeap = pHeap;
  61199. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  61200. pEngineNode->pEngine = pConfig->pEngine;
  61201. pEngineNode->sampleRate = (pConfig->sampleRate > 0) ? pConfig->sampleRate : ma_engine_get_sample_rate(pEngineNode->pEngine);
  61202. pEngineNode->volumeSmoothTimeInPCMFrames = pConfig->volumeSmoothTimeInPCMFrames;
  61203. pEngineNode->monoExpansionMode = pConfig->monoExpansionMode;
  61204. ma_atomic_float_set(&pEngineNode->volume, 1);
  61205. pEngineNode->pitch = 1;
  61206. pEngineNode->oldPitch = 1;
  61207. pEngineNode->oldDopplerPitch = 1;
  61208. pEngineNode->isPitchDisabled = pConfig->isPitchDisabled;
  61209. pEngineNode->isSpatializationDisabled = pConfig->isSpatializationDisabled;
  61210. pEngineNode->pinnedListenerIndex = pConfig->pinnedListenerIndex;
  61211. channelsIn = (pConfig->channelsIn != 0) ? pConfig->channelsIn : ma_engine_get_channels(pConfig->pEngine);
  61212. channelsOut = (pConfig->channelsOut != 0) ? pConfig->channelsOut : ma_engine_get_channels(pConfig->pEngine);
  61213. /*
  61214. If the sample rate of the sound is different to the engine, make sure pitching is enabled so that the resampler
  61215. is activated. Not doing this will result in the sound not being resampled if MA_SOUND_FLAG_NO_PITCH is used.
  61216. */
  61217. if (pEngineNode->sampleRate != ma_engine_get_sample_rate(pEngineNode->pEngine)) {
  61218. pEngineNode->isPitchDisabled = MA_FALSE;
  61219. }
  61220. /* Base node. */
  61221. baseNodeConfig = ma_engine_node_base_node_config_init(pConfig);
  61222. baseNodeConfig.pInputChannels = &channelsIn;
  61223. baseNodeConfig.pOutputChannels = &channelsOut;
  61224. result = ma_node_init_preallocated(&pConfig->pEngine->nodeGraph, &baseNodeConfig, ma_offset_ptr(pHeap, heapLayout.baseNodeOffset), &pEngineNode->baseNode);
  61225. if (result != MA_SUCCESS) {
  61226. goto error0;
  61227. }
  61228. /*
  61229. We can now initialize the effects we need in order to implement the engine node. There's a
  61230. defined order of operations here, mainly centered around when we convert our channels from the
  61231. data source's native channel count to the engine's channel count. As a rule, we want to do as
  61232. much computation as possible before spatialization because there's a chance that will increase
  61233. the channel count, thereby increasing the amount of work needing to be done to process.
  61234. */
  61235. /* We'll always do resampling first. */
  61236. resamplerConfig = ma_linear_resampler_config_init(ma_format_f32, baseNodeConfig.pInputChannels[0], pEngineNode->sampleRate, ma_engine_get_sample_rate(pEngineNode->pEngine));
  61237. resamplerConfig.lpfOrder = 0; /* <-- Need to disable low-pass filtering for pitch shifting for now because there's cases where the biquads are becoming unstable. Need to figure out a better fix for this. */
  61238. result = ma_linear_resampler_init_preallocated(&resamplerConfig, ma_offset_ptr(pHeap, heapLayout.resamplerOffset), &pEngineNode->resampler);
  61239. if (result != MA_SUCCESS) {
  61240. goto error1;
  61241. }
  61242. /* After resampling will come the fader. */
  61243. faderConfig = ma_fader_config_init(ma_format_f32, baseNodeConfig.pInputChannels[0], ma_engine_get_sample_rate(pEngineNode->pEngine));
  61244. result = ma_fader_init(&faderConfig, &pEngineNode->fader);
  61245. if (result != MA_SUCCESS) {
  61246. goto error2;
  61247. }
  61248. /*
  61249. Spatialization comes next. We spatialize based ont he node's output channel count. It's up the caller to
  61250. ensure channels counts link up correctly in the node graph.
  61251. */
  61252. spatializerConfig = ma_engine_node_spatializer_config_init(&baseNodeConfig);
  61253. spatializerConfig.gainSmoothTimeInFrames = pEngineNode->pEngine->gainSmoothTimeInFrames;
  61254. if (spatializerConfig.channelsIn == 2) {
  61255. spatializerConfig.pChannelMapIn = defaultStereoChannelMap;
  61256. }
  61257. result = ma_spatializer_init_preallocated(&spatializerConfig, ma_offset_ptr(pHeap, heapLayout.spatializerOffset), &pEngineNode->spatializer);
  61258. if (result != MA_SUCCESS) {
  61259. goto error2;
  61260. }
  61261. /*
  61262. After spatialization comes panning. We need to do this after spatialization because otherwise we wouldn't
  61263. be able to pan mono sounds.
  61264. */
  61265. pannerConfig = ma_panner_config_init(ma_format_f32, baseNodeConfig.pOutputChannels[0]);
  61266. result = ma_panner_init(&pannerConfig, &pEngineNode->panner);
  61267. if (result != MA_SUCCESS) {
  61268. goto error3;
  61269. }
  61270. /* We'll need a gainer for smoothing out volume changes if we have a non-zero smooth time. We apply this before converting to the output channel count. */
  61271. if (pConfig->volumeSmoothTimeInPCMFrames > 0) {
  61272. gainerConfig = ma_gainer_config_init(channelsIn, pConfig->volumeSmoothTimeInPCMFrames);
  61273. result = ma_gainer_init_preallocated(&gainerConfig, ma_offset_ptr(pHeap, heapLayout.gainerOffset), &pEngineNode->volumeGainer);
  61274. if (result != MA_SUCCESS) {
  61275. goto error3;
  61276. }
  61277. }
  61278. return MA_SUCCESS;
  61279. /* No need for allocation callbacks here because we use a preallocated heap. */
  61280. error3: ma_spatializer_uninit(&pEngineNode->spatializer, NULL);
  61281. error2: ma_linear_resampler_uninit(&pEngineNode->resampler, NULL);
  61282. error1: ma_node_uninit(&pEngineNode->baseNode, NULL);
  61283. error0: return result;
  61284. }
  61285. MA_API ma_result ma_engine_node_init(const ma_engine_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_engine_node* pEngineNode)
  61286. {
  61287. ma_result result;
  61288. size_t heapSizeInBytes;
  61289. void* pHeap;
  61290. result = ma_engine_node_get_heap_size(pConfig, &heapSizeInBytes);
  61291. if (result != MA_SUCCESS) {
  61292. return result;
  61293. }
  61294. if (heapSizeInBytes > 0) {
  61295. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  61296. if (pHeap == NULL) {
  61297. return MA_OUT_OF_MEMORY;
  61298. }
  61299. } else {
  61300. pHeap = NULL;
  61301. }
  61302. result = ma_engine_node_init_preallocated(pConfig, pHeap, pEngineNode);
  61303. if (result != MA_SUCCESS) {
  61304. ma_free(pHeap, pAllocationCallbacks);
  61305. return result;
  61306. }
  61307. pEngineNode->_ownsHeap = MA_TRUE;
  61308. return MA_SUCCESS;
  61309. }
  61310. MA_API void ma_engine_node_uninit(ma_engine_node* pEngineNode, const ma_allocation_callbacks* pAllocationCallbacks)
  61311. {
  61312. /*
  61313. The base node always needs to be uninitialized first to ensure it's detached from the graph completely before we
  61314. destroy anything that might be in the middle of being used by the processing function.
  61315. */
  61316. ma_node_uninit(&pEngineNode->baseNode, pAllocationCallbacks);
  61317. /* Now that the node has been uninitialized we can safely uninitialize the rest. */
  61318. if (pEngineNode->volumeSmoothTimeInPCMFrames > 0) {
  61319. ma_gainer_uninit(&pEngineNode->volumeGainer, pAllocationCallbacks);
  61320. }
  61321. ma_spatializer_uninit(&pEngineNode->spatializer, pAllocationCallbacks);
  61322. ma_linear_resampler_uninit(&pEngineNode->resampler, pAllocationCallbacks);
  61323. /* Free the heap last. */
  61324. if (pEngineNode->_ownsHeap) {
  61325. ma_free(pEngineNode->_pHeap, pAllocationCallbacks);
  61326. }
  61327. }
  61328. MA_API ma_sound_config ma_sound_config_init(void)
  61329. {
  61330. return ma_sound_config_init_2(NULL);
  61331. }
  61332. MA_API ma_sound_config ma_sound_config_init_2(ma_engine* pEngine)
  61333. {
  61334. ma_sound_config config;
  61335. MA_ZERO_OBJECT(&config);
  61336. if (pEngine != NULL) {
  61337. config.monoExpansionMode = pEngine->monoExpansionMode;
  61338. } else {
  61339. config.monoExpansionMode = ma_mono_expansion_mode_default;
  61340. }
  61341. config.rangeEndInPCMFrames = ~((ma_uint64)0);
  61342. config.loopPointEndInPCMFrames = ~((ma_uint64)0);
  61343. return config;
  61344. }
  61345. MA_API ma_sound_group_config ma_sound_group_config_init(void)
  61346. {
  61347. return ma_sound_group_config_init_2(NULL);
  61348. }
  61349. MA_API ma_sound_group_config ma_sound_group_config_init_2(ma_engine* pEngine)
  61350. {
  61351. ma_sound_group_config config;
  61352. MA_ZERO_OBJECT(&config);
  61353. if (pEngine != NULL) {
  61354. config.monoExpansionMode = pEngine->monoExpansionMode;
  61355. } else {
  61356. config.monoExpansionMode = ma_mono_expansion_mode_default;
  61357. }
  61358. return config;
  61359. }
  61360. MA_API ma_engine_config ma_engine_config_init(void)
  61361. {
  61362. ma_engine_config config;
  61363. MA_ZERO_OBJECT(&config);
  61364. config.listenerCount = 1; /* Always want at least one listener. */
  61365. config.monoExpansionMode = ma_mono_expansion_mode_default;
  61366. return config;
  61367. }
  61368. #if !defined(MA_NO_DEVICE_IO)
  61369. static void ma_engine_data_callback_internal(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  61370. {
  61371. ma_engine* pEngine = (ma_engine*)pDevice->pUserData;
  61372. (void)pFramesIn;
  61373. /*
  61374. Experiment: Try processing a resource manager job if we're on the Emscripten build.
  61375. This serves two purposes:
  61376. 1) It ensures jobs are actually processed at some point since we cannot guarantee that the
  61377. caller is doing the right thing and calling ma_resource_manager_process_next_job(); and
  61378. 2) It's an attempt at working around an issue where processing jobs on the Emscripten main
  61379. loop doesn't work as well as it should. When trying to load sounds without the `DECODE`
  61380. flag or with the `ASYNC` flag, the sound data is just not able to be loaded in time
  61381. before the callback is processed. I think it's got something to do with the single-
  61382. threaded nature of Web, but I'm not entirely sure.
  61383. */
  61384. #if !defined(MA_NO_RESOURCE_MANAGER) && defined(MA_EMSCRIPTEN)
  61385. {
  61386. if (pEngine->pResourceManager != NULL) {
  61387. if ((pEngine->pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) != 0) {
  61388. ma_resource_manager_process_next_job(pEngine->pResourceManager);
  61389. }
  61390. }
  61391. }
  61392. #endif
  61393. ma_engine_read_pcm_frames(pEngine, pFramesOut, frameCount, NULL);
  61394. }
  61395. #endif
  61396. MA_API ma_result ma_engine_init(const ma_engine_config* pConfig, ma_engine* pEngine)
  61397. {
  61398. ma_result result;
  61399. ma_node_graph_config nodeGraphConfig;
  61400. ma_engine_config engineConfig;
  61401. ma_spatializer_listener_config listenerConfig;
  61402. ma_uint32 iListener;
  61403. if (pEngine == NULL) {
  61404. return MA_INVALID_ARGS;
  61405. }
  61406. MA_ZERO_OBJECT(pEngine);
  61407. /* The config is allowed to be NULL in which case we use defaults for everything. */
  61408. if (pConfig != NULL) {
  61409. engineConfig = *pConfig;
  61410. } else {
  61411. engineConfig = ma_engine_config_init();
  61412. }
  61413. pEngine->monoExpansionMode = engineConfig.monoExpansionMode;
  61414. pEngine->defaultVolumeSmoothTimeInPCMFrames = engineConfig.defaultVolumeSmoothTimeInPCMFrames;
  61415. ma_allocation_callbacks_init_copy(&pEngine->allocationCallbacks, &engineConfig.allocationCallbacks);
  61416. #if !defined(MA_NO_RESOURCE_MANAGER)
  61417. {
  61418. pEngine->pResourceManager = engineConfig.pResourceManager;
  61419. }
  61420. #endif
  61421. #if !defined(MA_NO_DEVICE_IO)
  61422. {
  61423. pEngine->pDevice = engineConfig.pDevice;
  61424. /* If we don't have a device, we need one. */
  61425. if (pEngine->pDevice == NULL && engineConfig.noDevice == MA_FALSE) {
  61426. ma_device_config deviceConfig;
  61427. pEngine->pDevice = (ma_device*)ma_malloc(sizeof(*pEngine->pDevice), &pEngine->allocationCallbacks);
  61428. if (pEngine->pDevice == NULL) {
  61429. return MA_OUT_OF_MEMORY;
  61430. }
  61431. deviceConfig = ma_device_config_init(ma_device_type_playback);
  61432. deviceConfig.playback.pDeviceID = engineConfig.pPlaybackDeviceID;
  61433. deviceConfig.playback.format = ma_format_f32;
  61434. deviceConfig.playback.channels = engineConfig.channels;
  61435. deviceConfig.sampleRate = engineConfig.sampleRate;
  61436. deviceConfig.dataCallback = ma_engine_data_callback_internal;
  61437. deviceConfig.pUserData = pEngine;
  61438. deviceConfig.notificationCallback = engineConfig.notificationCallback;
  61439. deviceConfig.periodSizeInFrames = engineConfig.periodSizeInFrames;
  61440. deviceConfig.periodSizeInMilliseconds = engineConfig.periodSizeInMilliseconds;
  61441. deviceConfig.noPreSilencedOutputBuffer = MA_TRUE; /* We'll always be outputting to every frame in the callback so there's no need for a pre-silenced buffer. */
  61442. deviceConfig.noClip = MA_TRUE; /* The engine will do clipping itself. */
  61443. if (engineConfig.pContext == NULL) {
  61444. ma_context_config contextConfig = ma_context_config_init();
  61445. contextConfig.allocationCallbacks = pEngine->allocationCallbacks;
  61446. contextConfig.pLog = engineConfig.pLog;
  61447. /* If the engine config does not specify a log, use the resource manager's if we have one. */
  61448. #ifndef MA_NO_RESOURCE_MANAGER
  61449. {
  61450. if (contextConfig.pLog == NULL && engineConfig.pResourceManager != NULL) {
  61451. contextConfig.pLog = ma_resource_manager_get_log(engineConfig.pResourceManager);
  61452. }
  61453. }
  61454. #endif
  61455. result = ma_device_init_ex(NULL, 0, &contextConfig, &deviceConfig, pEngine->pDevice);
  61456. } else {
  61457. result = ma_device_init(engineConfig.pContext, &deviceConfig, pEngine->pDevice);
  61458. }
  61459. if (result != MA_SUCCESS) {
  61460. ma_free(pEngine->pDevice, &pEngine->allocationCallbacks);
  61461. pEngine->pDevice = NULL;
  61462. return result;
  61463. }
  61464. pEngine->ownsDevice = MA_TRUE;
  61465. }
  61466. /* Update the channel count and sample rate of the engine config so we can reference it below. */
  61467. if (pEngine->pDevice != NULL) {
  61468. engineConfig.channels = pEngine->pDevice->playback.channels;
  61469. engineConfig.sampleRate = pEngine->pDevice->sampleRate;
  61470. }
  61471. }
  61472. #endif
  61473. if (engineConfig.channels == 0 || engineConfig.sampleRate == 0) {
  61474. return MA_INVALID_ARGS;
  61475. }
  61476. pEngine->sampleRate = engineConfig.sampleRate;
  61477. /* The engine always uses either the log that was passed into the config, or the context's log is available. */
  61478. if (engineConfig.pLog != NULL) {
  61479. pEngine->pLog = engineConfig.pLog;
  61480. } else {
  61481. #if !defined(MA_NO_DEVICE_IO)
  61482. {
  61483. pEngine->pLog = ma_device_get_log(pEngine->pDevice);
  61484. }
  61485. #else
  61486. {
  61487. pEngine->pLog = NULL;
  61488. }
  61489. #endif
  61490. }
  61491. /* The engine is a node graph. This needs to be initialized after we have the device so we can can determine the channel count. */
  61492. nodeGraphConfig = ma_node_graph_config_init(engineConfig.channels);
  61493. nodeGraphConfig.nodeCacheCapInFrames = (engineConfig.periodSizeInFrames > 0xFFFF) ? 0xFFFF : (ma_uint16)engineConfig.periodSizeInFrames;
  61494. result = ma_node_graph_init(&nodeGraphConfig, &pEngine->allocationCallbacks, &pEngine->nodeGraph);
  61495. if (result != MA_SUCCESS) {
  61496. goto on_error_1;
  61497. }
  61498. /* We need at least one listener. */
  61499. if (engineConfig.listenerCount == 0) {
  61500. engineConfig.listenerCount = 1;
  61501. }
  61502. if (engineConfig.listenerCount > MA_ENGINE_MAX_LISTENERS) {
  61503. result = MA_INVALID_ARGS; /* Too many listeners. */
  61504. goto on_error_1;
  61505. }
  61506. for (iListener = 0; iListener < engineConfig.listenerCount; iListener += 1) {
  61507. listenerConfig = ma_spatializer_listener_config_init(ma_node_graph_get_channels(&pEngine->nodeGraph));
  61508. /*
  61509. If we're using a device, use the device's channel map for the listener. Otherwise just use
  61510. miniaudio's default channel map.
  61511. */
  61512. #if !defined(MA_NO_DEVICE_IO)
  61513. {
  61514. if (pEngine->pDevice != NULL) {
  61515. /*
  61516. Temporarily disabled. There is a subtle bug here where front-left and front-right
  61517. will be used by the device's channel map, but this is not what we want to use for
  61518. spatialization. Instead we want to use side-left and side-right. I need to figure
  61519. out a better solution for this. For now, disabling the use of device channel maps.
  61520. */
  61521. /*listenerConfig.pChannelMapOut = pEngine->pDevice->playback.channelMap;*/
  61522. }
  61523. }
  61524. #endif
  61525. result = ma_spatializer_listener_init(&listenerConfig, &pEngine->allocationCallbacks, &pEngine->listeners[iListener]); /* TODO: Change this to a pre-allocated heap. */
  61526. if (result != MA_SUCCESS) {
  61527. goto on_error_2;
  61528. }
  61529. pEngine->listenerCount += 1;
  61530. }
  61531. /* Gain smoothing for spatialized sounds. */
  61532. pEngine->gainSmoothTimeInFrames = engineConfig.gainSmoothTimeInFrames;
  61533. if (pEngine->gainSmoothTimeInFrames == 0) {
  61534. ma_uint32 gainSmoothTimeInMilliseconds = engineConfig.gainSmoothTimeInMilliseconds;
  61535. if (gainSmoothTimeInMilliseconds == 0) {
  61536. gainSmoothTimeInMilliseconds = 8;
  61537. }
  61538. pEngine->gainSmoothTimeInFrames = (gainSmoothTimeInMilliseconds * ma_engine_get_sample_rate(pEngine)) / 1000; /* 8ms by default. */
  61539. }
  61540. /* We need a resource manager. */
  61541. #ifndef MA_NO_RESOURCE_MANAGER
  61542. {
  61543. if (pEngine->pResourceManager == NULL) {
  61544. ma_resource_manager_config resourceManagerConfig;
  61545. pEngine->pResourceManager = (ma_resource_manager*)ma_malloc(sizeof(*pEngine->pResourceManager), &pEngine->allocationCallbacks);
  61546. if (pEngine->pResourceManager == NULL) {
  61547. result = MA_OUT_OF_MEMORY;
  61548. goto on_error_2;
  61549. }
  61550. resourceManagerConfig = ma_resource_manager_config_init();
  61551. resourceManagerConfig.pLog = pEngine->pLog; /* Always use the engine's log for internally-managed resource managers. */
  61552. resourceManagerConfig.decodedFormat = ma_format_f32;
  61553. resourceManagerConfig.decodedChannels = 0; /* Leave the decoded channel count as 0 so we can get good spatialization. */
  61554. resourceManagerConfig.decodedSampleRate = ma_engine_get_sample_rate(pEngine);
  61555. ma_allocation_callbacks_init_copy(&resourceManagerConfig.allocationCallbacks, &pEngine->allocationCallbacks);
  61556. resourceManagerConfig.pVFS = engineConfig.pResourceManagerVFS;
  61557. /* The Emscripten build cannot use threads. */
  61558. #if defined(MA_EMSCRIPTEN)
  61559. {
  61560. resourceManagerConfig.jobThreadCount = 0;
  61561. resourceManagerConfig.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING;
  61562. }
  61563. #endif
  61564. result = ma_resource_manager_init(&resourceManagerConfig, pEngine->pResourceManager);
  61565. if (result != MA_SUCCESS) {
  61566. goto on_error_3;
  61567. }
  61568. pEngine->ownsResourceManager = MA_TRUE;
  61569. }
  61570. }
  61571. #endif
  61572. /* Setup some stuff for inlined sounds. That is sounds played with ma_engine_play_sound(). */
  61573. pEngine->inlinedSoundLock = 0;
  61574. pEngine->pInlinedSoundHead = NULL;
  61575. /* Start the engine if required. This should always be the last step. */
  61576. #if !defined(MA_NO_DEVICE_IO)
  61577. {
  61578. if (engineConfig.noAutoStart == MA_FALSE && pEngine->pDevice != NULL) {
  61579. result = ma_engine_start(pEngine);
  61580. if (result != MA_SUCCESS) {
  61581. goto on_error_4; /* Failed to start the engine. */
  61582. }
  61583. }
  61584. }
  61585. #endif
  61586. return MA_SUCCESS;
  61587. #if !defined(MA_NO_DEVICE_IO)
  61588. on_error_4:
  61589. #endif
  61590. #if !defined(MA_NO_RESOURCE_MANAGER)
  61591. on_error_3:
  61592. if (pEngine->ownsResourceManager) {
  61593. ma_free(pEngine->pResourceManager, &pEngine->allocationCallbacks);
  61594. }
  61595. #endif /* MA_NO_RESOURCE_MANAGER */
  61596. on_error_2:
  61597. for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) {
  61598. ma_spatializer_listener_uninit(&pEngine->listeners[iListener], &pEngine->allocationCallbacks);
  61599. }
  61600. ma_node_graph_uninit(&pEngine->nodeGraph, &pEngine->allocationCallbacks);
  61601. on_error_1:
  61602. #if !defined(MA_NO_DEVICE_IO)
  61603. {
  61604. if (pEngine->ownsDevice) {
  61605. ma_device_uninit(pEngine->pDevice);
  61606. ma_free(pEngine->pDevice, &pEngine->allocationCallbacks);
  61607. }
  61608. }
  61609. #endif
  61610. return result;
  61611. }
  61612. MA_API void ma_engine_uninit(ma_engine* pEngine)
  61613. {
  61614. ma_uint32 iListener;
  61615. if (pEngine == NULL) {
  61616. return;
  61617. }
  61618. /* The device must be uninitialized before the node graph to ensure the audio thread doesn't try accessing it. */
  61619. #if !defined(MA_NO_DEVICE_IO)
  61620. {
  61621. if (pEngine->ownsDevice) {
  61622. ma_device_uninit(pEngine->pDevice);
  61623. ma_free(pEngine->pDevice, &pEngine->allocationCallbacks);
  61624. } else {
  61625. if (pEngine->pDevice != NULL) {
  61626. ma_device_stop(pEngine->pDevice);
  61627. }
  61628. }
  61629. }
  61630. #endif
  61631. /*
  61632. All inlined sounds need to be deleted. I'm going to use a lock here just to future proof in case
  61633. I want to do some kind of garbage collection later on.
  61634. */
  61635. ma_spinlock_lock(&pEngine->inlinedSoundLock);
  61636. {
  61637. for (;;) {
  61638. ma_sound_inlined* pSoundToDelete = pEngine->pInlinedSoundHead;
  61639. if (pSoundToDelete == NULL) {
  61640. break; /* Done. */
  61641. }
  61642. pEngine->pInlinedSoundHead = pSoundToDelete->pNext;
  61643. ma_sound_uninit(&pSoundToDelete->sound);
  61644. ma_free(pSoundToDelete, &pEngine->allocationCallbacks);
  61645. }
  61646. }
  61647. ma_spinlock_unlock(&pEngine->inlinedSoundLock);
  61648. for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) {
  61649. ma_spatializer_listener_uninit(&pEngine->listeners[iListener], &pEngine->allocationCallbacks);
  61650. }
  61651. /* Make sure the node graph is uninitialized after the audio thread has been shutdown to prevent accessing of the node graph after being uninitialized. */
  61652. ma_node_graph_uninit(&pEngine->nodeGraph, &pEngine->allocationCallbacks);
  61653. /* Uninitialize the resource manager last to ensure we don't have a thread still trying to access it. */
  61654. #ifndef MA_NO_RESOURCE_MANAGER
  61655. if (pEngine->ownsResourceManager) {
  61656. ma_resource_manager_uninit(pEngine->pResourceManager);
  61657. ma_free(pEngine->pResourceManager, &pEngine->allocationCallbacks);
  61658. }
  61659. #endif
  61660. }
  61661. MA_API ma_result ma_engine_read_pcm_frames(ma_engine* pEngine, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  61662. {
  61663. return ma_node_graph_read_pcm_frames(&pEngine->nodeGraph, pFramesOut, frameCount, pFramesRead);
  61664. }
  61665. MA_API ma_node_graph* ma_engine_get_node_graph(ma_engine* pEngine)
  61666. {
  61667. if (pEngine == NULL) {
  61668. return NULL;
  61669. }
  61670. return &pEngine->nodeGraph;
  61671. }
  61672. #if !defined(MA_NO_RESOURCE_MANAGER)
  61673. MA_API ma_resource_manager* ma_engine_get_resource_manager(ma_engine* pEngine)
  61674. {
  61675. if (pEngine == NULL) {
  61676. return NULL;
  61677. }
  61678. #if !defined(MA_NO_RESOURCE_MANAGER)
  61679. {
  61680. return pEngine->pResourceManager;
  61681. }
  61682. #else
  61683. {
  61684. return NULL;
  61685. }
  61686. #endif
  61687. }
  61688. #endif
  61689. MA_API ma_device* ma_engine_get_device(ma_engine* pEngine)
  61690. {
  61691. if (pEngine == NULL) {
  61692. return NULL;
  61693. }
  61694. #if !defined(MA_NO_DEVICE_IO)
  61695. {
  61696. return pEngine->pDevice;
  61697. }
  61698. #else
  61699. {
  61700. return NULL;
  61701. }
  61702. #endif
  61703. }
  61704. MA_API ma_log* ma_engine_get_log(ma_engine* pEngine)
  61705. {
  61706. if (pEngine == NULL) {
  61707. return NULL;
  61708. }
  61709. if (pEngine->pLog != NULL) {
  61710. return pEngine->pLog;
  61711. } else {
  61712. #if !defined(MA_NO_DEVICE_IO)
  61713. {
  61714. return ma_device_get_log(ma_engine_get_device(pEngine));
  61715. }
  61716. #else
  61717. {
  61718. return NULL;
  61719. }
  61720. #endif
  61721. }
  61722. }
  61723. MA_API ma_node* ma_engine_get_endpoint(ma_engine* pEngine)
  61724. {
  61725. return ma_node_graph_get_endpoint(&pEngine->nodeGraph);
  61726. }
  61727. MA_API ma_uint64 ma_engine_get_time_in_pcm_frames(const ma_engine* pEngine)
  61728. {
  61729. return ma_node_graph_get_time(&pEngine->nodeGraph);
  61730. }
  61731. MA_API ma_uint64 ma_engine_get_time_in_milliseconds(const ma_engine* pEngine)
  61732. {
  61733. return ma_engine_get_time_in_pcm_frames(pEngine) * 1000 / ma_engine_get_sample_rate(pEngine);
  61734. }
  61735. MA_API ma_result ma_engine_set_time_in_pcm_frames(ma_engine* pEngine, ma_uint64 globalTime)
  61736. {
  61737. return ma_node_graph_set_time(&pEngine->nodeGraph, globalTime);
  61738. }
  61739. MA_API ma_result ma_engine_set_time_in_milliseconds(ma_engine* pEngine, ma_uint64 globalTime)
  61740. {
  61741. return ma_engine_set_time_in_pcm_frames(pEngine, globalTime * ma_engine_get_sample_rate(pEngine) / 1000);
  61742. }
  61743. MA_API ma_uint64 ma_engine_get_time(const ma_engine* pEngine)
  61744. {
  61745. return ma_engine_get_time_in_pcm_frames(pEngine);
  61746. }
  61747. MA_API ma_result ma_engine_set_time(ma_engine* pEngine, ma_uint64 globalTime)
  61748. {
  61749. return ma_engine_set_time_in_pcm_frames(pEngine, globalTime);
  61750. }
  61751. MA_API ma_uint32 ma_engine_get_channels(const ma_engine* pEngine)
  61752. {
  61753. return ma_node_graph_get_channels(&pEngine->nodeGraph);
  61754. }
  61755. MA_API ma_uint32 ma_engine_get_sample_rate(const ma_engine* pEngine)
  61756. {
  61757. if (pEngine == NULL) {
  61758. return 0;
  61759. }
  61760. return pEngine->sampleRate;
  61761. }
  61762. MA_API ma_result ma_engine_start(ma_engine* pEngine)
  61763. {
  61764. ma_result result;
  61765. if (pEngine == NULL) {
  61766. return MA_INVALID_ARGS;
  61767. }
  61768. #if !defined(MA_NO_DEVICE_IO)
  61769. {
  61770. if (pEngine->pDevice != NULL) {
  61771. result = ma_device_start(pEngine->pDevice);
  61772. } else {
  61773. result = MA_INVALID_OPERATION; /* The engine is running without a device which means there's no real notion of "starting" the engine. */
  61774. }
  61775. }
  61776. #else
  61777. {
  61778. result = MA_INVALID_OPERATION; /* Device IO is disabled, so there's no real notion of "starting" the engine. */
  61779. }
  61780. #endif
  61781. if (result != MA_SUCCESS) {
  61782. return result;
  61783. }
  61784. return MA_SUCCESS;
  61785. }
  61786. MA_API ma_result ma_engine_stop(ma_engine* pEngine)
  61787. {
  61788. ma_result result;
  61789. if (pEngine == NULL) {
  61790. return MA_INVALID_ARGS;
  61791. }
  61792. #if !defined(MA_NO_DEVICE_IO)
  61793. {
  61794. if (pEngine->pDevice != NULL) {
  61795. result = ma_device_stop(pEngine->pDevice);
  61796. } else {
  61797. result = MA_INVALID_OPERATION; /* The engine is running without a device which means there's no real notion of "stopping" the engine. */
  61798. }
  61799. }
  61800. #else
  61801. {
  61802. result = MA_INVALID_OPERATION; /* Device IO is disabled, so there's no real notion of "stopping" the engine. */
  61803. }
  61804. #endif
  61805. if (result != MA_SUCCESS) {
  61806. return result;
  61807. }
  61808. return MA_SUCCESS;
  61809. }
  61810. MA_API ma_result ma_engine_set_volume(ma_engine* pEngine, float volume)
  61811. {
  61812. if (pEngine == NULL) {
  61813. return MA_INVALID_ARGS;
  61814. }
  61815. return ma_node_set_output_bus_volume(ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0, volume);
  61816. }
  61817. MA_API ma_result ma_engine_set_gain_db(ma_engine* pEngine, float gainDB)
  61818. {
  61819. if (pEngine == NULL) {
  61820. return MA_INVALID_ARGS;
  61821. }
  61822. return ma_node_set_output_bus_volume(ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0, ma_volume_db_to_linear(gainDB));
  61823. }
  61824. MA_API ma_uint32 ma_engine_get_listener_count(const ma_engine* pEngine)
  61825. {
  61826. if (pEngine == NULL) {
  61827. return 0;
  61828. }
  61829. return pEngine->listenerCount;
  61830. }
  61831. MA_API ma_uint32 ma_engine_find_closest_listener(const ma_engine* pEngine, float absolutePosX, float absolutePosY, float absolutePosZ)
  61832. {
  61833. ma_uint32 iListener;
  61834. ma_uint32 iListenerClosest;
  61835. float closestLen2 = MA_FLT_MAX;
  61836. if (pEngine == NULL || pEngine->listenerCount == 1) {
  61837. return 0;
  61838. }
  61839. iListenerClosest = 0;
  61840. for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) {
  61841. if (ma_engine_listener_is_enabled(pEngine, iListener)) {
  61842. float len2 = ma_vec3f_len2(ma_vec3f_sub(ma_spatializer_listener_get_position(&pEngine->listeners[iListener]), ma_vec3f_init_3f(absolutePosX, absolutePosY, absolutePosZ)));
  61843. if (closestLen2 > len2) {
  61844. closestLen2 = len2;
  61845. iListenerClosest = iListener;
  61846. }
  61847. }
  61848. }
  61849. MA_ASSERT(iListenerClosest < 255);
  61850. return iListenerClosest;
  61851. }
  61852. MA_API void ma_engine_listener_set_position(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  61853. {
  61854. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61855. return;
  61856. }
  61857. ma_spatializer_listener_set_position(&pEngine->listeners[listenerIndex], x, y, z);
  61858. }
  61859. MA_API ma_vec3f ma_engine_listener_get_position(const ma_engine* pEngine, ma_uint32 listenerIndex)
  61860. {
  61861. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61862. return ma_vec3f_init_3f(0, 0, 0);
  61863. }
  61864. return ma_spatializer_listener_get_position(&pEngine->listeners[listenerIndex]);
  61865. }
  61866. MA_API void ma_engine_listener_set_direction(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  61867. {
  61868. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61869. return;
  61870. }
  61871. ma_spatializer_listener_set_direction(&pEngine->listeners[listenerIndex], x, y, z);
  61872. }
  61873. MA_API ma_vec3f ma_engine_listener_get_direction(const ma_engine* pEngine, ma_uint32 listenerIndex)
  61874. {
  61875. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61876. return ma_vec3f_init_3f(0, 0, -1);
  61877. }
  61878. return ma_spatializer_listener_get_direction(&pEngine->listeners[listenerIndex]);
  61879. }
  61880. MA_API void ma_engine_listener_set_velocity(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  61881. {
  61882. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61883. return;
  61884. }
  61885. ma_spatializer_listener_set_velocity(&pEngine->listeners[listenerIndex], x, y, z);
  61886. }
  61887. MA_API ma_vec3f ma_engine_listener_get_velocity(const ma_engine* pEngine, ma_uint32 listenerIndex)
  61888. {
  61889. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61890. return ma_vec3f_init_3f(0, 0, 0);
  61891. }
  61892. return ma_spatializer_listener_get_velocity(&pEngine->listeners[listenerIndex]);
  61893. }
  61894. MA_API void ma_engine_listener_set_cone(ma_engine* pEngine, ma_uint32 listenerIndex, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  61895. {
  61896. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61897. return;
  61898. }
  61899. ma_spatializer_listener_set_cone(&pEngine->listeners[listenerIndex], innerAngleInRadians, outerAngleInRadians, outerGain);
  61900. }
  61901. MA_API void ma_engine_listener_get_cone(const ma_engine* pEngine, ma_uint32 listenerIndex, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  61902. {
  61903. if (pInnerAngleInRadians != NULL) {
  61904. *pInnerAngleInRadians = 0;
  61905. }
  61906. if (pOuterAngleInRadians != NULL) {
  61907. *pOuterAngleInRadians = 0;
  61908. }
  61909. if (pOuterGain != NULL) {
  61910. *pOuterGain = 0;
  61911. }
  61912. ma_spatializer_listener_get_cone(&pEngine->listeners[listenerIndex], pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain);
  61913. }
  61914. MA_API void ma_engine_listener_set_world_up(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  61915. {
  61916. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61917. return;
  61918. }
  61919. ma_spatializer_listener_set_world_up(&pEngine->listeners[listenerIndex], x, y, z);
  61920. }
  61921. MA_API ma_vec3f ma_engine_listener_get_world_up(const ma_engine* pEngine, ma_uint32 listenerIndex)
  61922. {
  61923. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61924. return ma_vec3f_init_3f(0, 1, 0);
  61925. }
  61926. return ma_spatializer_listener_get_world_up(&pEngine->listeners[listenerIndex]);
  61927. }
  61928. MA_API void ma_engine_listener_set_enabled(ma_engine* pEngine, ma_uint32 listenerIndex, ma_bool32 isEnabled)
  61929. {
  61930. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61931. return;
  61932. }
  61933. ma_spatializer_listener_set_enabled(&pEngine->listeners[listenerIndex], isEnabled);
  61934. }
  61935. MA_API ma_bool32 ma_engine_listener_is_enabled(const ma_engine* pEngine, ma_uint32 listenerIndex)
  61936. {
  61937. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  61938. return MA_FALSE;
  61939. }
  61940. return ma_spatializer_listener_is_enabled(&pEngine->listeners[listenerIndex]);
  61941. }
  61942. #ifndef MA_NO_RESOURCE_MANAGER
  61943. MA_API ma_result ma_engine_play_sound_ex(ma_engine* pEngine, const char* pFilePath, ma_node* pNode, ma_uint32 nodeInputBusIndex)
  61944. {
  61945. ma_result result = MA_SUCCESS;
  61946. ma_sound_inlined* pSound = NULL;
  61947. ma_sound_inlined* pNextSound = NULL;
  61948. if (pEngine == NULL || pFilePath == NULL) {
  61949. return MA_INVALID_ARGS;
  61950. }
  61951. /* Attach to the endpoint node if nothing is specicied. */
  61952. if (pNode == NULL) {
  61953. pNode = ma_node_graph_get_endpoint(&pEngine->nodeGraph);
  61954. nodeInputBusIndex = 0;
  61955. }
  61956. /*
  61957. We want to check if we can recycle an already-allocated inlined sound. Since this is just a
  61958. helper I'm not *too* concerned about performance here and I'm happy to use a lock to keep
  61959. the implementation simple. Maybe this can be optimized later if there's enough demand, but
  61960. if this function is being used it probably means the caller doesn't really care too much.
  61961. What we do is check the atEnd flag. When this is true, we can recycle the sound. Otherwise
  61962. we just keep iterating. If we reach the end without finding a sound to recycle we just
  61963. allocate a new one. This doesn't scale well for a massive number of sounds being played
  61964. simultaneously as we don't ever actually free the sound objects. Some kind of garbage
  61965. collection routine might be valuable for this which I'll think about.
  61966. */
  61967. ma_spinlock_lock(&pEngine->inlinedSoundLock);
  61968. {
  61969. ma_uint32 soundFlags = 0;
  61970. for (pNextSound = pEngine->pInlinedSoundHead; pNextSound != NULL; pNextSound = pNextSound->pNext) {
  61971. if (ma_sound_at_end(&pNextSound->sound)) {
  61972. /*
  61973. The sound is at the end which means it's available for recycling. All we need to do
  61974. is uninitialize it and reinitialize it. All we're doing is recycling memory.
  61975. */
  61976. pSound = pNextSound;
  61977. c89atomic_fetch_sub_32(&pEngine->inlinedSoundCount, 1);
  61978. break;
  61979. }
  61980. }
  61981. if (pSound != NULL) {
  61982. /*
  61983. We actually want to detach the sound from the list here. The reason is because we want the sound
  61984. to be in a consistent state at the non-recycled case to simplify the logic below.
  61985. */
  61986. if (pEngine->pInlinedSoundHead == pSound) {
  61987. pEngine->pInlinedSoundHead = pSound->pNext;
  61988. }
  61989. if (pSound->pPrev != NULL) {
  61990. pSound->pPrev->pNext = pSound->pNext;
  61991. }
  61992. if (pSound->pNext != NULL) {
  61993. pSound->pNext->pPrev = pSound->pPrev;
  61994. }
  61995. /* Now the previous sound needs to be uninitialized. */
  61996. ma_sound_uninit(&pNextSound->sound);
  61997. } else {
  61998. /* No sound available for recycling. Allocate one now. */
  61999. pSound = (ma_sound_inlined*)ma_malloc(sizeof(*pSound), &pEngine->allocationCallbacks);
  62000. }
  62001. if (pSound != NULL) { /* Safety check for the allocation above. */
  62002. /*
  62003. At this point we should have memory allocated for the inlined sound. We just need
  62004. to initialize it like a normal sound now.
  62005. */
  62006. soundFlags |= MA_SOUND_FLAG_ASYNC; /* For inlined sounds we don't want to be sitting around waiting for stuff to load so force an async load. */
  62007. soundFlags |= MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT; /* We want specific control over where the sound is attached in the graph. We'll attach it manually just before playing the sound. */
  62008. soundFlags |= MA_SOUND_FLAG_NO_PITCH; /* Pitching isn't usable with inlined sounds, so disable it to save on speed. */
  62009. soundFlags |= MA_SOUND_FLAG_NO_SPATIALIZATION; /* Not currently doing spatialization with inlined sounds, but this might actually change later. For now disable spatialization. Will be removed if we ever add support for spatialization here. */
  62010. result = ma_sound_init_from_file(pEngine, pFilePath, soundFlags, NULL, NULL, &pSound->sound);
  62011. if (result == MA_SUCCESS) {
  62012. /* Now attach the sound to the graph. */
  62013. result = ma_node_attach_output_bus(pSound, 0, pNode, nodeInputBusIndex);
  62014. if (result == MA_SUCCESS) {
  62015. /* At this point the sound should be loaded and we can go ahead and add it to the list. The new item becomes the new head. */
  62016. pSound->pNext = pEngine->pInlinedSoundHead;
  62017. pSound->pPrev = NULL;
  62018. pEngine->pInlinedSoundHead = pSound; /* <-- This is what attaches the sound to the list. */
  62019. if (pSound->pNext != NULL) {
  62020. pSound->pNext->pPrev = pSound;
  62021. }
  62022. } else {
  62023. ma_free(pSound, &pEngine->allocationCallbacks);
  62024. }
  62025. } else {
  62026. ma_free(pSound, &pEngine->allocationCallbacks);
  62027. }
  62028. } else {
  62029. result = MA_OUT_OF_MEMORY;
  62030. }
  62031. }
  62032. ma_spinlock_unlock(&pEngine->inlinedSoundLock);
  62033. if (result != MA_SUCCESS) {
  62034. return result;
  62035. }
  62036. /* Finally we can start playing the sound. */
  62037. result = ma_sound_start(&pSound->sound);
  62038. if (result != MA_SUCCESS) {
  62039. /* Failed to start the sound. We need to mark it for recycling and return an error. */
  62040. c89atomic_exchange_32(&pSound->sound.atEnd, MA_TRUE);
  62041. return result;
  62042. }
  62043. c89atomic_fetch_add_32(&pEngine->inlinedSoundCount, 1);
  62044. return result;
  62045. }
  62046. MA_API ma_result ma_engine_play_sound(ma_engine* pEngine, const char* pFilePath, ma_sound_group* pGroup)
  62047. {
  62048. return ma_engine_play_sound_ex(pEngine, pFilePath, pGroup, 0);
  62049. }
  62050. #endif
  62051. static ma_result ma_sound_preinit(ma_engine* pEngine, ma_sound* pSound)
  62052. {
  62053. if (pSound == NULL) {
  62054. return MA_INVALID_ARGS;
  62055. }
  62056. MA_ZERO_OBJECT(pSound);
  62057. pSound->seekTarget = MA_SEEK_TARGET_NONE;
  62058. if (pEngine == NULL) {
  62059. return MA_INVALID_ARGS;
  62060. }
  62061. return MA_SUCCESS;
  62062. }
  62063. static ma_result ma_sound_init_from_data_source_internal(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound)
  62064. {
  62065. ma_result result;
  62066. ma_engine_node_config engineNodeConfig;
  62067. ma_engine_node_type type; /* Will be set to ma_engine_node_type_group if no data source is specified. */
  62068. /* Do not clear pSound to zero here - that's done at a higher level with ma_sound_preinit(). */
  62069. MA_ASSERT(pEngine != NULL);
  62070. MA_ASSERT(pSound != NULL);
  62071. if (pConfig == NULL) {
  62072. return MA_INVALID_ARGS;
  62073. }
  62074. pSound->pDataSource = pConfig->pDataSource;
  62075. if (pConfig->pDataSource != NULL) {
  62076. type = ma_engine_node_type_sound;
  62077. } else {
  62078. type = ma_engine_node_type_group;
  62079. }
  62080. /*
  62081. Sounds are engine nodes. Before we can initialize this we need to determine the channel count.
  62082. If we can't do this we need to abort. It's up to the caller to ensure they're using a data
  62083. source that provides this information upfront.
  62084. */
  62085. engineNodeConfig = ma_engine_node_config_init(pEngine, type, pConfig->flags);
  62086. engineNodeConfig.channelsIn = pConfig->channelsIn;
  62087. engineNodeConfig.channelsOut = pConfig->channelsOut;
  62088. engineNodeConfig.volumeSmoothTimeInPCMFrames = pConfig->volumeSmoothTimeInPCMFrames;
  62089. engineNodeConfig.monoExpansionMode = pConfig->monoExpansionMode;
  62090. if (engineNodeConfig.volumeSmoothTimeInPCMFrames == 0) {
  62091. engineNodeConfig.volumeSmoothTimeInPCMFrames = pEngine->defaultVolumeSmoothTimeInPCMFrames;
  62092. }
  62093. /* If we're loading from a data source the input channel count needs to be the data source's native channel count. */
  62094. if (pConfig->pDataSource != NULL) {
  62095. result = ma_data_source_get_data_format(pConfig->pDataSource, NULL, &engineNodeConfig.channelsIn, &engineNodeConfig.sampleRate, NULL, 0);
  62096. if (result != MA_SUCCESS) {
  62097. return result; /* Failed to retrieve the channel count. */
  62098. }
  62099. if (engineNodeConfig.channelsIn == 0) {
  62100. return MA_INVALID_OPERATION; /* Invalid channel count. */
  62101. }
  62102. if (engineNodeConfig.channelsOut == MA_SOUND_SOURCE_CHANNEL_COUNT) {
  62103. engineNodeConfig.channelsOut = engineNodeConfig.channelsIn;
  62104. }
  62105. }
  62106. /* Getting here means we should have a valid channel count and we can initialize the engine node. */
  62107. result = ma_engine_node_init(&engineNodeConfig, &pEngine->allocationCallbacks, &pSound->engineNode);
  62108. if (result != MA_SUCCESS) {
  62109. return result;
  62110. }
  62111. /* If no attachment is specified, attach the sound straight to the endpoint. */
  62112. if (pConfig->pInitialAttachment == NULL) {
  62113. /* No group. Attach straight to the endpoint by default, unless the caller has requested that it not. */
  62114. if ((pConfig->flags & MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT) == 0) {
  62115. result = ma_node_attach_output_bus(pSound, 0, ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0);
  62116. }
  62117. } else {
  62118. /* An attachment is specified. Attach to it by default. The sound has only a single output bus, and the config will specify which input bus to attach to. */
  62119. result = ma_node_attach_output_bus(pSound, 0, pConfig->pInitialAttachment, pConfig->initialAttachmentInputBusIndex);
  62120. }
  62121. if (result != MA_SUCCESS) {
  62122. ma_engine_node_uninit(&pSound->engineNode, &pEngine->allocationCallbacks);
  62123. return result;
  62124. }
  62125. /* Apply initial range and looping state to the data source if applicable. */
  62126. if (pConfig->rangeBegInPCMFrames != 0 || pConfig->rangeEndInPCMFrames != ~((ma_uint64)0)) {
  62127. ma_data_source_set_range_in_pcm_frames(ma_sound_get_data_source(pSound), pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames);
  62128. }
  62129. if (pConfig->loopPointBegInPCMFrames != 0 || pConfig->loopPointEndInPCMFrames != ~((ma_uint64)0)) {
  62130. ma_data_source_set_range_in_pcm_frames(ma_sound_get_data_source(pSound), pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames);
  62131. }
  62132. ma_sound_set_looping(pSound, pConfig->isLooping);
  62133. return MA_SUCCESS;
  62134. }
  62135. #ifndef MA_NO_RESOURCE_MANAGER
  62136. MA_API ma_result ma_sound_init_from_file_internal(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound)
  62137. {
  62138. ma_result result = MA_SUCCESS;
  62139. ma_uint32 flags;
  62140. ma_sound_config config;
  62141. ma_resource_manager_pipeline_notifications notifications;
  62142. /*
  62143. The engine requires knowledge of the channel count of the underlying data source before it can
  62144. initialize the sound. Therefore, we need to make the resource manager wait until initialization
  62145. of the underlying data source to be initialized so we can get access to the channel count. To
  62146. do this, the MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT is forced.
  62147. Because we're initializing the data source before the sound, there's a chance the notification
  62148. will get triggered before this function returns. This is OK, so long as the caller is aware of
  62149. it and can avoid accessing the sound from within the notification.
  62150. */
  62151. flags = pConfig->flags | MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT;
  62152. pSound->pResourceManagerDataSource = (ma_resource_manager_data_source*)ma_malloc(sizeof(*pSound->pResourceManagerDataSource), &pEngine->allocationCallbacks);
  62153. if (pSound->pResourceManagerDataSource == NULL) {
  62154. return MA_OUT_OF_MEMORY;
  62155. }
  62156. /* Removed in 0.12. Set pDoneFence on the notifications. */
  62157. notifications = pConfig->initNotifications;
  62158. if (pConfig->pDoneFence != NULL && notifications.done.pFence == NULL) {
  62159. notifications.done.pFence = pConfig->pDoneFence;
  62160. }
  62161. /*
  62162. We must wrap everything around the fence if one was specified. This ensures ma_fence_wait() does
  62163. not return prematurely before the sound has finished initializing.
  62164. */
  62165. if (notifications.done.pFence) { ma_fence_acquire(notifications.done.pFence); }
  62166. {
  62167. ma_resource_manager_data_source_config resourceManagerDataSourceConfig = ma_resource_manager_data_source_config_init();
  62168. resourceManagerDataSourceConfig.pFilePath = pConfig->pFilePath;
  62169. resourceManagerDataSourceConfig.pFilePathW = pConfig->pFilePathW;
  62170. resourceManagerDataSourceConfig.flags = flags;
  62171. resourceManagerDataSourceConfig.pNotifications = &notifications;
  62172. resourceManagerDataSourceConfig.initialSeekPointInPCMFrames = pConfig->initialSeekPointInPCMFrames;
  62173. resourceManagerDataSourceConfig.rangeBegInPCMFrames = pConfig->rangeBegInPCMFrames;
  62174. resourceManagerDataSourceConfig.rangeEndInPCMFrames = pConfig->rangeEndInPCMFrames;
  62175. resourceManagerDataSourceConfig.loopPointBegInPCMFrames = pConfig->loopPointBegInPCMFrames;
  62176. resourceManagerDataSourceConfig.loopPointEndInPCMFrames = pConfig->loopPointEndInPCMFrames;
  62177. resourceManagerDataSourceConfig.isLooping = pConfig->isLooping;
  62178. result = ma_resource_manager_data_source_init_ex(pEngine->pResourceManager, &resourceManagerDataSourceConfig, pSound->pResourceManagerDataSource);
  62179. if (result != MA_SUCCESS) {
  62180. goto done;
  62181. }
  62182. pSound->ownsDataSource = MA_TRUE; /* <-- Important. Not setting this will result in the resource manager data source never getting uninitialized. */
  62183. /* We need to use a slightly customized version of the config so we'll need to make a copy. */
  62184. config = *pConfig;
  62185. config.pFilePath = NULL;
  62186. config.pFilePathW = NULL;
  62187. config.pDataSource = pSound->pResourceManagerDataSource;
  62188. result = ma_sound_init_from_data_source_internal(pEngine, &config, pSound);
  62189. if (result != MA_SUCCESS) {
  62190. ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource);
  62191. ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks);
  62192. MA_ZERO_OBJECT(pSound);
  62193. goto done;
  62194. }
  62195. }
  62196. done:
  62197. if (notifications.done.pFence) { ma_fence_release(notifications.done.pFence); }
  62198. return result;
  62199. }
  62200. MA_API ma_result ma_sound_init_from_file(ma_engine* pEngine, const char* pFilePath, ma_uint32 flags, ma_sound_group* pGroup, ma_fence* pDoneFence, ma_sound* pSound)
  62201. {
  62202. ma_sound_config config;
  62203. if (pFilePath == NULL) {
  62204. return MA_INVALID_ARGS;
  62205. }
  62206. config = ma_sound_config_init_2(pEngine);
  62207. config.pFilePath = pFilePath;
  62208. config.flags = flags;
  62209. config.pInitialAttachment = pGroup;
  62210. config.pDoneFence = pDoneFence;
  62211. return ma_sound_init_ex(pEngine, &config, pSound);
  62212. }
  62213. MA_API ma_result ma_sound_init_from_file_w(ma_engine* pEngine, const wchar_t* pFilePath, ma_uint32 flags, ma_sound_group* pGroup, ma_fence* pDoneFence, ma_sound* pSound)
  62214. {
  62215. ma_sound_config config;
  62216. if (pFilePath == NULL) {
  62217. return MA_INVALID_ARGS;
  62218. }
  62219. config = ma_sound_config_init_2(pEngine);
  62220. config.pFilePathW = pFilePath;
  62221. config.flags = flags;
  62222. config.pInitialAttachment = pGroup;
  62223. config.pDoneFence = pDoneFence;
  62224. return ma_sound_init_ex(pEngine, &config, pSound);
  62225. }
  62226. MA_API ma_result ma_sound_init_copy(ma_engine* pEngine, const ma_sound* pExistingSound, ma_uint32 flags, ma_sound_group* pGroup, ma_sound* pSound)
  62227. {
  62228. ma_result result;
  62229. ma_sound_config config;
  62230. result = ma_sound_preinit(pEngine, pSound);
  62231. if (result != MA_SUCCESS) {
  62232. return result;
  62233. }
  62234. if (pExistingSound == NULL) {
  62235. return MA_INVALID_ARGS;
  62236. }
  62237. /* Cloning only works for data buffers (not streams) that are loaded from the resource manager. */
  62238. if (pExistingSound->pResourceManagerDataSource == NULL) {
  62239. return MA_INVALID_OPERATION;
  62240. }
  62241. /*
  62242. We need to make a clone of the data source. If the data source is not a data buffer (i.e. a stream)
  62243. the this will fail.
  62244. */
  62245. pSound->pResourceManagerDataSource = (ma_resource_manager_data_source*)ma_malloc(sizeof(*pSound->pResourceManagerDataSource), &pEngine->allocationCallbacks);
  62246. if (pSound->pResourceManagerDataSource == NULL) {
  62247. return MA_OUT_OF_MEMORY;
  62248. }
  62249. result = ma_resource_manager_data_source_init_copy(pEngine->pResourceManager, pExistingSound->pResourceManagerDataSource, pSound->pResourceManagerDataSource);
  62250. if (result != MA_SUCCESS) {
  62251. ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks);
  62252. return result;
  62253. }
  62254. config = ma_sound_config_init_2(pEngine);
  62255. config.pDataSource = pSound->pResourceManagerDataSource;
  62256. config.flags = flags;
  62257. config.pInitialAttachment = pGroup;
  62258. config.monoExpansionMode = pExistingSound->engineNode.monoExpansionMode;
  62259. config.volumeSmoothTimeInPCMFrames = pExistingSound->engineNode.volumeSmoothTimeInPCMFrames;
  62260. result = ma_sound_init_from_data_source_internal(pEngine, &config, pSound);
  62261. if (result != MA_SUCCESS) {
  62262. ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource);
  62263. ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks);
  62264. MA_ZERO_OBJECT(pSound);
  62265. return result;
  62266. }
  62267. return MA_SUCCESS;
  62268. }
  62269. #endif
  62270. MA_API ma_result ma_sound_init_from_data_source(ma_engine* pEngine, ma_data_source* pDataSource, ma_uint32 flags, ma_sound_group* pGroup, ma_sound* pSound)
  62271. {
  62272. ma_sound_config config = ma_sound_config_init_2(pEngine);
  62273. config.pDataSource = pDataSource;
  62274. config.flags = flags;
  62275. config.pInitialAttachment = pGroup;
  62276. return ma_sound_init_ex(pEngine, &config, pSound);
  62277. }
  62278. MA_API ma_result ma_sound_init_ex(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound)
  62279. {
  62280. ma_result result;
  62281. result = ma_sound_preinit(pEngine, pSound);
  62282. if (result != MA_SUCCESS) {
  62283. return result;
  62284. }
  62285. if (pConfig == NULL) {
  62286. return MA_INVALID_ARGS;
  62287. }
  62288. pSound->endCallback = pConfig->endCallback;
  62289. pSound->pEndCallbackUserData = pConfig->pEndCallbackUserData;
  62290. /* We need to load the sound differently depending on whether or not we're loading from a file. */
  62291. #ifndef MA_NO_RESOURCE_MANAGER
  62292. if (pConfig->pFilePath != NULL || pConfig->pFilePathW != NULL) {
  62293. return ma_sound_init_from_file_internal(pEngine, pConfig, pSound);
  62294. } else
  62295. #endif
  62296. {
  62297. /*
  62298. Getting here means we're not loading from a file. We may be loading from an already-initialized
  62299. data source, or none at all. If we aren't specifying any data source, we'll be initializing the
  62300. the equivalent to a group. ma_data_source_init_from_data_source_internal() will deal with this
  62301. for us, so no special treatment required here.
  62302. */
  62303. return ma_sound_init_from_data_source_internal(pEngine, pConfig, pSound);
  62304. }
  62305. }
  62306. MA_API void ma_sound_uninit(ma_sound* pSound)
  62307. {
  62308. if (pSound == NULL) {
  62309. return;
  62310. }
  62311. /*
  62312. Always uninitialize the node first. This ensures it's detached from the graph and does not return until it has done
  62313. so which makes thread safety beyond this point trivial.
  62314. */
  62315. ma_engine_node_uninit(&pSound->engineNode, &pSound->engineNode.pEngine->allocationCallbacks);
  62316. /* Once the sound is detached from the group we can guarantee that it won't be referenced by the mixer thread which means it's safe for us to destroy the data source. */
  62317. #ifndef MA_NO_RESOURCE_MANAGER
  62318. if (pSound->ownsDataSource) {
  62319. ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource);
  62320. ma_free(pSound->pResourceManagerDataSource, &pSound->engineNode.pEngine->allocationCallbacks);
  62321. pSound->pDataSource = NULL;
  62322. }
  62323. #else
  62324. MA_ASSERT(pSound->ownsDataSource == MA_FALSE);
  62325. #endif
  62326. }
  62327. MA_API ma_engine* ma_sound_get_engine(const ma_sound* pSound)
  62328. {
  62329. if (pSound == NULL) {
  62330. return NULL;
  62331. }
  62332. return pSound->engineNode.pEngine;
  62333. }
  62334. MA_API ma_data_source* ma_sound_get_data_source(const ma_sound* pSound)
  62335. {
  62336. if (pSound == NULL) {
  62337. return NULL;
  62338. }
  62339. return pSound->pDataSource;
  62340. }
  62341. MA_API ma_result ma_sound_start(ma_sound* pSound)
  62342. {
  62343. if (pSound == NULL) {
  62344. return MA_INVALID_ARGS;
  62345. }
  62346. /* If the sound is already playing, do nothing. */
  62347. if (ma_sound_is_playing(pSound)) {
  62348. return MA_SUCCESS;
  62349. }
  62350. /* If the sound is at the end it means we want to start from the start again. */
  62351. if (ma_sound_at_end(pSound)) {
  62352. ma_result result = ma_data_source_seek_to_pcm_frame(pSound->pDataSource, 0);
  62353. if (result != MA_SUCCESS && result != MA_NOT_IMPLEMENTED) {
  62354. return result; /* Failed to seek back to the start. */
  62355. }
  62356. /* Make sure we clear the end indicator. */
  62357. c89atomic_exchange_32(&pSound->atEnd, MA_FALSE);
  62358. }
  62359. /* Make sure the sound is started. If there's a start delay, the sound won't actually start until the start time is reached. */
  62360. ma_node_set_state(pSound, ma_node_state_started);
  62361. return MA_SUCCESS;
  62362. }
  62363. MA_API ma_result ma_sound_stop(ma_sound* pSound)
  62364. {
  62365. if (pSound == NULL) {
  62366. return MA_INVALID_ARGS;
  62367. }
  62368. /* This will stop the sound immediately. Use ma_sound_set_stop_time() to stop the sound at a specific time. */
  62369. ma_node_set_state(pSound, ma_node_state_stopped);
  62370. return MA_SUCCESS;
  62371. }
  62372. MA_API void ma_sound_set_volume(ma_sound* pSound, float volume)
  62373. {
  62374. if (pSound == NULL) {
  62375. return;
  62376. }
  62377. ma_engine_node_set_volume(&pSound->engineNode, volume);
  62378. }
  62379. MA_API float ma_sound_get_volume(const ma_sound* pSound)
  62380. {
  62381. float volume = 0;
  62382. if (pSound == NULL) {
  62383. return 0;
  62384. }
  62385. ma_engine_node_get_volume(&pSound->engineNode, &volume);
  62386. return volume;
  62387. }
  62388. MA_API void ma_sound_set_pan(ma_sound* pSound, float pan)
  62389. {
  62390. if (pSound == NULL) {
  62391. return;
  62392. }
  62393. ma_panner_set_pan(&pSound->engineNode.panner, pan);
  62394. }
  62395. MA_API float ma_sound_get_pan(const ma_sound* pSound)
  62396. {
  62397. if (pSound == NULL) {
  62398. return 0;
  62399. }
  62400. return ma_panner_get_pan(&pSound->engineNode.panner);
  62401. }
  62402. MA_API void ma_sound_set_pan_mode(ma_sound* pSound, ma_pan_mode panMode)
  62403. {
  62404. if (pSound == NULL) {
  62405. return;
  62406. }
  62407. ma_panner_set_mode(&pSound->engineNode.panner, panMode);
  62408. }
  62409. MA_API ma_pan_mode ma_sound_get_pan_mode(const ma_sound* pSound)
  62410. {
  62411. if (pSound == NULL) {
  62412. return ma_pan_mode_balance;
  62413. }
  62414. return ma_panner_get_mode(&pSound->engineNode.panner);
  62415. }
  62416. MA_API void ma_sound_set_pitch(ma_sound* pSound, float pitch)
  62417. {
  62418. if (pSound == NULL) {
  62419. return;
  62420. }
  62421. if (pitch <= 0) {
  62422. return;
  62423. }
  62424. c89atomic_exchange_explicit_f32(&pSound->engineNode.pitch, pitch, c89atomic_memory_order_release);
  62425. }
  62426. MA_API float ma_sound_get_pitch(const ma_sound* pSound)
  62427. {
  62428. if (pSound == NULL) {
  62429. return 0;
  62430. }
  62431. return c89atomic_load_f32(&pSound->engineNode.pitch); /* Naughty const-cast for this. */
  62432. }
  62433. MA_API void ma_sound_set_spatialization_enabled(ma_sound* pSound, ma_bool32 enabled)
  62434. {
  62435. if (pSound == NULL) {
  62436. return;
  62437. }
  62438. c89atomic_exchange_explicit_32(&pSound->engineNode.isSpatializationDisabled, !enabled, c89atomic_memory_order_release);
  62439. }
  62440. MA_API ma_bool32 ma_sound_is_spatialization_enabled(const ma_sound* pSound)
  62441. {
  62442. if (pSound == NULL) {
  62443. return MA_FALSE;
  62444. }
  62445. return ma_engine_node_is_spatialization_enabled(&pSound->engineNode);
  62446. }
  62447. MA_API void ma_sound_set_pinned_listener_index(ma_sound* pSound, ma_uint32 listenerIndex)
  62448. {
  62449. if (pSound == NULL || listenerIndex >= ma_engine_get_listener_count(ma_sound_get_engine(pSound))) {
  62450. return;
  62451. }
  62452. c89atomic_exchange_explicit_32(&pSound->engineNode.pinnedListenerIndex, listenerIndex, c89atomic_memory_order_release);
  62453. }
  62454. MA_API ma_uint32 ma_sound_get_pinned_listener_index(const ma_sound* pSound)
  62455. {
  62456. if (pSound == NULL) {
  62457. return MA_LISTENER_INDEX_CLOSEST;
  62458. }
  62459. return c89atomic_load_explicit_32(&pSound->engineNode.pinnedListenerIndex, c89atomic_memory_order_acquire);
  62460. }
  62461. MA_API ma_uint32 ma_sound_get_listener_index(const ma_sound* pSound)
  62462. {
  62463. ma_uint32 listenerIndex;
  62464. if (pSound == NULL) {
  62465. return 0;
  62466. }
  62467. listenerIndex = ma_sound_get_pinned_listener_index(pSound);
  62468. if (listenerIndex == MA_LISTENER_INDEX_CLOSEST) {
  62469. ma_vec3f position = ma_sound_get_position(pSound);
  62470. return ma_engine_find_closest_listener(ma_sound_get_engine(pSound), position.x, position.y, position.z);
  62471. }
  62472. return listenerIndex;
  62473. }
  62474. MA_API ma_vec3f ma_sound_get_direction_to_listener(const ma_sound* pSound)
  62475. {
  62476. ma_vec3f relativePos;
  62477. ma_engine* pEngine;
  62478. if (pSound == NULL) {
  62479. return ma_vec3f_init_3f(0, 0, -1);
  62480. }
  62481. pEngine = ma_sound_get_engine(pSound);
  62482. if (pEngine == NULL) {
  62483. return ma_vec3f_init_3f(0, 0, -1);
  62484. }
  62485. ma_spatializer_get_relative_position_and_direction(&pSound->engineNode.spatializer, &pEngine->listeners[ma_sound_get_listener_index(pSound)], &relativePos, NULL);
  62486. return ma_vec3f_normalize(ma_vec3f_neg(relativePos));
  62487. }
  62488. MA_API void ma_sound_set_position(ma_sound* pSound, float x, float y, float z)
  62489. {
  62490. if (pSound == NULL) {
  62491. return;
  62492. }
  62493. ma_spatializer_set_position(&pSound->engineNode.spatializer, x, y, z);
  62494. }
  62495. MA_API ma_vec3f ma_sound_get_position(const ma_sound* pSound)
  62496. {
  62497. if (pSound == NULL) {
  62498. return ma_vec3f_init_3f(0, 0, 0);
  62499. }
  62500. return ma_spatializer_get_position(&pSound->engineNode.spatializer);
  62501. }
  62502. MA_API void ma_sound_set_direction(ma_sound* pSound, float x, float y, float z)
  62503. {
  62504. if (pSound == NULL) {
  62505. return;
  62506. }
  62507. ma_spatializer_set_direction(&pSound->engineNode.spatializer, x, y, z);
  62508. }
  62509. MA_API ma_vec3f ma_sound_get_direction(const ma_sound* pSound)
  62510. {
  62511. if (pSound == NULL) {
  62512. return ma_vec3f_init_3f(0, 0, 0);
  62513. }
  62514. return ma_spatializer_get_direction(&pSound->engineNode.spatializer);
  62515. }
  62516. MA_API void ma_sound_set_velocity(ma_sound* pSound, float x, float y, float z)
  62517. {
  62518. if (pSound == NULL) {
  62519. return;
  62520. }
  62521. ma_spatializer_set_velocity(&pSound->engineNode.spatializer, x, y, z);
  62522. }
  62523. MA_API ma_vec3f ma_sound_get_velocity(const ma_sound* pSound)
  62524. {
  62525. if (pSound == NULL) {
  62526. return ma_vec3f_init_3f(0, 0, 0);
  62527. }
  62528. return ma_spatializer_get_velocity(&pSound->engineNode.spatializer);
  62529. }
  62530. MA_API void ma_sound_set_attenuation_model(ma_sound* pSound, ma_attenuation_model attenuationModel)
  62531. {
  62532. if (pSound == NULL) {
  62533. return;
  62534. }
  62535. ma_spatializer_set_attenuation_model(&pSound->engineNode.spatializer, attenuationModel);
  62536. }
  62537. MA_API ma_attenuation_model ma_sound_get_attenuation_model(const ma_sound* pSound)
  62538. {
  62539. if (pSound == NULL) {
  62540. return ma_attenuation_model_none;
  62541. }
  62542. return ma_spatializer_get_attenuation_model(&pSound->engineNode.spatializer);
  62543. }
  62544. MA_API void ma_sound_set_positioning(ma_sound* pSound, ma_positioning positioning)
  62545. {
  62546. if (pSound == NULL) {
  62547. return;
  62548. }
  62549. ma_spatializer_set_positioning(&pSound->engineNode.spatializer, positioning);
  62550. }
  62551. MA_API ma_positioning ma_sound_get_positioning(const ma_sound* pSound)
  62552. {
  62553. if (pSound == NULL) {
  62554. return ma_positioning_absolute;
  62555. }
  62556. return ma_spatializer_get_positioning(&pSound->engineNode.spatializer);
  62557. }
  62558. MA_API void ma_sound_set_rolloff(ma_sound* pSound, float rolloff)
  62559. {
  62560. if (pSound == NULL) {
  62561. return;
  62562. }
  62563. ma_spatializer_set_rolloff(&pSound->engineNode.spatializer, rolloff);
  62564. }
  62565. MA_API float ma_sound_get_rolloff(const ma_sound* pSound)
  62566. {
  62567. if (pSound == NULL) {
  62568. return 0;
  62569. }
  62570. return ma_spatializer_get_rolloff(&pSound->engineNode.spatializer);
  62571. }
  62572. MA_API void ma_sound_set_min_gain(ma_sound* pSound, float minGain)
  62573. {
  62574. if (pSound == NULL) {
  62575. return;
  62576. }
  62577. ma_spatializer_set_min_gain(&pSound->engineNode.spatializer, minGain);
  62578. }
  62579. MA_API float ma_sound_get_min_gain(const ma_sound* pSound)
  62580. {
  62581. if (pSound == NULL) {
  62582. return 0;
  62583. }
  62584. return ma_spatializer_get_min_gain(&pSound->engineNode.spatializer);
  62585. }
  62586. MA_API void ma_sound_set_max_gain(ma_sound* pSound, float maxGain)
  62587. {
  62588. if (pSound == NULL) {
  62589. return;
  62590. }
  62591. ma_spatializer_set_max_gain(&pSound->engineNode.spatializer, maxGain);
  62592. }
  62593. MA_API float ma_sound_get_max_gain(const ma_sound* pSound)
  62594. {
  62595. if (pSound == NULL) {
  62596. return 0;
  62597. }
  62598. return ma_spatializer_get_max_gain(&pSound->engineNode.spatializer);
  62599. }
  62600. MA_API void ma_sound_set_min_distance(ma_sound* pSound, float minDistance)
  62601. {
  62602. if (pSound == NULL) {
  62603. return;
  62604. }
  62605. ma_spatializer_set_min_distance(&pSound->engineNode.spatializer, minDistance);
  62606. }
  62607. MA_API float ma_sound_get_min_distance(const ma_sound* pSound)
  62608. {
  62609. if (pSound == NULL) {
  62610. return 0;
  62611. }
  62612. return ma_spatializer_get_min_distance(&pSound->engineNode.spatializer);
  62613. }
  62614. MA_API void ma_sound_set_max_distance(ma_sound* pSound, float maxDistance)
  62615. {
  62616. if (pSound == NULL) {
  62617. return;
  62618. }
  62619. ma_spatializer_set_max_distance(&pSound->engineNode.spatializer, maxDistance);
  62620. }
  62621. MA_API float ma_sound_get_max_distance(const ma_sound* pSound)
  62622. {
  62623. if (pSound == NULL) {
  62624. return 0;
  62625. }
  62626. return ma_spatializer_get_max_distance(&pSound->engineNode.spatializer);
  62627. }
  62628. MA_API void ma_sound_set_cone(ma_sound* pSound, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  62629. {
  62630. if (pSound == NULL) {
  62631. return;
  62632. }
  62633. ma_spatializer_set_cone(&pSound->engineNode.spatializer, innerAngleInRadians, outerAngleInRadians, outerGain);
  62634. }
  62635. MA_API void ma_sound_get_cone(const ma_sound* pSound, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  62636. {
  62637. if (pInnerAngleInRadians != NULL) {
  62638. *pInnerAngleInRadians = 0;
  62639. }
  62640. if (pOuterAngleInRadians != NULL) {
  62641. *pOuterAngleInRadians = 0;
  62642. }
  62643. if (pOuterGain != NULL) {
  62644. *pOuterGain = 0;
  62645. }
  62646. ma_spatializer_get_cone(&pSound->engineNode.spatializer, pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain);
  62647. }
  62648. MA_API void ma_sound_set_doppler_factor(ma_sound* pSound, float dopplerFactor)
  62649. {
  62650. if (pSound == NULL) {
  62651. return;
  62652. }
  62653. ma_spatializer_set_doppler_factor(&pSound->engineNode.spatializer, dopplerFactor);
  62654. }
  62655. MA_API float ma_sound_get_doppler_factor(const ma_sound* pSound)
  62656. {
  62657. if (pSound == NULL) {
  62658. return 0;
  62659. }
  62660. return ma_spatializer_get_doppler_factor(&pSound->engineNode.spatializer);
  62661. }
  62662. MA_API void ma_sound_set_directional_attenuation_factor(ma_sound* pSound, float directionalAttenuationFactor)
  62663. {
  62664. if (pSound == NULL) {
  62665. return;
  62666. }
  62667. ma_spatializer_set_directional_attenuation_factor(&pSound->engineNode.spatializer, directionalAttenuationFactor);
  62668. }
  62669. MA_API float ma_sound_get_directional_attenuation_factor(const ma_sound* pSound)
  62670. {
  62671. if (pSound == NULL) {
  62672. return 1;
  62673. }
  62674. return ma_spatializer_get_directional_attenuation_factor(&pSound->engineNode.spatializer);
  62675. }
  62676. MA_API void ma_sound_set_fade_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames)
  62677. {
  62678. if (pSound == NULL) {
  62679. return;
  62680. }
  62681. ma_fader_set_fade(&pSound->engineNode.fader, volumeBeg, volumeEnd, fadeLengthInFrames);
  62682. }
  62683. MA_API void ma_sound_set_fade_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds)
  62684. {
  62685. if (pSound == NULL) {
  62686. return;
  62687. }
  62688. ma_sound_set_fade_in_pcm_frames(pSound, volumeBeg, volumeEnd, (fadeLengthInMilliseconds * pSound->engineNode.fader.config.sampleRate) / 1000);
  62689. }
  62690. MA_API float ma_sound_get_current_fade_volume(const ma_sound* pSound)
  62691. {
  62692. if (pSound == NULL) {
  62693. return MA_INVALID_ARGS;
  62694. }
  62695. return ma_fader_get_current_volume(&pSound->engineNode.fader);
  62696. }
  62697. MA_API void ma_sound_set_start_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames)
  62698. {
  62699. if (pSound == NULL) {
  62700. return;
  62701. }
  62702. ma_node_set_state_time(pSound, ma_node_state_started, absoluteGlobalTimeInFrames);
  62703. }
  62704. MA_API void ma_sound_set_start_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds)
  62705. {
  62706. if (pSound == NULL) {
  62707. return;
  62708. }
  62709. ma_sound_set_start_time_in_pcm_frames(pSound, absoluteGlobalTimeInMilliseconds * ma_engine_get_sample_rate(ma_sound_get_engine(pSound)) / 1000);
  62710. }
  62711. MA_API void ma_sound_set_stop_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames)
  62712. {
  62713. if (pSound == NULL) {
  62714. return;
  62715. }
  62716. ma_node_set_state_time(pSound, ma_node_state_stopped, absoluteGlobalTimeInFrames);
  62717. }
  62718. MA_API void ma_sound_set_stop_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds)
  62719. {
  62720. if (pSound == NULL) {
  62721. return;
  62722. }
  62723. ma_sound_set_stop_time_in_pcm_frames(pSound, absoluteGlobalTimeInMilliseconds * ma_engine_get_sample_rate(ma_sound_get_engine(pSound)) / 1000);
  62724. }
  62725. MA_API ma_bool32 ma_sound_is_playing(const ma_sound* pSound)
  62726. {
  62727. if (pSound == NULL) {
  62728. return MA_FALSE;
  62729. }
  62730. return ma_node_get_state_by_time(pSound, ma_engine_get_time_in_pcm_frames(ma_sound_get_engine(pSound))) == ma_node_state_started;
  62731. }
  62732. MA_API ma_uint64 ma_sound_get_time_in_pcm_frames(const ma_sound* pSound)
  62733. {
  62734. if (pSound == NULL) {
  62735. return 0;
  62736. }
  62737. return ma_node_get_time(pSound);
  62738. }
  62739. MA_API void ma_sound_set_looping(ma_sound* pSound, ma_bool32 isLooping)
  62740. {
  62741. if (pSound == NULL) {
  62742. return;
  62743. }
  62744. /* Looping is only a valid concept if the sound is backed by a data source. */
  62745. if (pSound->pDataSource == NULL) {
  62746. return;
  62747. }
  62748. /* The looping state needs to be applied to the data source in order for any looping to actually happen. */
  62749. ma_data_source_set_looping(pSound->pDataSource, isLooping);
  62750. }
  62751. MA_API ma_bool32 ma_sound_is_looping(const ma_sound* pSound)
  62752. {
  62753. if (pSound == NULL) {
  62754. return MA_FALSE;
  62755. }
  62756. /* There is no notion of looping for sounds that are not backed by a data source. */
  62757. if (pSound->pDataSource == NULL) {
  62758. return MA_FALSE;
  62759. }
  62760. return ma_data_source_is_looping(pSound->pDataSource);
  62761. }
  62762. MA_API ma_bool32 ma_sound_at_end(const ma_sound* pSound)
  62763. {
  62764. if (pSound == NULL) {
  62765. return MA_FALSE;
  62766. }
  62767. /* There is no notion of an end of a sound if it's not backed by a data source. */
  62768. if (pSound->pDataSource == NULL) {
  62769. return MA_FALSE;
  62770. }
  62771. return ma_sound_get_at_end(pSound);
  62772. }
  62773. MA_API ma_result ma_sound_seek_to_pcm_frame(ma_sound* pSound, ma_uint64 frameIndex)
  62774. {
  62775. if (pSound == NULL) {
  62776. return MA_INVALID_ARGS;
  62777. }
  62778. /* Seeking is only valid for sounds that are backed by a data source. */
  62779. if (pSound->pDataSource == NULL) {
  62780. return MA_INVALID_OPERATION;
  62781. }
  62782. /* We can't be seeking while reading at the same time. We just set the seek target and get the mixing thread to do the actual seek. */
  62783. c89atomic_exchange_64(&pSound->seekTarget, frameIndex);
  62784. return MA_SUCCESS;
  62785. }
  62786. MA_API ma_result ma_sound_get_data_format(ma_sound* pSound, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  62787. {
  62788. if (pSound == NULL) {
  62789. return MA_INVALID_ARGS;
  62790. }
  62791. /* The data format is retrieved directly from the data source if the sound is backed by one. Otherwise we pull it from the node. */
  62792. if (pSound->pDataSource == NULL) {
  62793. ma_uint32 channels;
  62794. if (pFormat != NULL) {
  62795. *pFormat = ma_format_f32;
  62796. }
  62797. channels = ma_node_get_input_channels(&pSound->engineNode, 0);
  62798. if (pChannels != NULL) {
  62799. *pChannels = channels;
  62800. }
  62801. if (pSampleRate != NULL) {
  62802. *pSampleRate = pSound->engineNode.resampler.config.sampleRateIn;
  62803. }
  62804. if (pChannelMap != NULL) {
  62805. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channels);
  62806. }
  62807. return MA_SUCCESS;
  62808. } else {
  62809. return ma_data_source_get_data_format(pSound->pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  62810. }
  62811. }
  62812. MA_API ma_result ma_sound_get_cursor_in_pcm_frames(ma_sound* pSound, ma_uint64* pCursor)
  62813. {
  62814. if (pSound == NULL) {
  62815. return MA_INVALID_ARGS;
  62816. }
  62817. /* The notion of a cursor is only valid for sounds that are backed by a data source. */
  62818. if (pSound->pDataSource == NULL) {
  62819. return MA_INVALID_OPERATION;
  62820. }
  62821. return ma_data_source_get_cursor_in_pcm_frames(pSound->pDataSource, pCursor);
  62822. }
  62823. MA_API ma_result ma_sound_get_length_in_pcm_frames(ma_sound* pSound, ma_uint64* pLength)
  62824. {
  62825. if (pSound == NULL) {
  62826. return MA_INVALID_ARGS;
  62827. }
  62828. /* The notion of a sound length is only valid for sounds that are backed by a data source. */
  62829. if (pSound->pDataSource == NULL) {
  62830. return MA_INVALID_OPERATION;
  62831. }
  62832. return ma_data_source_get_length_in_pcm_frames(pSound->pDataSource, pLength);
  62833. }
  62834. MA_API ma_result ma_sound_get_cursor_in_seconds(ma_sound* pSound, float* pCursor)
  62835. {
  62836. if (pSound == NULL) {
  62837. return MA_INVALID_ARGS;
  62838. }
  62839. /* The notion of a cursor is only valid for sounds that are backed by a data source. */
  62840. if (pSound->pDataSource == NULL) {
  62841. return MA_INVALID_OPERATION;
  62842. }
  62843. return ma_data_source_get_cursor_in_seconds(pSound->pDataSource, pCursor);
  62844. }
  62845. MA_API ma_result ma_sound_get_length_in_seconds(ma_sound* pSound, float* pLength)
  62846. {
  62847. if (pSound == NULL) {
  62848. return MA_INVALID_ARGS;
  62849. }
  62850. /* The notion of a sound length is only valid for sounds that are backed by a data source. */
  62851. if (pSound->pDataSource == NULL) {
  62852. return MA_INVALID_OPERATION;
  62853. }
  62854. return ma_data_source_get_length_in_seconds(pSound->pDataSource, pLength);
  62855. }
  62856. MA_API ma_result ma_sound_set_end_callback(ma_sound* pSound, ma_sound_end_proc callback, void* pUserData)
  62857. {
  62858. if (pSound == NULL) {
  62859. return MA_INVALID_ARGS;
  62860. }
  62861. /* The notion of an end is only valid for sounds that are backed by a data source. */
  62862. if (pSound->pDataSource == NULL) {
  62863. return MA_INVALID_OPERATION;
  62864. }
  62865. pSound->endCallback = callback;
  62866. pSound->pEndCallbackUserData = pUserData;
  62867. return MA_SUCCESS;
  62868. }
  62869. MA_API ma_result ma_sound_group_init(ma_engine* pEngine, ma_uint32 flags, ma_sound_group* pParentGroup, ma_sound_group* pGroup)
  62870. {
  62871. ma_sound_group_config config = ma_sound_group_config_init_2(pEngine);
  62872. config.flags = flags;
  62873. config.pInitialAttachment = pParentGroup;
  62874. return ma_sound_group_init_ex(pEngine, &config, pGroup);
  62875. }
  62876. MA_API ma_result ma_sound_group_init_ex(ma_engine* pEngine, const ma_sound_group_config* pConfig, ma_sound_group* pGroup)
  62877. {
  62878. ma_sound_config soundConfig;
  62879. if (pGroup == NULL) {
  62880. return MA_INVALID_ARGS;
  62881. }
  62882. MA_ZERO_OBJECT(pGroup);
  62883. if (pConfig == NULL) {
  62884. return MA_INVALID_ARGS;
  62885. }
  62886. /* A sound group is just a sound without a data source. */
  62887. soundConfig = *pConfig;
  62888. soundConfig.pFilePath = NULL;
  62889. soundConfig.pFilePathW = NULL;
  62890. soundConfig.pDataSource = NULL;
  62891. /*
  62892. Groups need to have spatialization disabled by default because I think it'll be pretty rare
  62893. that programs will want to spatialize groups (but not unheard of). Certainly it feels like
  62894. disabling this by default feels like the right option. Spatialization can be enabled with a
  62895. call to ma_sound_group_set_spatialization_enabled().
  62896. */
  62897. soundConfig.flags |= MA_SOUND_FLAG_NO_SPATIALIZATION;
  62898. return ma_sound_init_ex(pEngine, &soundConfig, pGroup);
  62899. }
  62900. MA_API void ma_sound_group_uninit(ma_sound_group* pGroup)
  62901. {
  62902. ma_sound_uninit(pGroup);
  62903. }
  62904. MA_API ma_engine* ma_sound_group_get_engine(const ma_sound_group* pGroup)
  62905. {
  62906. return ma_sound_get_engine(pGroup);
  62907. }
  62908. MA_API ma_result ma_sound_group_start(ma_sound_group* pGroup)
  62909. {
  62910. return ma_sound_start(pGroup);
  62911. }
  62912. MA_API ma_result ma_sound_group_stop(ma_sound_group* pGroup)
  62913. {
  62914. return ma_sound_stop(pGroup);
  62915. }
  62916. MA_API void ma_sound_group_set_volume(ma_sound_group* pGroup, float volume)
  62917. {
  62918. ma_sound_set_volume(pGroup, volume);
  62919. }
  62920. MA_API float ma_sound_group_get_volume(const ma_sound_group* pGroup)
  62921. {
  62922. return ma_sound_get_volume(pGroup);
  62923. }
  62924. MA_API void ma_sound_group_set_pan(ma_sound_group* pGroup, float pan)
  62925. {
  62926. ma_sound_set_pan(pGroup, pan);
  62927. }
  62928. MA_API float ma_sound_group_get_pan(const ma_sound_group* pGroup)
  62929. {
  62930. return ma_sound_get_pan(pGroup);
  62931. }
  62932. MA_API void ma_sound_group_set_pan_mode(ma_sound_group* pGroup, ma_pan_mode panMode)
  62933. {
  62934. ma_sound_set_pan_mode(pGroup, panMode);
  62935. }
  62936. MA_API ma_pan_mode ma_sound_group_get_pan_mode(const ma_sound_group* pGroup)
  62937. {
  62938. return ma_sound_get_pan_mode(pGroup);
  62939. }
  62940. MA_API void ma_sound_group_set_pitch(ma_sound_group* pGroup, float pitch)
  62941. {
  62942. ma_sound_set_pitch(pGroup, pitch);
  62943. }
  62944. MA_API float ma_sound_group_get_pitch(const ma_sound_group* pGroup)
  62945. {
  62946. return ma_sound_get_pitch(pGroup);
  62947. }
  62948. MA_API void ma_sound_group_set_spatialization_enabled(ma_sound_group* pGroup, ma_bool32 enabled)
  62949. {
  62950. ma_sound_set_spatialization_enabled(pGroup, enabled);
  62951. }
  62952. MA_API ma_bool32 ma_sound_group_is_spatialization_enabled(const ma_sound_group* pGroup)
  62953. {
  62954. return ma_sound_is_spatialization_enabled(pGroup);
  62955. }
  62956. MA_API void ma_sound_group_set_pinned_listener_index(ma_sound_group* pGroup, ma_uint32 listenerIndex)
  62957. {
  62958. ma_sound_set_pinned_listener_index(pGroup, listenerIndex);
  62959. }
  62960. MA_API ma_uint32 ma_sound_group_get_pinned_listener_index(const ma_sound_group* pGroup)
  62961. {
  62962. return ma_sound_get_pinned_listener_index(pGroup);
  62963. }
  62964. MA_API ma_uint32 ma_sound_group_get_listener_index(const ma_sound_group* pGroup)
  62965. {
  62966. return ma_sound_get_listener_index(pGroup);
  62967. }
  62968. MA_API ma_vec3f ma_sound_group_get_direction_to_listener(const ma_sound_group* pGroup)
  62969. {
  62970. return ma_sound_get_direction_to_listener(pGroup);
  62971. }
  62972. MA_API void ma_sound_group_set_position(ma_sound_group* pGroup, float x, float y, float z)
  62973. {
  62974. ma_sound_set_position(pGroup, x, y, z);
  62975. }
  62976. MA_API ma_vec3f ma_sound_group_get_position(const ma_sound_group* pGroup)
  62977. {
  62978. return ma_sound_get_position(pGroup);
  62979. }
  62980. MA_API void ma_sound_group_set_direction(ma_sound_group* pGroup, float x, float y, float z)
  62981. {
  62982. ma_sound_set_direction(pGroup, x, y, z);
  62983. }
  62984. MA_API ma_vec3f ma_sound_group_get_direction(const ma_sound_group* pGroup)
  62985. {
  62986. return ma_sound_get_direction(pGroup);
  62987. }
  62988. MA_API void ma_sound_group_set_velocity(ma_sound_group* pGroup, float x, float y, float z)
  62989. {
  62990. ma_sound_set_velocity(pGroup, x, y, z);
  62991. }
  62992. MA_API ma_vec3f ma_sound_group_get_velocity(const ma_sound_group* pGroup)
  62993. {
  62994. return ma_sound_get_velocity(pGroup);
  62995. }
  62996. MA_API void ma_sound_group_set_attenuation_model(ma_sound_group* pGroup, ma_attenuation_model attenuationModel)
  62997. {
  62998. ma_sound_set_attenuation_model(pGroup, attenuationModel);
  62999. }
  63000. MA_API ma_attenuation_model ma_sound_group_get_attenuation_model(const ma_sound_group* pGroup)
  63001. {
  63002. return ma_sound_get_attenuation_model(pGroup);
  63003. }
  63004. MA_API void ma_sound_group_set_positioning(ma_sound_group* pGroup, ma_positioning positioning)
  63005. {
  63006. ma_sound_set_positioning(pGroup, positioning);
  63007. }
  63008. MA_API ma_positioning ma_sound_group_get_positioning(const ma_sound_group* pGroup)
  63009. {
  63010. return ma_sound_get_positioning(pGroup);
  63011. }
  63012. MA_API void ma_sound_group_set_rolloff(ma_sound_group* pGroup, float rolloff)
  63013. {
  63014. ma_sound_set_rolloff(pGroup, rolloff);
  63015. }
  63016. MA_API float ma_sound_group_get_rolloff(const ma_sound_group* pGroup)
  63017. {
  63018. return ma_sound_get_rolloff(pGroup);
  63019. }
  63020. MA_API void ma_sound_group_set_min_gain(ma_sound_group* pGroup, float minGain)
  63021. {
  63022. ma_sound_set_min_gain(pGroup, minGain);
  63023. }
  63024. MA_API float ma_sound_group_get_min_gain(const ma_sound_group* pGroup)
  63025. {
  63026. return ma_sound_get_min_gain(pGroup);
  63027. }
  63028. MA_API void ma_sound_group_set_max_gain(ma_sound_group* pGroup, float maxGain)
  63029. {
  63030. ma_sound_set_max_gain(pGroup, maxGain);
  63031. }
  63032. MA_API float ma_sound_group_get_max_gain(const ma_sound_group* pGroup)
  63033. {
  63034. return ma_sound_get_max_gain(pGroup);
  63035. }
  63036. MA_API void ma_sound_group_set_min_distance(ma_sound_group* pGroup, float minDistance)
  63037. {
  63038. ma_sound_set_min_distance(pGroup, minDistance);
  63039. }
  63040. MA_API float ma_sound_group_get_min_distance(const ma_sound_group* pGroup)
  63041. {
  63042. return ma_sound_get_min_distance(pGroup);
  63043. }
  63044. MA_API void ma_sound_group_set_max_distance(ma_sound_group* pGroup, float maxDistance)
  63045. {
  63046. ma_sound_set_max_distance(pGroup, maxDistance);
  63047. }
  63048. MA_API float ma_sound_group_get_max_distance(const ma_sound_group* pGroup)
  63049. {
  63050. return ma_sound_get_max_distance(pGroup);
  63051. }
  63052. MA_API void ma_sound_group_set_cone(ma_sound_group* pGroup, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  63053. {
  63054. ma_sound_set_cone(pGroup, innerAngleInRadians, outerAngleInRadians, outerGain);
  63055. }
  63056. MA_API void ma_sound_group_get_cone(const ma_sound_group* pGroup, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  63057. {
  63058. ma_sound_get_cone(pGroup, pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain);
  63059. }
  63060. MA_API void ma_sound_group_set_doppler_factor(ma_sound_group* pGroup, float dopplerFactor)
  63061. {
  63062. ma_sound_set_doppler_factor(pGroup, dopplerFactor);
  63063. }
  63064. MA_API float ma_sound_group_get_doppler_factor(const ma_sound_group* pGroup)
  63065. {
  63066. return ma_sound_get_doppler_factor(pGroup);
  63067. }
  63068. MA_API void ma_sound_group_set_directional_attenuation_factor(ma_sound_group* pGroup, float directionalAttenuationFactor)
  63069. {
  63070. ma_sound_set_directional_attenuation_factor(pGroup, directionalAttenuationFactor);
  63071. }
  63072. MA_API float ma_sound_group_get_directional_attenuation_factor(const ma_sound_group* pGroup)
  63073. {
  63074. return ma_sound_get_directional_attenuation_factor(pGroup);
  63075. }
  63076. MA_API void ma_sound_group_set_fade_in_pcm_frames(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames)
  63077. {
  63078. ma_sound_set_fade_in_pcm_frames(pGroup, volumeBeg, volumeEnd, fadeLengthInFrames);
  63079. }
  63080. MA_API void ma_sound_group_set_fade_in_milliseconds(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds)
  63081. {
  63082. ma_sound_set_fade_in_milliseconds(pGroup, volumeBeg, volumeEnd, fadeLengthInMilliseconds);
  63083. }
  63084. MA_API float ma_sound_group_get_current_fade_volume(ma_sound_group* pGroup)
  63085. {
  63086. return ma_sound_get_current_fade_volume(pGroup);
  63087. }
  63088. MA_API void ma_sound_group_set_start_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames)
  63089. {
  63090. ma_sound_set_start_time_in_pcm_frames(pGroup, absoluteGlobalTimeInFrames);
  63091. }
  63092. MA_API void ma_sound_group_set_start_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds)
  63093. {
  63094. ma_sound_set_start_time_in_milliseconds(pGroup, absoluteGlobalTimeInMilliseconds);
  63095. }
  63096. MA_API void ma_sound_group_set_stop_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames)
  63097. {
  63098. ma_sound_set_stop_time_in_pcm_frames(pGroup, absoluteGlobalTimeInFrames);
  63099. }
  63100. MA_API void ma_sound_group_set_stop_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds)
  63101. {
  63102. ma_sound_set_stop_time_in_milliseconds(pGroup, absoluteGlobalTimeInMilliseconds);
  63103. }
  63104. MA_API ma_bool32 ma_sound_group_is_playing(const ma_sound_group* pGroup)
  63105. {
  63106. return ma_sound_is_playing(pGroup);
  63107. }
  63108. MA_API ma_uint64 ma_sound_group_get_time_in_pcm_frames(const ma_sound_group* pGroup)
  63109. {
  63110. return ma_sound_get_time_in_pcm_frames(pGroup);
  63111. }
  63112. #endif /* MA_NO_ENGINE */
  63113. /* END SECTION: miniaudio_engine.c */
  63114. /**************************************************************************************************************************************************************
  63115. ***************************************************************************************************************************************************************
  63116. Auto Generated
  63117. ==============
  63118. All code below is auto-generated from a tool. This mostly consists of decoding backend implementations such as dr_wav, dr_flac, etc. If you find a bug in the
  63119. code below please report the bug to the respective repository for the relevant project (probably dr_libs).
  63120. ***************************************************************************************************************************************************************
  63121. **************************************************************************************************************************************************************/
  63122. #if !defined(MA_NO_WAV) && (!defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING))
  63123. #if !defined(DR_WAV_IMPLEMENTATION) && !defined(DRWAV_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
  63124. /* dr_wav_c begin */
  63125. #ifndef dr_wav_c
  63126. #define dr_wav_c
  63127. #ifdef __MRC__
  63128. #pragma options opt off
  63129. #endif
  63130. #include <stdlib.h>
  63131. #include <string.h>
  63132. #include <limits.h>
  63133. #ifndef DR_WAV_NO_STDIO
  63134. #include <stdio.h>
  63135. #ifndef DR_WAV_NO_WCHAR
  63136. #include <wchar.h>
  63137. #endif
  63138. #endif
  63139. #ifndef DRWAV_ASSERT
  63140. #include <assert.h>
  63141. #define DRWAV_ASSERT(expression) assert(expression)
  63142. #endif
  63143. #ifndef DRWAV_MALLOC
  63144. #define DRWAV_MALLOC(sz) malloc((sz))
  63145. #endif
  63146. #ifndef DRWAV_REALLOC
  63147. #define DRWAV_REALLOC(p, sz) realloc((p), (sz))
  63148. #endif
  63149. #ifndef DRWAV_FREE
  63150. #define DRWAV_FREE(p) free((p))
  63151. #endif
  63152. #ifndef DRWAV_COPY_MEMORY
  63153. #define DRWAV_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  63154. #endif
  63155. #ifndef DRWAV_ZERO_MEMORY
  63156. #define DRWAV_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  63157. #endif
  63158. #ifndef DRWAV_ZERO_OBJECT
  63159. #define DRWAV_ZERO_OBJECT(p) DRWAV_ZERO_MEMORY((p), sizeof(*p))
  63160. #endif
  63161. #define drwav_countof(x) (sizeof(x) / sizeof(x[0]))
  63162. #define drwav_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
  63163. #define drwav_min(a, b) (((a) < (b)) ? (a) : (b))
  63164. #define drwav_max(a, b) (((a) > (b)) ? (a) : (b))
  63165. #define drwav_clamp(x, lo, hi) (drwav_max((lo), drwav_min((hi), (x))))
  63166. #define drwav_offset_ptr(p, offset) (((drwav_uint8*)(p)) + (offset))
  63167. #define DRWAV_MAX_SIMD_VECTOR_SIZE 64
  63168. #if defined(__x86_64__) || defined(_M_X64)
  63169. #define DRWAV_X64
  63170. #elif defined(__i386) || defined(_M_IX86)
  63171. #define DRWAV_X86
  63172. #elif defined(__arm__) || defined(_M_ARM)
  63173. #define DRWAV_ARM
  63174. #endif
  63175. #ifdef _MSC_VER
  63176. #define DRWAV_INLINE __forceinline
  63177. #elif defined(__GNUC__)
  63178. #if defined(__STRICT_ANSI__)
  63179. #define DRWAV_GNUC_INLINE_HINT __inline__
  63180. #else
  63181. #define DRWAV_GNUC_INLINE_HINT inline
  63182. #endif
  63183. #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
  63184. #define DRWAV_INLINE DRWAV_GNUC_INLINE_HINT __attribute__((always_inline))
  63185. #else
  63186. #define DRWAV_INLINE DRWAV_GNUC_INLINE_HINT
  63187. #endif
  63188. #elif defined(__WATCOMC__)
  63189. #define DRWAV_INLINE __inline
  63190. #else
  63191. #define DRWAV_INLINE
  63192. #endif
  63193. #if defined(SIZE_MAX)
  63194. #define DRWAV_SIZE_MAX SIZE_MAX
  63195. #else
  63196. #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
  63197. #define DRWAV_SIZE_MAX ((drwav_uint64)0xFFFFFFFFFFFFFFFF)
  63198. #else
  63199. #define DRWAV_SIZE_MAX 0xFFFFFFFF
  63200. #endif
  63201. #endif
  63202. #if defined(_MSC_VER) && _MSC_VER >= 1400
  63203. #define DRWAV_HAS_BYTESWAP16_INTRINSIC
  63204. #define DRWAV_HAS_BYTESWAP32_INTRINSIC
  63205. #define DRWAV_HAS_BYTESWAP64_INTRINSIC
  63206. #elif defined(__clang__)
  63207. #if defined(__has_builtin)
  63208. #if __has_builtin(__builtin_bswap16)
  63209. #define DRWAV_HAS_BYTESWAP16_INTRINSIC
  63210. #endif
  63211. #if __has_builtin(__builtin_bswap32)
  63212. #define DRWAV_HAS_BYTESWAP32_INTRINSIC
  63213. #endif
  63214. #if __has_builtin(__builtin_bswap64)
  63215. #define DRWAV_HAS_BYTESWAP64_INTRINSIC
  63216. #endif
  63217. #endif
  63218. #elif defined(__GNUC__)
  63219. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  63220. #define DRWAV_HAS_BYTESWAP32_INTRINSIC
  63221. #define DRWAV_HAS_BYTESWAP64_INTRINSIC
  63222. #endif
  63223. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  63224. #define DRWAV_HAS_BYTESWAP16_INTRINSIC
  63225. #endif
  63226. #endif
  63227. DRWAV_API void drwav_version(drwav_uint32* pMajor, drwav_uint32* pMinor, drwav_uint32* pRevision)
  63228. {
  63229. if (pMajor) {
  63230. *pMajor = DRWAV_VERSION_MAJOR;
  63231. }
  63232. if (pMinor) {
  63233. *pMinor = DRWAV_VERSION_MINOR;
  63234. }
  63235. if (pRevision) {
  63236. *pRevision = DRWAV_VERSION_REVISION;
  63237. }
  63238. }
  63239. DRWAV_API const char* drwav_version_string(void)
  63240. {
  63241. return DRWAV_VERSION_STRING;
  63242. }
  63243. #ifndef DRWAV_MAX_SAMPLE_RATE
  63244. #define DRWAV_MAX_SAMPLE_RATE 384000
  63245. #endif
  63246. #ifndef DRWAV_MAX_CHANNELS
  63247. #define DRWAV_MAX_CHANNELS 256
  63248. #endif
  63249. #ifndef DRWAV_MAX_BITS_PER_SAMPLE
  63250. #define DRWAV_MAX_BITS_PER_SAMPLE 64
  63251. #endif
  63252. static const drwav_uint8 drwavGUID_W64_RIFF[16] = {0x72,0x69,0x66,0x66, 0x2E,0x91, 0xCF,0x11, 0xA5,0xD6, 0x28,0xDB,0x04,0xC1,0x00,0x00};
  63253. static const drwav_uint8 drwavGUID_W64_WAVE[16] = {0x77,0x61,0x76,0x65, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  63254. static const drwav_uint8 drwavGUID_W64_FMT [16] = {0x66,0x6D,0x74,0x20, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  63255. static const drwav_uint8 drwavGUID_W64_FACT[16] = {0x66,0x61,0x63,0x74, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  63256. static const drwav_uint8 drwavGUID_W64_DATA[16] = {0x64,0x61,0x74,0x61, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  63257. static DRWAV_INLINE int drwav__is_little_endian(void)
  63258. {
  63259. #if defined(DRWAV_X86) || defined(DRWAV_X64)
  63260. return DRWAV_TRUE;
  63261. #elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
  63262. return DRWAV_TRUE;
  63263. #else
  63264. int n = 1;
  63265. return (*(char*)&n) == 1;
  63266. #endif
  63267. }
  63268. static DRWAV_INLINE void drwav_bytes_to_guid(const drwav_uint8* data, drwav_uint8* guid)
  63269. {
  63270. int i;
  63271. for (i = 0; i < 16; ++i) {
  63272. guid[i] = data[i];
  63273. }
  63274. }
  63275. static DRWAV_INLINE drwav_uint16 drwav__bswap16(drwav_uint16 n)
  63276. {
  63277. #ifdef DRWAV_HAS_BYTESWAP16_INTRINSIC
  63278. #if defined(_MSC_VER)
  63279. return _byteswap_ushort(n);
  63280. #elif defined(__GNUC__) || defined(__clang__)
  63281. return __builtin_bswap16(n);
  63282. #else
  63283. #error "This compiler does not support the byte swap intrinsic."
  63284. #endif
  63285. #else
  63286. return ((n & 0xFF00) >> 8) |
  63287. ((n & 0x00FF) << 8);
  63288. #endif
  63289. }
  63290. static DRWAV_INLINE drwav_uint32 drwav__bswap32(drwav_uint32 n)
  63291. {
  63292. #ifdef DRWAV_HAS_BYTESWAP32_INTRINSIC
  63293. #if defined(_MSC_VER)
  63294. return _byteswap_ulong(n);
  63295. #elif defined(__GNUC__) || defined(__clang__)
  63296. #if defined(DRWAV_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(DRWAV_64BIT)
  63297. drwav_uint32 r;
  63298. __asm__ __volatile__ (
  63299. #if defined(DRWAV_64BIT)
  63300. "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n)
  63301. #else
  63302. "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  63303. #endif
  63304. );
  63305. return r;
  63306. #else
  63307. return __builtin_bswap32(n);
  63308. #endif
  63309. #else
  63310. #error "This compiler does not support the byte swap intrinsic."
  63311. #endif
  63312. #else
  63313. return ((n & 0xFF000000) >> 24) |
  63314. ((n & 0x00FF0000) >> 8) |
  63315. ((n & 0x0000FF00) << 8) |
  63316. ((n & 0x000000FF) << 24);
  63317. #endif
  63318. }
  63319. static DRWAV_INLINE drwav_uint64 drwav__bswap64(drwav_uint64 n)
  63320. {
  63321. #ifdef DRWAV_HAS_BYTESWAP64_INTRINSIC
  63322. #if defined(_MSC_VER)
  63323. return _byteswap_uint64(n);
  63324. #elif defined(__GNUC__) || defined(__clang__)
  63325. return __builtin_bswap64(n);
  63326. #else
  63327. #error "This compiler does not support the byte swap intrinsic."
  63328. #endif
  63329. #else
  63330. return ((n & ((drwav_uint64)0xFF000000 << 32)) >> 56) |
  63331. ((n & ((drwav_uint64)0x00FF0000 << 32)) >> 40) |
  63332. ((n & ((drwav_uint64)0x0000FF00 << 32)) >> 24) |
  63333. ((n & ((drwav_uint64)0x000000FF << 32)) >> 8) |
  63334. ((n & ((drwav_uint64)0xFF000000 )) << 8) |
  63335. ((n & ((drwav_uint64)0x00FF0000 )) << 24) |
  63336. ((n & ((drwav_uint64)0x0000FF00 )) << 40) |
  63337. ((n & ((drwav_uint64)0x000000FF )) << 56);
  63338. #endif
  63339. }
  63340. static DRWAV_INLINE drwav_int16 drwav__bswap_s16(drwav_int16 n)
  63341. {
  63342. return (drwav_int16)drwav__bswap16((drwav_uint16)n);
  63343. }
  63344. static DRWAV_INLINE void drwav__bswap_samples_s16(drwav_int16* pSamples, drwav_uint64 sampleCount)
  63345. {
  63346. drwav_uint64 iSample;
  63347. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63348. pSamples[iSample] = drwav__bswap_s16(pSamples[iSample]);
  63349. }
  63350. }
  63351. static DRWAV_INLINE void drwav__bswap_s24(drwav_uint8* p)
  63352. {
  63353. drwav_uint8 t;
  63354. t = p[0];
  63355. p[0] = p[2];
  63356. p[2] = t;
  63357. }
  63358. static DRWAV_INLINE void drwav__bswap_samples_s24(drwav_uint8* pSamples, drwav_uint64 sampleCount)
  63359. {
  63360. drwav_uint64 iSample;
  63361. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63362. drwav_uint8* pSample = pSamples + (iSample*3);
  63363. drwav__bswap_s24(pSample);
  63364. }
  63365. }
  63366. static DRWAV_INLINE drwav_int32 drwav__bswap_s32(drwav_int32 n)
  63367. {
  63368. return (drwav_int32)drwav__bswap32((drwav_uint32)n);
  63369. }
  63370. static DRWAV_INLINE void drwav__bswap_samples_s32(drwav_int32* pSamples, drwav_uint64 sampleCount)
  63371. {
  63372. drwav_uint64 iSample;
  63373. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63374. pSamples[iSample] = drwav__bswap_s32(pSamples[iSample]);
  63375. }
  63376. }
  63377. static DRWAV_INLINE float drwav__bswap_f32(float n)
  63378. {
  63379. union {
  63380. drwav_uint32 i;
  63381. float f;
  63382. } x;
  63383. x.f = n;
  63384. x.i = drwav__bswap32(x.i);
  63385. return x.f;
  63386. }
  63387. static DRWAV_INLINE void drwav__bswap_samples_f32(float* pSamples, drwav_uint64 sampleCount)
  63388. {
  63389. drwav_uint64 iSample;
  63390. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63391. pSamples[iSample] = drwav__bswap_f32(pSamples[iSample]);
  63392. }
  63393. }
  63394. static DRWAV_INLINE double drwav__bswap_f64(double n)
  63395. {
  63396. union {
  63397. drwav_uint64 i;
  63398. double f;
  63399. } x;
  63400. x.f = n;
  63401. x.i = drwav__bswap64(x.i);
  63402. return x.f;
  63403. }
  63404. static DRWAV_INLINE void drwav__bswap_samples_f64(double* pSamples, drwav_uint64 sampleCount)
  63405. {
  63406. drwav_uint64 iSample;
  63407. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63408. pSamples[iSample] = drwav__bswap_f64(pSamples[iSample]);
  63409. }
  63410. }
  63411. static DRWAV_INLINE void drwav__bswap_samples_pcm(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample)
  63412. {
  63413. switch (bytesPerSample)
  63414. {
  63415. case 1:
  63416. {
  63417. } break;
  63418. case 2:
  63419. {
  63420. drwav__bswap_samples_s16((drwav_int16*)pSamples, sampleCount);
  63421. } break;
  63422. case 3:
  63423. {
  63424. drwav__bswap_samples_s24((drwav_uint8*)pSamples, sampleCount);
  63425. } break;
  63426. case 4:
  63427. {
  63428. drwav__bswap_samples_s32((drwav_int32*)pSamples, sampleCount);
  63429. } break;
  63430. default:
  63431. {
  63432. DRWAV_ASSERT(DRWAV_FALSE);
  63433. } break;
  63434. }
  63435. }
  63436. static DRWAV_INLINE void drwav__bswap_samples_ieee(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample)
  63437. {
  63438. switch (bytesPerSample)
  63439. {
  63440. #if 0
  63441. case 2:
  63442. {
  63443. drwav__bswap_samples_f16((drwav_float16*)pSamples, sampleCount);
  63444. } break;
  63445. #endif
  63446. case 4:
  63447. {
  63448. drwav__bswap_samples_f32((float*)pSamples, sampleCount);
  63449. } break;
  63450. case 8:
  63451. {
  63452. drwav__bswap_samples_f64((double*)pSamples, sampleCount);
  63453. } break;
  63454. default:
  63455. {
  63456. DRWAV_ASSERT(DRWAV_FALSE);
  63457. } break;
  63458. }
  63459. }
  63460. static DRWAV_INLINE void drwav__bswap_samples(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample, drwav_uint16 format)
  63461. {
  63462. switch (format)
  63463. {
  63464. case DR_WAVE_FORMAT_PCM:
  63465. {
  63466. drwav__bswap_samples_pcm(pSamples, sampleCount, bytesPerSample);
  63467. } break;
  63468. case DR_WAVE_FORMAT_IEEE_FLOAT:
  63469. {
  63470. drwav__bswap_samples_ieee(pSamples, sampleCount, bytesPerSample);
  63471. } break;
  63472. case DR_WAVE_FORMAT_ALAW:
  63473. case DR_WAVE_FORMAT_MULAW:
  63474. {
  63475. drwav__bswap_samples_s16((drwav_int16*)pSamples, sampleCount);
  63476. } break;
  63477. case DR_WAVE_FORMAT_ADPCM:
  63478. case DR_WAVE_FORMAT_DVI_ADPCM:
  63479. default:
  63480. {
  63481. DRWAV_ASSERT(DRWAV_FALSE);
  63482. } break;
  63483. }
  63484. }
  63485. DRWAV_PRIVATE void* drwav__malloc_default(size_t sz, void* pUserData)
  63486. {
  63487. (void)pUserData;
  63488. return DRWAV_MALLOC(sz);
  63489. }
  63490. DRWAV_PRIVATE void* drwav__realloc_default(void* p, size_t sz, void* pUserData)
  63491. {
  63492. (void)pUserData;
  63493. return DRWAV_REALLOC(p, sz);
  63494. }
  63495. DRWAV_PRIVATE void drwav__free_default(void* p, void* pUserData)
  63496. {
  63497. (void)pUserData;
  63498. DRWAV_FREE(p);
  63499. }
  63500. DRWAV_PRIVATE void* drwav__malloc_from_callbacks(size_t sz, const drwav_allocation_callbacks* pAllocationCallbacks)
  63501. {
  63502. if (pAllocationCallbacks == NULL) {
  63503. return NULL;
  63504. }
  63505. if (pAllocationCallbacks->onMalloc != NULL) {
  63506. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  63507. }
  63508. if (pAllocationCallbacks->onRealloc != NULL) {
  63509. return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  63510. }
  63511. return NULL;
  63512. }
  63513. DRWAV_PRIVATE void* drwav__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drwav_allocation_callbacks* pAllocationCallbacks)
  63514. {
  63515. if (pAllocationCallbacks == NULL) {
  63516. return NULL;
  63517. }
  63518. if (pAllocationCallbacks->onRealloc != NULL) {
  63519. return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  63520. }
  63521. if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  63522. void* p2;
  63523. p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  63524. if (p2 == NULL) {
  63525. return NULL;
  63526. }
  63527. if (p != NULL) {
  63528. DRWAV_COPY_MEMORY(p2, p, szOld);
  63529. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  63530. }
  63531. return p2;
  63532. }
  63533. return NULL;
  63534. }
  63535. DRWAV_PRIVATE void drwav__free_from_callbacks(void* p, const drwav_allocation_callbacks* pAllocationCallbacks)
  63536. {
  63537. if (p == NULL || pAllocationCallbacks == NULL) {
  63538. return;
  63539. }
  63540. if (pAllocationCallbacks->onFree != NULL) {
  63541. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  63542. }
  63543. }
  63544. DRWAV_PRIVATE drwav_allocation_callbacks drwav_copy_allocation_callbacks_or_defaults(const drwav_allocation_callbacks* pAllocationCallbacks)
  63545. {
  63546. if (pAllocationCallbacks != NULL) {
  63547. return *pAllocationCallbacks;
  63548. } else {
  63549. drwav_allocation_callbacks allocationCallbacks;
  63550. allocationCallbacks.pUserData = NULL;
  63551. allocationCallbacks.onMalloc = drwav__malloc_default;
  63552. allocationCallbacks.onRealloc = drwav__realloc_default;
  63553. allocationCallbacks.onFree = drwav__free_default;
  63554. return allocationCallbacks;
  63555. }
  63556. }
  63557. static DRWAV_INLINE drwav_bool32 drwav__is_compressed_format_tag(drwav_uint16 formatTag)
  63558. {
  63559. return
  63560. formatTag == DR_WAVE_FORMAT_ADPCM ||
  63561. formatTag == DR_WAVE_FORMAT_DVI_ADPCM;
  63562. }
  63563. DRWAV_PRIVATE unsigned int drwav__chunk_padding_size_riff(drwav_uint64 chunkSize)
  63564. {
  63565. return (unsigned int)(chunkSize % 2);
  63566. }
  63567. DRWAV_PRIVATE unsigned int drwav__chunk_padding_size_w64(drwav_uint64 chunkSize)
  63568. {
  63569. return (unsigned int)(chunkSize % 8);
  63570. }
  63571. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
  63572. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
  63573. DRWAV_PRIVATE drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount);
  63574. DRWAV_PRIVATE drwav_result drwav__read_chunk_header(drwav_read_proc onRead, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_chunk_header* pHeaderOut)
  63575. {
  63576. if (container == drwav_container_riff || container == drwav_container_rf64) {
  63577. drwav_uint8 sizeInBytes[4];
  63578. if (onRead(pUserData, pHeaderOut->id.fourcc, 4) != 4) {
  63579. return DRWAV_AT_END;
  63580. }
  63581. if (onRead(pUserData, sizeInBytes, 4) != 4) {
  63582. return DRWAV_INVALID_FILE;
  63583. }
  63584. pHeaderOut->sizeInBytes = drwav_bytes_to_u32(sizeInBytes);
  63585. pHeaderOut->paddingSize = drwav__chunk_padding_size_riff(pHeaderOut->sizeInBytes);
  63586. *pRunningBytesReadOut += 8;
  63587. } else {
  63588. drwav_uint8 sizeInBytes[8];
  63589. if (onRead(pUserData, pHeaderOut->id.guid, 16) != 16) {
  63590. return DRWAV_AT_END;
  63591. }
  63592. if (onRead(pUserData, sizeInBytes, 8) != 8) {
  63593. return DRWAV_INVALID_FILE;
  63594. }
  63595. pHeaderOut->sizeInBytes = drwav_bytes_to_u64(sizeInBytes) - 24;
  63596. pHeaderOut->paddingSize = drwav__chunk_padding_size_w64(pHeaderOut->sizeInBytes);
  63597. *pRunningBytesReadOut += 24;
  63598. }
  63599. return DRWAV_SUCCESS;
  63600. }
  63601. DRWAV_PRIVATE drwav_bool32 drwav__seek_forward(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
  63602. {
  63603. drwav_uint64 bytesRemainingToSeek = offset;
  63604. while (bytesRemainingToSeek > 0) {
  63605. if (bytesRemainingToSeek > 0x7FFFFFFF) {
  63606. if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_current)) {
  63607. return DRWAV_FALSE;
  63608. }
  63609. bytesRemainingToSeek -= 0x7FFFFFFF;
  63610. } else {
  63611. if (!onSeek(pUserData, (int)bytesRemainingToSeek, drwav_seek_origin_current)) {
  63612. return DRWAV_FALSE;
  63613. }
  63614. bytesRemainingToSeek = 0;
  63615. }
  63616. }
  63617. return DRWAV_TRUE;
  63618. }
  63619. DRWAV_PRIVATE drwav_bool32 drwav__seek_from_start(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
  63620. {
  63621. if (offset <= 0x7FFFFFFF) {
  63622. return onSeek(pUserData, (int)offset, drwav_seek_origin_start);
  63623. }
  63624. if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_start)) {
  63625. return DRWAV_FALSE;
  63626. }
  63627. offset -= 0x7FFFFFFF;
  63628. for (;;) {
  63629. if (offset <= 0x7FFFFFFF) {
  63630. return onSeek(pUserData, (int)offset, drwav_seek_origin_current);
  63631. }
  63632. if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_current)) {
  63633. return DRWAV_FALSE;
  63634. }
  63635. offset -= 0x7FFFFFFF;
  63636. }
  63637. }
  63638. DRWAV_PRIVATE drwav_bool32 drwav__read_fmt(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_fmt* fmtOut)
  63639. {
  63640. drwav_chunk_header header;
  63641. drwav_uint8 fmt[16];
  63642. if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) {
  63643. return DRWAV_FALSE;
  63644. }
  63645. while (((container == drwav_container_riff || container == drwav_container_rf64) && !drwav_fourcc_equal(header.id.fourcc, "fmt ")) || (container == drwav_container_w64 && !drwav_guid_equal(header.id.guid, drwavGUID_W64_FMT))) {
  63646. if (!drwav__seek_forward(onSeek, header.sizeInBytes + header.paddingSize, pUserData)) {
  63647. return DRWAV_FALSE;
  63648. }
  63649. *pRunningBytesReadOut += header.sizeInBytes + header.paddingSize;
  63650. if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) {
  63651. return DRWAV_FALSE;
  63652. }
  63653. }
  63654. if (container == drwav_container_riff || container == drwav_container_rf64) {
  63655. if (!drwav_fourcc_equal(header.id.fourcc, "fmt ")) {
  63656. return DRWAV_FALSE;
  63657. }
  63658. } else {
  63659. if (!drwav_guid_equal(header.id.guid, drwavGUID_W64_FMT)) {
  63660. return DRWAV_FALSE;
  63661. }
  63662. }
  63663. if (onRead(pUserData, fmt, sizeof(fmt)) != sizeof(fmt)) {
  63664. return DRWAV_FALSE;
  63665. }
  63666. *pRunningBytesReadOut += sizeof(fmt);
  63667. fmtOut->formatTag = drwav_bytes_to_u16(fmt + 0);
  63668. fmtOut->channels = drwav_bytes_to_u16(fmt + 2);
  63669. fmtOut->sampleRate = drwav_bytes_to_u32(fmt + 4);
  63670. fmtOut->avgBytesPerSec = drwav_bytes_to_u32(fmt + 8);
  63671. fmtOut->blockAlign = drwav_bytes_to_u16(fmt + 12);
  63672. fmtOut->bitsPerSample = drwav_bytes_to_u16(fmt + 14);
  63673. fmtOut->extendedSize = 0;
  63674. fmtOut->validBitsPerSample = 0;
  63675. fmtOut->channelMask = 0;
  63676. DRWAV_ZERO_MEMORY(fmtOut->subFormat, sizeof(fmtOut->subFormat));
  63677. if (header.sizeInBytes > 16) {
  63678. drwav_uint8 fmt_cbSize[2];
  63679. int bytesReadSoFar = 0;
  63680. if (onRead(pUserData, fmt_cbSize, sizeof(fmt_cbSize)) != sizeof(fmt_cbSize)) {
  63681. return DRWAV_FALSE;
  63682. }
  63683. *pRunningBytesReadOut += sizeof(fmt_cbSize);
  63684. bytesReadSoFar = 18;
  63685. fmtOut->extendedSize = drwav_bytes_to_u16(fmt_cbSize);
  63686. if (fmtOut->extendedSize > 0) {
  63687. if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
  63688. if (fmtOut->extendedSize != 22) {
  63689. return DRWAV_FALSE;
  63690. }
  63691. }
  63692. if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
  63693. drwav_uint8 fmtext[22];
  63694. if (onRead(pUserData, fmtext, fmtOut->extendedSize) != fmtOut->extendedSize) {
  63695. return DRWAV_FALSE;
  63696. }
  63697. fmtOut->validBitsPerSample = drwav_bytes_to_u16(fmtext + 0);
  63698. fmtOut->channelMask = drwav_bytes_to_u32(fmtext + 2);
  63699. drwav_bytes_to_guid(fmtext + 6, fmtOut->subFormat);
  63700. } else {
  63701. if (!onSeek(pUserData, fmtOut->extendedSize, drwav_seek_origin_current)) {
  63702. return DRWAV_FALSE;
  63703. }
  63704. }
  63705. *pRunningBytesReadOut += fmtOut->extendedSize;
  63706. bytesReadSoFar += fmtOut->extendedSize;
  63707. }
  63708. if (!onSeek(pUserData, (int)(header.sizeInBytes - bytesReadSoFar), drwav_seek_origin_current)) {
  63709. return DRWAV_FALSE;
  63710. }
  63711. *pRunningBytesReadOut += (header.sizeInBytes - bytesReadSoFar);
  63712. }
  63713. if (header.paddingSize > 0) {
  63714. if (!onSeek(pUserData, header.paddingSize, drwav_seek_origin_current)) {
  63715. return DRWAV_FALSE;
  63716. }
  63717. *pRunningBytesReadOut += header.paddingSize;
  63718. }
  63719. return DRWAV_TRUE;
  63720. }
  63721. DRWAV_PRIVATE size_t drwav__on_read(drwav_read_proc onRead, void* pUserData, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor)
  63722. {
  63723. size_t bytesRead;
  63724. DRWAV_ASSERT(onRead != NULL);
  63725. DRWAV_ASSERT(pCursor != NULL);
  63726. bytesRead = onRead(pUserData, pBufferOut, bytesToRead);
  63727. *pCursor += bytesRead;
  63728. return bytesRead;
  63729. }
  63730. #if 0
  63731. DRWAV_PRIVATE drwav_bool32 drwav__on_seek(drwav_seek_proc onSeek, void* pUserData, int offset, drwav_seek_origin origin, drwav_uint64* pCursor)
  63732. {
  63733. DRWAV_ASSERT(onSeek != NULL);
  63734. DRWAV_ASSERT(pCursor != NULL);
  63735. if (!onSeek(pUserData, offset, origin)) {
  63736. return DRWAV_FALSE;
  63737. }
  63738. if (origin == drwav_seek_origin_start) {
  63739. *pCursor = offset;
  63740. } else {
  63741. *pCursor += offset;
  63742. }
  63743. return DRWAV_TRUE;
  63744. }
  63745. #endif
  63746. #define DRWAV_SMPL_BYTES 36
  63747. #define DRWAV_SMPL_LOOP_BYTES 24
  63748. #define DRWAV_INST_BYTES 7
  63749. #define DRWAV_ACID_BYTES 24
  63750. #define DRWAV_CUE_BYTES 4
  63751. #define DRWAV_BEXT_BYTES 602
  63752. #define DRWAV_BEXT_DESCRIPTION_BYTES 256
  63753. #define DRWAV_BEXT_ORIGINATOR_NAME_BYTES 32
  63754. #define DRWAV_BEXT_ORIGINATOR_REF_BYTES 32
  63755. #define DRWAV_BEXT_RESERVED_BYTES 180
  63756. #define DRWAV_BEXT_UMID_BYTES 64
  63757. #define DRWAV_CUE_POINT_BYTES 24
  63758. #define DRWAV_LIST_LABEL_OR_NOTE_BYTES 4
  63759. #define DRWAV_LIST_LABELLED_TEXT_BYTES 20
  63760. #define DRWAV_METADATA_ALIGNMENT 8
  63761. typedef enum
  63762. {
  63763. drwav__metadata_parser_stage_count,
  63764. drwav__metadata_parser_stage_read
  63765. } drwav__metadata_parser_stage;
  63766. typedef struct
  63767. {
  63768. drwav_read_proc onRead;
  63769. drwav_seek_proc onSeek;
  63770. void *pReadSeekUserData;
  63771. drwav__metadata_parser_stage stage;
  63772. drwav_metadata *pMetadata;
  63773. drwav_uint32 metadataCount;
  63774. drwav_uint8 *pData;
  63775. drwav_uint8 *pDataCursor;
  63776. drwav_uint64 metadataCursor;
  63777. drwav_uint64 extraCapacity;
  63778. } drwav__metadata_parser;
  63779. DRWAV_PRIVATE size_t drwav__metadata_memory_capacity(drwav__metadata_parser* pParser)
  63780. {
  63781. drwav_uint64 cap = sizeof(drwav_metadata) * (drwav_uint64)pParser->metadataCount + pParser->extraCapacity;
  63782. if (cap > DRWAV_SIZE_MAX) {
  63783. return 0;
  63784. }
  63785. return (size_t)cap;
  63786. }
  63787. DRWAV_PRIVATE drwav_uint8* drwav__metadata_get_memory(drwav__metadata_parser* pParser, size_t size, size_t align)
  63788. {
  63789. drwav_uint8* pResult;
  63790. if (align) {
  63791. drwav_uintptr modulo = (drwav_uintptr)pParser->pDataCursor % align;
  63792. if (modulo != 0) {
  63793. pParser->pDataCursor += align - modulo;
  63794. }
  63795. }
  63796. pResult = pParser->pDataCursor;
  63797. DRWAV_ASSERT((pResult + size) <= (pParser->pData + drwav__metadata_memory_capacity(pParser)));
  63798. pParser->pDataCursor += size;
  63799. return pResult;
  63800. }
  63801. DRWAV_PRIVATE void drwav__metadata_request_extra_memory_for_stage_2(drwav__metadata_parser* pParser, size_t bytes, size_t align)
  63802. {
  63803. size_t extra = bytes + (align ? (align - 1) : 0);
  63804. pParser->extraCapacity += extra;
  63805. }
  63806. DRWAV_PRIVATE drwav_result drwav__metadata_alloc(drwav__metadata_parser* pParser, drwav_allocation_callbacks* pAllocationCallbacks)
  63807. {
  63808. if (pParser->extraCapacity != 0 || pParser->metadataCount != 0) {
  63809. pAllocationCallbacks->onFree(pParser->pData, pAllocationCallbacks->pUserData);
  63810. pParser->pData = (drwav_uint8*)pAllocationCallbacks->onMalloc(drwav__metadata_memory_capacity(pParser), pAllocationCallbacks->pUserData);
  63811. pParser->pDataCursor = pParser->pData;
  63812. if (pParser->pData == NULL) {
  63813. return DRWAV_OUT_OF_MEMORY;
  63814. }
  63815. pParser->pMetadata = (drwav_metadata*)drwav__metadata_get_memory(pParser, sizeof(drwav_metadata) * pParser->metadataCount, 1);
  63816. pParser->metadataCursor = 0;
  63817. }
  63818. return DRWAV_SUCCESS;
  63819. }
  63820. DRWAV_PRIVATE size_t drwav__metadata_parser_read(drwav__metadata_parser* pParser, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor)
  63821. {
  63822. if (pCursor != NULL) {
  63823. return drwav__on_read(pParser->onRead, pParser->pReadSeekUserData, pBufferOut, bytesToRead, pCursor);
  63824. } else {
  63825. return pParser->onRead(pParser->pReadSeekUserData, pBufferOut, bytesToRead);
  63826. }
  63827. }
  63828. DRWAV_PRIVATE drwav_uint64 drwav__read_smpl_to_metadata_obj(drwav__metadata_parser* pParser, const drwav_chunk_header* pChunkHeader, drwav_metadata* pMetadata)
  63829. {
  63830. drwav_uint8 smplHeaderData[DRWAV_SMPL_BYTES];
  63831. drwav_uint64 totalBytesRead = 0;
  63832. size_t bytesJustRead;
  63833. if (pMetadata == NULL) {
  63834. return 0;
  63835. }
  63836. bytesJustRead = drwav__metadata_parser_read(pParser, smplHeaderData, sizeof(smplHeaderData), &totalBytesRead);
  63837. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  63838. DRWAV_ASSERT(pChunkHeader != NULL);
  63839. if (pMetadata != NULL && bytesJustRead == sizeof(smplHeaderData)) {
  63840. drwav_uint32 iSampleLoop;
  63841. pMetadata->type = drwav_metadata_type_smpl;
  63842. pMetadata->data.smpl.manufacturerId = drwav_bytes_to_u32(smplHeaderData + 0);
  63843. pMetadata->data.smpl.productId = drwav_bytes_to_u32(smplHeaderData + 4);
  63844. pMetadata->data.smpl.samplePeriodNanoseconds = drwav_bytes_to_u32(smplHeaderData + 8);
  63845. pMetadata->data.smpl.midiUnityNote = drwav_bytes_to_u32(smplHeaderData + 12);
  63846. pMetadata->data.smpl.midiPitchFraction = drwav_bytes_to_u32(smplHeaderData + 16);
  63847. pMetadata->data.smpl.smpteFormat = drwav_bytes_to_u32(smplHeaderData + 20);
  63848. pMetadata->data.smpl.smpteOffset = drwav_bytes_to_u32(smplHeaderData + 24);
  63849. pMetadata->data.smpl.sampleLoopCount = drwav_bytes_to_u32(smplHeaderData + 28);
  63850. pMetadata->data.smpl.samplerSpecificDataSizeInBytes = drwav_bytes_to_u32(smplHeaderData + 32);
  63851. if (pMetadata->data.smpl.sampleLoopCount == (pChunkHeader->sizeInBytes - DRWAV_SMPL_BYTES) / DRWAV_SMPL_LOOP_BYTES) {
  63852. pMetadata->data.smpl.pLoops = (drwav_smpl_loop*)drwav__metadata_get_memory(pParser, sizeof(drwav_smpl_loop) * pMetadata->data.smpl.sampleLoopCount, DRWAV_METADATA_ALIGNMENT);
  63853. for (iSampleLoop = 0; iSampleLoop < pMetadata->data.smpl.sampleLoopCount; ++iSampleLoop) {
  63854. drwav_uint8 smplLoopData[DRWAV_SMPL_LOOP_BYTES];
  63855. bytesJustRead = drwav__metadata_parser_read(pParser, smplLoopData, sizeof(smplLoopData), &totalBytesRead);
  63856. if (bytesJustRead == sizeof(smplLoopData)) {
  63857. pMetadata->data.smpl.pLoops[iSampleLoop].cuePointId = drwav_bytes_to_u32(smplLoopData + 0);
  63858. pMetadata->data.smpl.pLoops[iSampleLoop].type = drwav_bytes_to_u32(smplLoopData + 4);
  63859. pMetadata->data.smpl.pLoops[iSampleLoop].firstSampleByteOffset = drwav_bytes_to_u32(smplLoopData + 8);
  63860. pMetadata->data.smpl.pLoops[iSampleLoop].lastSampleByteOffset = drwav_bytes_to_u32(smplLoopData + 12);
  63861. pMetadata->data.smpl.pLoops[iSampleLoop].sampleFraction = drwav_bytes_to_u32(smplLoopData + 16);
  63862. pMetadata->data.smpl.pLoops[iSampleLoop].playCount = drwav_bytes_to_u32(smplLoopData + 20);
  63863. } else {
  63864. break;
  63865. }
  63866. }
  63867. if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) {
  63868. pMetadata->data.smpl.pSamplerSpecificData = drwav__metadata_get_memory(pParser, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, 1);
  63869. DRWAV_ASSERT(pMetadata->data.smpl.pSamplerSpecificData != NULL);
  63870. drwav__metadata_parser_read(pParser, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, &totalBytesRead);
  63871. }
  63872. }
  63873. }
  63874. return totalBytesRead;
  63875. }
  63876. DRWAV_PRIVATE drwav_uint64 drwav__read_cue_to_metadata_obj(drwav__metadata_parser* pParser, const drwav_chunk_header* pChunkHeader, drwav_metadata* pMetadata)
  63877. {
  63878. drwav_uint8 cueHeaderSectionData[DRWAV_CUE_BYTES];
  63879. drwav_uint64 totalBytesRead = 0;
  63880. size_t bytesJustRead;
  63881. if (pMetadata == NULL) {
  63882. return 0;
  63883. }
  63884. bytesJustRead = drwav__metadata_parser_read(pParser, cueHeaderSectionData, sizeof(cueHeaderSectionData), &totalBytesRead);
  63885. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  63886. if (bytesJustRead == sizeof(cueHeaderSectionData)) {
  63887. pMetadata->type = drwav_metadata_type_cue;
  63888. pMetadata->data.cue.cuePointCount = drwav_bytes_to_u32(cueHeaderSectionData);
  63889. if (pMetadata->data.cue.cuePointCount == (pChunkHeader->sizeInBytes - DRWAV_CUE_BYTES) / DRWAV_CUE_POINT_BYTES) {
  63890. pMetadata->data.cue.pCuePoints = (drwav_cue_point*)drwav__metadata_get_memory(pParser, sizeof(drwav_cue_point) * pMetadata->data.cue.cuePointCount, DRWAV_METADATA_ALIGNMENT);
  63891. DRWAV_ASSERT(pMetadata->data.cue.pCuePoints != NULL);
  63892. if (pMetadata->data.cue.cuePointCount > 0) {
  63893. drwav_uint32 iCuePoint;
  63894. for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) {
  63895. drwav_uint8 cuePointData[DRWAV_CUE_POINT_BYTES];
  63896. bytesJustRead = drwav__metadata_parser_read(pParser, cuePointData, sizeof(cuePointData), &totalBytesRead);
  63897. if (bytesJustRead == sizeof(cuePointData)) {
  63898. pMetadata->data.cue.pCuePoints[iCuePoint].id = drwav_bytes_to_u32(cuePointData + 0);
  63899. pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition = drwav_bytes_to_u32(cuePointData + 4);
  63900. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[0] = cuePointData[8];
  63901. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[1] = cuePointData[9];
  63902. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[2] = cuePointData[10];
  63903. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[3] = cuePointData[11];
  63904. pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart = drwav_bytes_to_u32(cuePointData + 12);
  63905. pMetadata->data.cue.pCuePoints[iCuePoint].blockStart = drwav_bytes_to_u32(cuePointData + 16);
  63906. pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset = drwav_bytes_to_u32(cuePointData + 20);
  63907. } else {
  63908. break;
  63909. }
  63910. }
  63911. }
  63912. }
  63913. }
  63914. return totalBytesRead;
  63915. }
  63916. DRWAV_PRIVATE drwav_uint64 drwav__read_inst_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata)
  63917. {
  63918. drwav_uint8 instData[DRWAV_INST_BYTES];
  63919. drwav_uint64 bytesRead;
  63920. if (pMetadata == NULL) {
  63921. return 0;
  63922. }
  63923. bytesRead = drwav__metadata_parser_read(pParser, instData, sizeof(instData), NULL);
  63924. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  63925. if (bytesRead == sizeof(instData)) {
  63926. pMetadata->type = drwav_metadata_type_inst;
  63927. pMetadata->data.inst.midiUnityNote = (drwav_int8)instData[0];
  63928. pMetadata->data.inst.fineTuneCents = (drwav_int8)instData[1];
  63929. pMetadata->data.inst.gainDecibels = (drwav_int8)instData[2];
  63930. pMetadata->data.inst.lowNote = (drwav_int8)instData[3];
  63931. pMetadata->data.inst.highNote = (drwav_int8)instData[4];
  63932. pMetadata->data.inst.lowVelocity = (drwav_int8)instData[5];
  63933. pMetadata->data.inst.highVelocity = (drwav_int8)instData[6];
  63934. }
  63935. return bytesRead;
  63936. }
  63937. DRWAV_PRIVATE drwav_uint64 drwav__read_acid_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata)
  63938. {
  63939. drwav_uint8 acidData[DRWAV_ACID_BYTES];
  63940. drwav_uint64 bytesRead;
  63941. if (pMetadata == NULL) {
  63942. return 0;
  63943. }
  63944. bytesRead = drwav__metadata_parser_read(pParser, acidData, sizeof(acidData), NULL);
  63945. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  63946. if (bytesRead == sizeof(acidData)) {
  63947. pMetadata->type = drwav_metadata_type_acid;
  63948. pMetadata->data.acid.flags = drwav_bytes_to_u32(acidData + 0);
  63949. pMetadata->data.acid.midiUnityNote = drwav_bytes_to_u16(acidData + 4);
  63950. pMetadata->data.acid.reserved1 = drwav_bytes_to_u16(acidData + 6);
  63951. pMetadata->data.acid.reserved2 = drwav_bytes_to_f32(acidData + 8);
  63952. pMetadata->data.acid.numBeats = drwav_bytes_to_u32(acidData + 12);
  63953. pMetadata->data.acid.meterDenominator = drwav_bytes_to_u16(acidData + 16);
  63954. pMetadata->data.acid.meterNumerator = drwav_bytes_to_u16(acidData + 18);
  63955. pMetadata->data.acid.tempo = drwav_bytes_to_f32(acidData + 20);
  63956. }
  63957. return bytesRead;
  63958. }
  63959. DRWAV_PRIVATE size_t drwav__strlen(const char* str)
  63960. {
  63961. size_t result = 0;
  63962. while (*str++) {
  63963. result += 1;
  63964. }
  63965. return result;
  63966. }
  63967. DRWAV_PRIVATE size_t drwav__strlen_clamped(const char* str, size_t maxToRead)
  63968. {
  63969. size_t result = 0;
  63970. while (*str++ && result < maxToRead) {
  63971. result += 1;
  63972. }
  63973. return result;
  63974. }
  63975. DRWAV_PRIVATE char* drwav__metadata_copy_string(drwav__metadata_parser* pParser, const char* str, size_t maxToRead)
  63976. {
  63977. size_t len = drwav__strlen_clamped(str, maxToRead);
  63978. if (len) {
  63979. char* result = (char*)drwav__metadata_get_memory(pParser, len + 1, 1);
  63980. DRWAV_ASSERT(result != NULL);
  63981. DRWAV_COPY_MEMORY(result, str, len);
  63982. result[len] = '\0';
  63983. return result;
  63984. } else {
  63985. return NULL;
  63986. }
  63987. }
  63988. typedef struct
  63989. {
  63990. const void* pBuffer;
  63991. size_t sizeInBytes;
  63992. size_t cursor;
  63993. } drwav_buffer_reader;
  63994. DRWAV_PRIVATE drwav_result drwav_buffer_reader_init(const void* pBuffer, size_t sizeInBytes, drwav_buffer_reader* pReader)
  63995. {
  63996. DRWAV_ASSERT(pBuffer != NULL);
  63997. DRWAV_ASSERT(pReader != NULL);
  63998. DRWAV_ZERO_OBJECT(pReader);
  63999. pReader->pBuffer = pBuffer;
  64000. pReader->sizeInBytes = sizeInBytes;
  64001. pReader->cursor = 0;
  64002. return DRWAV_SUCCESS;
  64003. }
  64004. DRWAV_PRIVATE const void* drwav_buffer_reader_ptr(const drwav_buffer_reader* pReader)
  64005. {
  64006. DRWAV_ASSERT(pReader != NULL);
  64007. return drwav_offset_ptr(pReader->pBuffer, pReader->cursor);
  64008. }
  64009. DRWAV_PRIVATE drwav_result drwav_buffer_reader_seek(drwav_buffer_reader* pReader, size_t bytesToSeek)
  64010. {
  64011. DRWAV_ASSERT(pReader != NULL);
  64012. if (pReader->cursor + bytesToSeek > pReader->sizeInBytes) {
  64013. return DRWAV_BAD_SEEK;
  64014. }
  64015. pReader->cursor += bytesToSeek;
  64016. return DRWAV_SUCCESS;
  64017. }
  64018. DRWAV_PRIVATE drwav_result drwav_buffer_reader_read(drwav_buffer_reader* pReader, void* pDst, size_t bytesToRead, size_t* pBytesRead)
  64019. {
  64020. drwav_result result = DRWAV_SUCCESS;
  64021. size_t bytesRemaining;
  64022. DRWAV_ASSERT(pReader != NULL);
  64023. if (pBytesRead != NULL) {
  64024. *pBytesRead = 0;
  64025. }
  64026. bytesRemaining = (pReader->sizeInBytes - pReader->cursor);
  64027. if (bytesToRead > bytesRemaining) {
  64028. bytesToRead = bytesRemaining;
  64029. }
  64030. if (pDst == NULL) {
  64031. result = drwav_buffer_reader_seek(pReader, bytesToRead);
  64032. } else {
  64033. DRWAV_COPY_MEMORY(pDst, drwav_buffer_reader_ptr(pReader), bytesToRead);
  64034. pReader->cursor += bytesToRead;
  64035. }
  64036. DRWAV_ASSERT(pReader->cursor <= pReader->sizeInBytes);
  64037. if (result == DRWAV_SUCCESS) {
  64038. if (pBytesRead != NULL) {
  64039. *pBytesRead = bytesToRead;
  64040. }
  64041. }
  64042. return DRWAV_SUCCESS;
  64043. }
  64044. DRWAV_PRIVATE drwav_result drwav_buffer_reader_read_u16(drwav_buffer_reader* pReader, drwav_uint16* pDst)
  64045. {
  64046. drwav_result result;
  64047. size_t bytesRead;
  64048. drwav_uint8 data[2];
  64049. DRWAV_ASSERT(pReader != NULL);
  64050. DRWAV_ASSERT(pDst != NULL);
  64051. *pDst = 0;
  64052. result = drwav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead);
  64053. if (result != DRWAV_SUCCESS || bytesRead != sizeof(*pDst)) {
  64054. return result;
  64055. }
  64056. *pDst = drwav_bytes_to_u16(data);
  64057. return DRWAV_SUCCESS;
  64058. }
  64059. DRWAV_PRIVATE drwav_result drwav_buffer_reader_read_u32(drwav_buffer_reader* pReader, drwav_uint32* pDst)
  64060. {
  64061. drwav_result result;
  64062. size_t bytesRead;
  64063. drwav_uint8 data[4];
  64064. DRWAV_ASSERT(pReader != NULL);
  64065. DRWAV_ASSERT(pDst != NULL);
  64066. *pDst = 0;
  64067. result = drwav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead);
  64068. if (result != DRWAV_SUCCESS || bytesRead != sizeof(*pDst)) {
  64069. return result;
  64070. }
  64071. *pDst = drwav_bytes_to_u32(data);
  64072. return DRWAV_SUCCESS;
  64073. }
  64074. DRWAV_PRIVATE drwav_uint64 drwav__read_bext_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata, drwav_uint64 chunkSize)
  64075. {
  64076. drwav_uint8 bextData[DRWAV_BEXT_BYTES];
  64077. size_t bytesRead = drwav__metadata_parser_read(pParser, bextData, sizeof(bextData), NULL);
  64078. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  64079. if (bytesRead == sizeof(bextData)) {
  64080. drwav_buffer_reader reader;
  64081. drwav_uint32 timeReferenceLow;
  64082. drwav_uint32 timeReferenceHigh;
  64083. size_t extraBytes;
  64084. pMetadata->type = drwav_metadata_type_bext;
  64085. if (drwav_buffer_reader_init(bextData, bytesRead, &reader) == DRWAV_SUCCESS) {
  64086. pMetadata->data.bext.pDescription = drwav__metadata_copy_string(pParser, (const char*)drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_DESCRIPTION_BYTES);
  64087. drwav_buffer_reader_seek(&reader, DRWAV_BEXT_DESCRIPTION_BYTES);
  64088. pMetadata->data.bext.pOriginatorName = drwav__metadata_copy_string(pParser, (const char*)drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_ORIGINATOR_NAME_BYTES);
  64089. drwav_buffer_reader_seek(&reader, DRWAV_BEXT_ORIGINATOR_NAME_BYTES);
  64090. pMetadata->data.bext.pOriginatorReference = drwav__metadata_copy_string(pParser, (const char*)drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_ORIGINATOR_REF_BYTES);
  64091. drwav_buffer_reader_seek(&reader, DRWAV_BEXT_ORIGINATOR_REF_BYTES);
  64092. drwav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate), NULL);
  64093. drwav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime), NULL);
  64094. drwav_buffer_reader_read_u32(&reader, &timeReferenceLow);
  64095. drwav_buffer_reader_read_u32(&reader, &timeReferenceHigh);
  64096. pMetadata->data.bext.timeReference = ((drwav_uint64)timeReferenceHigh << 32) + timeReferenceLow;
  64097. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.version);
  64098. pMetadata->data.bext.pUMID = drwav__metadata_get_memory(pParser, DRWAV_BEXT_UMID_BYTES, 1);
  64099. drwav_buffer_reader_read(&reader, pMetadata->data.bext.pUMID, DRWAV_BEXT_UMID_BYTES, NULL);
  64100. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessValue);
  64101. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessRange);
  64102. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxTruePeakLevel);
  64103. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxMomentaryLoudness);
  64104. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxShortTermLoudness);
  64105. DRWAV_ASSERT((drwav_offset_ptr(drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_RESERVED_BYTES)) == (bextData + DRWAV_BEXT_BYTES));
  64106. extraBytes = (size_t)(chunkSize - DRWAV_BEXT_BYTES);
  64107. if (extraBytes > 0) {
  64108. pMetadata->data.bext.pCodingHistory = (char*)drwav__metadata_get_memory(pParser, extraBytes + 1, 1);
  64109. DRWAV_ASSERT(pMetadata->data.bext.pCodingHistory != NULL);
  64110. bytesRead += drwav__metadata_parser_read(pParser, pMetadata->data.bext.pCodingHistory, extraBytes, NULL);
  64111. pMetadata->data.bext.codingHistorySize = (drwav_uint32)drwav__strlen(pMetadata->data.bext.pCodingHistory);
  64112. } else {
  64113. pMetadata->data.bext.pCodingHistory = NULL;
  64114. pMetadata->data.bext.codingHistorySize = 0;
  64115. }
  64116. }
  64117. }
  64118. return bytesRead;
  64119. }
  64120. DRWAV_PRIVATE drwav_uint64 drwav__read_list_label_or_note_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata, drwav_uint64 chunkSize, drwav_metadata_type type)
  64121. {
  64122. drwav_uint8 cueIDBuffer[DRWAV_LIST_LABEL_OR_NOTE_BYTES];
  64123. drwav_uint64 totalBytesRead = 0;
  64124. size_t bytesJustRead = drwav__metadata_parser_read(pParser, cueIDBuffer, sizeof(cueIDBuffer), &totalBytesRead);
  64125. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  64126. if (bytesJustRead == sizeof(cueIDBuffer)) {
  64127. drwav_uint32 sizeIncludingNullTerminator;
  64128. pMetadata->type = type;
  64129. pMetadata->data.labelOrNote.cuePointId = drwav_bytes_to_u32(cueIDBuffer);
  64130. sizeIncludingNullTerminator = (drwav_uint32)chunkSize - DRWAV_LIST_LABEL_OR_NOTE_BYTES;
  64131. if (sizeIncludingNullTerminator > 0) {
  64132. pMetadata->data.labelOrNote.stringLength = sizeIncludingNullTerminator - 1;
  64133. pMetadata->data.labelOrNote.pString = (char*)drwav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1);
  64134. DRWAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL);
  64135. drwav__metadata_parser_read(pParser, pMetadata->data.labelOrNote.pString, sizeIncludingNullTerminator, &totalBytesRead);
  64136. } else {
  64137. pMetadata->data.labelOrNote.stringLength = 0;
  64138. pMetadata->data.labelOrNote.pString = NULL;
  64139. }
  64140. }
  64141. return totalBytesRead;
  64142. }
  64143. DRWAV_PRIVATE drwav_uint64 drwav__read_list_labelled_cue_region_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata, drwav_uint64 chunkSize)
  64144. {
  64145. drwav_uint8 buffer[DRWAV_LIST_LABELLED_TEXT_BYTES];
  64146. drwav_uint64 totalBytesRead = 0;
  64147. size_t bytesJustRead = drwav__metadata_parser_read(pParser, buffer, sizeof(buffer), &totalBytesRead);
  64148. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  64149. if (bytesJustRead == sizeof(buffer)) {
  64150. drwav_uint32 sizeIncludingNullTerminator;
  64151. pMetadata->type = drwav_metadata_type_list_labelled_cue_region;
  64152. pMetadata->data.labelledCueRegion.cuePointId = drwav_bytes_to_u32(buffer + 0);
  64153. pMetadata->data.labelledCueRegion.sampleLength = drwav_bytes_to_u32(buffer + 4);
  64154. pMetadata->data.labelledCueRegion.purposeId[0] = buffer[8];
  64155. pMetadata->data.labelledCueRegion.purposeId[1] = buffer[9];
  64156. pMetadata->data.labelledCueRegion.purposeId[2] = buffer[10];
  64157. pMetadata->data.labelledCueRegion.purposeId[3] = buffer[11];
  64158. pMetadata->data.labelledCueRegion.country = drwav_bytes_to_u16(buffer + 12);
  64159. pMetadata->data.labelledCueRegion.language = drwav_bytes_to_u16(buffer + 14);
  64160. pMetadata->data.labelledCueRegion.dialect = drwav_bytes_to_u16(buffer + 16);
  64161. pMetadata->data.labelledCueRegion.codePage = drwav_bytes_to_u16(buffer + 18);
  64162. sizeIncludingNullTerminator = (drwav_uint32)chunkSize - DRWAV_LIST_LABELLED_TEXT_BYTES;
  64163. if (sizeIncludingNullTerminator > 0) {
  64164. pMetadata->data.labelledCueRegion.stringLength = sizeIncludingNullTerminator - 1;
  64165. pMetadata->data.labelledCueRegion.pString = (char*)drwav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1);
  64166. DRWAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL);
  64167. drwav__metadata_parser_read(pParser, pMetadata->data.labelledCueRegion.pString, sizeIncludingNullTerminator, &totalBytesRead);
  64168. } else {
  64169. pMetadata->data.labelledCueRegion.stringLength = 0;
  64170. pMetadata->data.labelledCueRegion.pString = NULL;
  64171. }
  64172. }
  64173. return totalBytesRead;
  64174. }
  64175. DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_info_text_chunk(drwav__metadata_parser* pParser, drwav_uint64 chunkSize, drwav_metadata_type type)
  64176. {
  64177. drwav_uint64 bytesRead = 0;
  64178. drwav_uint32 stringSizeWithNullTerminator = (drwav_uint32)chunkSize;
  64179. if (pParser->stage == drwav__metadata_parser_stage_count) {
  64180. pParser->metadataCount += 1;
  64181. drwav__metadata_request_extra_memory_for_stage_2(pParser, stringSizeWithNullTerminator, 1);
  64182. } else {
  64183. drwav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor];
  64184. pMetadata->type = type;
  64185. if (stringSizeWithNullTerminator > 0) {
  64186. pMetadata->data.infoText.stringLength = stringSizeWithNullTerminator - 1;
  64187. pMetadata->data.infoText.pString = (char*)drwav__metadata_get_memory(pParser, stringSizeWithNullTerminator, 1);
  64188. DRWAV_ASSERT(pMetadata->data.infoText.pString != NULL);
  64189. bytesRead = drwav__metadata_parser_read(pParser, pMetadata->data.infoText.pString, (size_t)stringSizeWithNullTerminator, NULL);
  64190. if (bytesRead == chunkSize) {
  64191. pParser->metadataCursor += 1;
  64192. } else {
  64193. }
  64194. } else {
  64195. pMetadata->data.infoText.stringLength = 0;
  64196. pMetadata->data.infoText.pString = NULL;
  64197. pParser->metadataCursor += 1;
  64198. }
  64199. }
  64200. return bytesRead;
  64201. }
  64202. DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_unknown_chunk(drwav__metadata_parser* pParser, const drwav_uint8* pChunkId, drwav_uint64 chunkSize, drwav_metadata_location location)
  64203. {
  64204. drwav_uint64 bytesRead = 0;
  64205. if (location == drwav_metadata_location_invalid) {
  64206. return 0;
  64207. }
  64208. if (drwav_fourcc_equal(pChunkId, "data") || drwav_fourcc_equal(pChunkId, "fmt") || drwav_fourcc_equal(pChunkId, "fact")) {
  64209. return 0;
  64210. }
  64211. if (pParser->stage == drwav__metadata_parser_stage_count) {
  64212. pParser->metadataCount += 1;
  64213. drwav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)chunkSize, 1);
  64214. } else {
  64215. drwav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor];
  64216. pMetadata->type = drwav_metadata_type_unknown;
  64217. pMetadata->data.unknown.chunkLocation = location;
  64218. pMetadata->data.unknown.id[0] = pChunkId[0];
  64219. pMetadata->data.unknown.id[1] = pChunkId[1];
  64220. pMetadata->data.unknown.id[2] = pChunkId[2];
  64221. pMetadata->data.unknown.id[3] = pChunkId[3];
  64222. pMetadata->data.unknown.dataSizeInBytes = (drwav_uint32)chunkSize;
  64223. pMetadata->data.unknown.pData = (drwav_uint8 *)drwav__metadata_get_memory(pParser, (size_t)chunkSize, 1);
  64224. DRWAV_ASSERT(pMetadata->data.unknown.pData != NULL);
  64225. bytesRead = drwav__metadata_parser_read(pParser, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes, NULL);
  64226. if (bytesRead == pMetadata->data.unknown.dataSizeInBytes) {
  64227. pParser->metadataCursor += 1;
  64228. } else {
  64229. }
  64230. }
  64231. return bytesRead;
  64232. }
  64233. DRWAV_PRIVATE drwav_bool32 drwav__chunk_matches(drwav_metadata_type allowedMetadataTypes, const drwav_uint8* pChunkID, drwav_metadata_type type, const char* pID)
  64234. {
  64235. return (allowedMetadataTypes & type) && drwav_fourcc_equal(pChunkID, pID);
  64236. }
  64237. DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_chunk(drwav__metadata_parser* pParser, const drwav_chunk_header* pChunkHeader, drwav_metadata_type allowedMetadataTypes)
  64238. {
  64239. const drwav_uint8 *pChunkID = pChunkHeader->id.fourcc;
  64240. drwav_uint64 bytesRead = 0;
  64241. if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_smpl, "smpl")) {
  64242. if (pChunkHeader->sizeInBytes >= DRWAV_SMPL_BYTES) {
  64243. if (pParser->stage == drwav__metadata_parser_stage_count) {
  64244. drwav_uint8 buffer[4];
  64245. size_t bytesJustRead;
  64246. if (!pParser->onSeek(pParser->pReadSeekUserData, 28, drwav_seek_origin_current)) {
  64247. return bytesRead;
  64248. }
  64249. bytesRead += 28;
  64250. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead);
  64251. if (bytesJustRead == sizeof(buffer)) {
  64252. drwav_uint32 loopCount = drwav_bytes_to_u32(buffer);
  64253. drwav_uint64 calculatedLoopCount;
  64254. calculatedLoopCount = (pChunkHeader->sizeInBytes - DRWAV_SMPL_BYTES) / DRWAV_SMPL_LOOP_BYTES;
  64255. if (calculatedLoopCount == loopCount) {
  64256. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead);
  64257. if (bytesJustRead == sizeof(buffer)) {
  64258. drwav_uint32 samplerSpecificDataSizeInBytes = drwav_bytes_to_u32(buffer);
  64259. pParser->metadataCount += 1;
  64260. drwav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(drwav_smpl_loop) * loopCount, DRWAV_METADATA_ALIGNMENT);
  64261. drwav__metadata_request_extra_memory_for_stage_2(pParser, samplerSpecificDataSizeInBytes, 1);
  64262. }
  64263. } else {
  64264. }
  64265. }
  64266. } else {
  64267. bytesRead = drwav__read_smpl_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]);
  64268. if (bytesRead == pChunkHeader->sizeInBytes) {
  64269. pParser->metadataCursor += 1;
  64270. } else {
  64271. }
  64272. }
  64273. } else {
  64274. }
  64275. } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_inst, "inst")) {
  64276. if (pChunkHeader->sizeInBytes == DRWAV_INST_BYTES) {
  64277. if (pParser->stage == drwav__metadata_parser_stage_count) {
  64278. pParser->metadataCount += 1;
  64279. } else {
  64280. bytesRead = drwav__read_inst_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]);
  64281. if (bytesRead == pChunkHeader->sizeInBytes) {
  64282. pParser->metadataCursor += 1;
  64283. } else {
  64284. }
  64285. }
  64286. } else {
  64287. }
  64288. } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_acid, "acid")) {
  64289. if (pChunkHeader->sizeInBytes == DRWAV_ACID_BYTES) {
  64290. if (pParser->stage == drwav__metadata_parser_stage_count) {
  64291. pParser->metadataCount += 1;
  64292. } else {
  64293. bytesRead = drwav__read_acid_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]);
  64294. if (bytesRead == pChunkHeader->sizeInBytes) {
  64295. pParser->metadataCursor += 1;
  64296. } else {
  64297. }
  64298. }
  64299. } else {
  64300. }
  64301. } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_cue, "cue ")) {
  64302. if (pChunkHeader->sizeInBytes >= DRWAV_CUE_BYTES) {
  64303. if (pParser->stage == drwav__metadata_parser_stage_count) {
  64304. size_t cueCount;
  64305. pParser->metadataCount += 1;
  64306. cueCount = (size_t)(pChunkHeader->sizeInBytes - DRWAV_CUE_BYTES) / DRWAV_CUE_POINT_BYTES;
  64307. drwav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(drwav_cue_point) * cueCount, DRWAV_METADATA_ALIGNMENT);
  64308. } else {
  64309. bytesRead = drwav__read_cue_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]);
  64310. if (bytesRead == pChunkHeader->sizeInBytes) {
  64311. pParser->metadataCursor += 1;
  64312. } else {
  64313. }
  64314. }
  64315. } else {
  64316. }
  64317. } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_bext, "bext")) {
  64318. if (pChunkHeader->sizeInBytes >= DRWAV_BEXT_BYTES) {
  64319. if (pParser->stage == drwav__metadata_parser_stage_count) {
  64320. char buffer[DRWAV_BEXT_DESCRIPTION_BYTES + 1];
  64321. size_t allocSizeNeeded = DRWAV_BEXT_UMID_BYTES;
  64322. size_t bytesJustRead;
  64323. buffer[DRWAV_BEXT_DESCRIPTION_BYTES] = '\0';
  64324. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, DRWAV_BEXT_DESCRIPTION_BYTES, &bytesRead);
  64325. if (bytesJustRead != DRWAV_BEXT_DESCRIPTION_BYTES) {
  64326. return bytesRead;
  64327. }
  64328. allocSizeNeeded += drwav__strlen(buffer) + 1;
  64329. buffer[DRWAV_BEXT_ORIGINATOR_NAME_BYTES] = '\0';
  64330. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, DRWAV_BEXT_ORIGINATOR_NAME_BYTES, &bytesRead);
  64331. if (bytesJustRead != DRWAV_BEXT_ORIGINATOR_NAME_BYTES) {
  64332. return bytesRead;
  64333. }
  64334. allocSizeNeeded += drwav__strlen(buffer) + 1;
  64335. buffer[DRWAV_BEXT_ORIGINATOR_REF_BYTES] = '\0';
  64336. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, DRWAV_BEXT_ORIGINATOR_REF_BYTES, &bytesRead);
  64337. if (bytesJustRead != DRWAV_BEXT_ORIGINATOR_REF_BYTES) {
  64338. return bytesRead;
  64339. }
  64340. allocSizeNeeded += drwav__strlen(buffer) + 1;
  64341. allocSizeNeeded += (size_t)pChunkHeader->sizeInBytes - DRWAV_BEXT_BYTES;
  64342. drwav__metadata_request_extra_memory_for_stage_2(pParser, allocSizeNeeded, 1);
  64343. pParser->metadataCount += 1;
  64344. } else {
  64345. bytesRead = drwav__read_bext_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], pChunkHeader->sizeInBytes);
  64346. if (bytesRead == pChunkHeader->sizeInBytes) {
  64347. pParser->metadataCursor += 1;
  64348. } else {
  64349. }
  64350. }
  64351. } else {
  64352. }
  64353. } else if (drwav_fourcc_equal(pChunkID, "LIST") || drwav_fourcc_equal(pChunkID, "list")) {
  64354. drwav_metadata_location listType = drwav_metadata_location_invalid;
  64355. while (bytesRead < pChunkHeader->sizeInBytes) {
  64356. drwav_uint8 subchunkId[4];
  64357. drwav_uint8 subchunkSizeBuffer[4];
  64358. drwav_uint64 subchunkDataSize;
  64359. drwav_uint64 subchunkBytesRead = 0;
  64360. drwav_uint64 bytesJustRead = drwav__metadata_parser_read(pParser, subchunkId, sizeof(subchunkId), &bytesRead);
  64361. if (bytesJustRead != sizeof(subchunkId)) {
  64362. break;
  64363. }
  64364. if (drwav_fourcc_equal(subchunkId, "adtl")) {
  64365. listType = drwav_metadata_location_inside_adtl_list;
  64366. continue;
  64367. } else if (drwav_fourcc_equal(subchunkId, "INFO")) {
  64368. listType = drwav_metadata_location_inside_info_list;
  64369. continue;
  64370. }
  64371. bytesJustRead = drwav__metadata_parser_read(pParser, subchunkSizeBuffer, sizeof(subchunkSizeBuffer), &bytesRead);
  64372. if (bytesJustRead != sizeof(subchunkSizeBuffer)) {
  64373. break;
  64374. }
  64375. subchunkDataSize = drwav_bytes_to_u32(subchunkSizeBuffer);
  64376. if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_label, "labl") || drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_note, "note")) {
  64377. if (subchunkDataSize >= DRWAV_LIST_LABEL_OR_NOTE_BYTES) {
  64378. drwav_uint64 stringSizeWithNullTerm = subchunkDataSize - DRWAV_LIST_LABEL_OR_NOTE_BYTES;
  64379. if (pParser->stage == drwav__metadata_parser_stage_count) {
  64380. pParser->metadataCount += 1;
  64381. drwav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerm, 1);
  64382. } else {
  64383. subchunkBytesRead = drwav__read_list_label_or_note_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize, drwav_fourcc_equal(subchunkId, "labl") ? drwav_metadata_type_list_label : drwav_metadata_type_list_note);
  64384. if (subchunkBytesRead == subchunkDataSize) {
  64385. pParser->metadataCursor += 1;
  64386. } else {
  64387. }
  64388. }
  64389. } else {
  64390. }
  64391. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_labelled_cue_region, "ltxt")) {
  64392. if (subchunkDataSize >= DRWAV_LIST_LABELLED_TEXT_BYTES) {
  64393. drwav_uint64 stringSizeWithNullTerminator = subchunkDataSize - DRWAV_LIST_LABELLED_TEXT_BYTES;
  64394. if (pParser->stage == drwav__metadata_parser_stage_count) {
  64395. pParser->metadataCount += 1;
  64396. drwav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerminator, 1);
  64397. } else {
  64398. subchunkBytesRead = drwav__read_list_labelled_cue_region_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize);
  64399. if (subchunkBytesRead == subchunkDataSize) {
  64400. pParser->metadataCursor += 1;
  64401. } else {
  64402. }
  64403. }
  64404. } else {
  64405. }
  64406. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_software, "ISFT")) {
  64407. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_software);
  64408. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_copyright, "ICOP")) {
  64409. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_copyright);
  64410. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_title, "INAM")) {
  64411. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_title);
  64412. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_artist, "IART")) {
  64413. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_artist);
  64414. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_comment, "ICMT")) {
  64415. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_comment);
  64416. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_date, "ICRD")) {
  64417. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_date);
  64418. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_genre, "IGNR")) {
  64419. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_genre);
  64420. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_album, "IPRD")) {
  64421. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_album);
  64422. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_tracknumber, "ITRK")) {
  64423. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_tracknumber);
  64424. } else if ((allowedMetadataTypes & drwav_metadata_type_unknown) != 0) {
  64425. subchunkBytesRead = drwav__metadata_process_unknown_chunk(pParser, subchunkId, subchunkDataSize, listType);
  64426. }
  64427. bytesRead += subchunkBytesRead;
  64428. DRWAV_ASSERT(subchunkBytesRead <= subchunkDataSize);
  64429. if (subchunkBytesRead < subchunkDataSize) {
  64430. drwav_uint64 bytesToSeek = subchunkDataSize - subchunkBytesRead;
  64431. if (!pParser->onSeek(pParser->pReadSeekUserData, (int)bytesToSeek, drwav_seek_origin_current)) {
  64432. break;
  64433. }
  64434. bytesRead += bytesToSeek;
  64435. }
  64436. if ((subchunkDataSize % 2) == 1) {
  64437. if (!pParser->onSeek(pParser->pReadSeekUserData, 1, drwav_seek_origin_current)) {
  64438. break;
  64439. }
  64440. bytesRead += 1;
  64441. }
  64442. }
  64443. } else if ((allowedMetadataTypes & drwav_metadata_type_unknown) != 0) {
  64444. bytesRead = drwav__metadata_process_unknown_chunk(pParser, pChunkID, pChunkHeader->sizeInBytes, drwav_metadata_location_top_level);
  64445. }
  64446. return bytesRead;
  64447. }
  64448. DRWAV_PRIVATE drwav_uint32 drwav_get_bytes_per_pcm_frame(drwav* pWav)
  64449. {
  64450. drwav_uint32 bytesPerFrame;
  64451. if ((pWav->bitsPerSample & 0x7) == 0) {
  64452. bytesPerFrame = (pWav->bitsPerSample * pWav->fmt.channels) >> 3;
  64453. } else {
  64454. bytesPerFrame = pWav->fmt.blockAlign;
  64455. }
  64456. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW || pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  64457. if (bytesPerFrame != pWav->fmt.channels) {
  64458. return 0;
  64459. }
  64460. }
  64461. return bytesPerFrame;
  64462. }
  64463. DRWAV_API drwav_uint16 drwav_fmt_get_format(const drwav_fmt* pFMT)
  64464. {
  64465. if (pFMT == NULL) {
  64466. return 0;
  64467. }
  64468. if (pFMT->formatTag != DR_WAVE_FORMAT_EXTENSIBLE) {
  64469. return pFMT->formatTag;
  64470. } else {
  64471. return drwav_bytes_to_u16(pFMT->subFormat);
  64472. }
  64473. }
  64474. DRWAV_PRIVATE drwav_bool32 drwav_preinit(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pReadSeekUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  64475. {
  64476. if (pWav == NULL || onRead == NULL || onSeek == NULL) {
  64477. return DRWAV_FALSE;
  64478. }
  64479. DRWAV_ZERO_MEMORY(pWav, sizeof(*pWav));
  64480. pWav->onRead = onRead;
  64481. pWav->onSeek = onSeek;
  64482. pWav->pUserData = pReadSeekUserData;
  64483. pWav->allocationCallbacks = drwav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
  64484. if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) {
  64485. return DRWAV_FALSE;
  64486. }
  64487. return DRWAV_TRUE;
  64488. }
  64489. DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags)
  64490. {
  64491. drwav_uint64 cursor;
  64492. drwav_bool32 sequential;
  64493. drwav_uint8 riff[4];
  64494. drwav_fmt fmt;
  64495. unsigned short translatedFormatTag;
  64496. drwav_bool32 foundDataChunk;
  64497. drwav_uint64 dataChunkSize = 0;
  64498. drwav_uint64 sampleCountFromFactChunk = 0;
  64499. drwav_uint64 chunkSize;
  64500. drwav__metadata_parser metadataParser;
  64501. cursor = 0;
  64502. sequential = (flags & DRWAV_SEQUENTIAL) != 0;
  64503. if (drwav__on_read(pWav->onRead, pWav->pUserData, riff, sizeof(riff), &cursor) != sizeof(riff)) {
  64504. return DRWAV_FALSE;
  64505. }
  64506. if (drwav_fourcc_equal(riff, "RIFF")) {
  64507. pWav->container = drwav_container_riff;
  64508. } else if (drwav_fourcc_equal(riff, "riff")) {
  64509. int i;
  64510. drwav_uint8 riff2[12];
  64511. pWav->container = drwav_container_w64;
  64512. if (drwav__on_read(pWav->onRead, pWav->pUserData, riff2, sizeof(riff2), &cursor) != sizeof(riff2)) {
  64513. return DRWAV_FALSE;
  64514. }
  64515. for (i = 0; i < 12; ++i) {
  64516. if (riff2[i] != drwavGUID_W64_RIFF[i+4]) {
  64517. return DRWAV_FALSE;
  64518. }
  64519. }
  64520. } else if (drwav_fourcc_equal(riff, "RF64")) {
  64521. pWav->container = drwav_container_rf64;
  64522. } else {
  64523. return DRWAV_FALSE;
  64524. }
  64525. if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64) {
  64526. drwav_uint8 chunkSizeBytes[4];
  64527. drwav_uint8 wave[4];
  64528. if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
  64529. return DRWAV_FALSE;
  64530. }
  64531. if (pWav->container == drwav_container_riff) {
  64532. if (drwav_bytes_to_u32(chunkSizeBytes) < 36) {
  64533. return DRWAV_FALSE;
  64534. }
  64535. } else {
  64536. if (drwav_bytes_to_u32(chunkSizeBytes) != 0xFFFFFFFF) {
  64537. return DRWAV_FALSE;
  64538. }
  64539. }
  64540. if (drwav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
  64541. return DRWAV_FALSE;
  64542. }
  64543. if (!drwav_fourcc_equal(wave, "WAVE")) {
  64544. return DRWAV_FALSE;
  64545. }
  64546. } else {
  64547. drwav_uint8 chunkSizeBytes[8];
  64548. drwav_uint8 wave[16];
  64549. if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
  64550. return DRWAV_FALSE;
  64551. }
  64552. if (drwav_bytes_to_u64(chunkSizeBytes) < 80) {
  64553. return DRWAV_FALSE;
  64554. }
  64555. if (drwav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
  64556. return DRWAV_FALSE;
  64557. }
  64558. if (!drwav_guid_equal(wave, drwavGUID_W64_WAVE)) {
  64559. return DRWAV_FALSE;
  64560. }
  64561. }
  64562. if (pWav->container == drwav_container_rf64) {
  64563. drwav_uint8 sizeBytes[8];
  64564. drwav_uint64 bytesRemainingInChunk;
  64565. drwav_chunk_header header;
  64566. drwav_result result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
  64567. if (result != DRWAV_SUCCESS) {
  64568. return DRWAV_FALSE;
  64569. }
  64570. if (!drwav_fourcc_equal(header.id.fourcc, "ds64")) {
  64571. return DRWAV_FALSE;
  64572. }
  64573. bytesRemainingInChunk = header.sizeInBytes + header.paddingSize;
  64574. if (!drwav__seek_forward(pWav->onSeek, 8, pWav->pUserData)) {
  64575. return DRWAV_FALSE;
  64576. }
  64577. bytesRemainingInChunk -= 8;
  64578. cursor += 8;
  64579. if (drwav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) {
  64580. return DRWAV_FALSE;
  64581. }
  64582. bytesRemainingInChunk -= 8;
  64583. dataChunkSize = drwav_bytes_to_u64(sizeBytes);
  64584. if (drwav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) {
  64585. return DRWAV_FALSE;
  64586. }
  64587. bytesRemainingInChunk -= 8;
  64588. sampleCountFromFactChunk = drwav_bytes_to_u64(sizeBytes);
  64589. if (!drwav__seek_forward(pWav->onSeek, bytesRemainingInChunk, pWav->pUserData)) {
  64590. return DRWAV_FALSE;
  64591. }
  64592. cursor += bytesRemainingInChunk;
  64593. }
  64594. if (!drwav__read_fmt(pWav->onRead, pWav->onSeek, pWav->pUserData, pWav->container, &cursor, &fmt)) {
  64595. return DRWAV_FALSE;
  64596. }
  64597. if ((fmt.sampleRate == 0 || fmt.sampleRate > DRWAV_MAX_SAMPLE_RATE) ||
  64598. (fmt.channels == 0 || fmt.channels > DRWAV_MAX_CHANNELS) ||
  64599. (fmt.bitsPerSample == 0 || fmt.bitsPerSample > DRWAV_MAX_BITS_PER_SAMPLE) ||
  64600. fmt.blockAlign == 0) {
  64601. return DRWAV_FALSE;
  64602. }
  64603. translatedFormatTag = fmt.formatTag;
  64604. if (translatedFormatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
  64605. translatedFormatTag = drwav_bytes_to_u16(fmt.subFormat + 0);
  64606. }
  64607. DRWAV_ZERO_MEMORY(&metadataParser, sizeof(metadataParser));
  64608. if (!sequential && pWav->allowedMetadataTypes != drwav_metadata_type_none && (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64)) {
  64609. drwav_uint64 cursorForMetadata = cursor;
  64610. metadataParser.onRead = pWav->onRead;
  64611. metadataParser.onSeek = pWav->onSeek;
  64612. metadataParser.pReadSeekUserData = pWav->pUserData;
  64613. metadataParser.stage = drwav__metadata_parser_stage_count;
  64614. for (;;) {
  64615. drwav_result result;
  64616. drwav_uint64 bytesRead;
  64617. drwav_uint64 remainingBytes;
  64618. drwav_chunk_header header;
  64619. result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursorForMetadata, &header);
  64620. if (result != DRWAV_SUCCESS) {
  64621. break;
  64622. }
  64623. bytesRead = drwav__metadata_process_chunk(&metadataParser, &header, pWav->allowedMetadataTypes);
  64624. DRWAV_ASSERT(bytesRead <= header.sizeInBytes);
  64625. remainingBytes = header.sizeInBytes - bytesRead + header.paddingSize;
  64626. if (!drwav__seek_forward(pWav->onSeek, remainingBytes, pWav->pUserData)) {
  64627. break;
  64628. }
  64629. cursorForMetadata += remainingBytes;
  64630. }
  64631. if (!drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData)) {
  64632. return DRWAV_FALSE;
  64633. }
  64634. drwav__metadata_alloc(&metadataParser, &pWav->allocationCallbacks);
  64635. metadataParser.stage = drwav__metadata_parser_stage_read;
  64636. }
  64637. foundDataChunk = DRWAV_FALSE;
  64638. for (;;) {
  64639. drwav_chunk_header header;
  64640. drwav_result result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
  64641. if (result != DRWAV_SUCCESS) {
  64642. if (!foundDataChunk) {
  64643. return DRWAV_FALSE;
  64644. } else {
  64645. break;
  64646. }
  64647. }
  64648. if (!sequential && onChunk != NULL) {
  64649. drwav_uint64 callbackBytesRead = onChunk(pChunkUserData, pWav->onRead, pWav->onSeek, pWav->pUserData, &header, pWav->container, &fmt);
  64650. if (callbackBytesRead > 0) {
  64651. if (!drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData)) {
  64652. return DRWAV_FALSE;
  64653. }
  64654. }
  64655. }
  64656. if (!sequential && pWav->allowedMetadataTypes != drwav_metadata_type_none && (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64)) {
  64657. drwav_uint64 bytesRead = drwav__metadata_process_chunk(&metadataParser, &header, pWav->allowedMetadataTypes);
  64658. if (bytesRead > 0) {
  64659. if (!drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData)) {
  64660. return DRWAV_FALSE;
  64661. }
  64662. }
  64663. }
  64664. if (!foundDataChunk) {
  64665. pWav->dataChunkDataPos = cursor;
  64666. }
  64667. chunkSize = header.sizeInBytes;
  64668. if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64) {
  64669. if (drwav_fourcc_equal(header.id.fourcc, "data")) {
  64670. foundDataChunk = DRWAV_TRUE;
  64671. if (pWav->container != drwav_container_rf64) {
  64672. dataChunkSize = chunkSize;
  64673. }
  64674. }
  64675. } else {
  64676. if (drwav_guid_equal(header.id.guid, drwavGUID_W64_DATA)) {
  64677. foundDataChunk = DRWAV_TRUE;
  64678. dataChunkSize = chunkSize;
  64679. }
  64680. }
  64681. if (foundDataChunk && sequential) {
  64682. break;
  64683. }
  64684. if (pWav->container == drwav_container_riff) {
  64685. if (drwav_fourcc_equal(header.id.fourcc, "fact")) {
  64686. drwav_uint32 sampleCount;
  64687. if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCount, 4, &cursor) != 4) {
  64688. return DRWAV_FALSE;
  64689. }
  64690. chunkSize -= 4;
  64691. if (!foundDataChunk) {
  64692. pWav->dataChunkDataPos = cursor;
  64693. }
  64694. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  64695. sampleCountFromFactChunk = sampleCount;
  64696. } else {
  64697. sampleCountFromFactChunk = 0;
  64698. }
  64699. }
  64700. } else if (pWav->container == drwav_container_w64) {
  64701. if (drwav_guid_equal(header.id.guid, drwavGUID_W64_FACT)) {
  64702. if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCountFromFactChunk, 8, &cursor) != 8) {
  64703. return DRWAV_FALSE;
  64704. }
  64705. chunkSize -= 8;
  64706. if (!foundDataChunk) {
  64707. pWav->dataChunkDataPos = cursor;
  64708. }
  64709. }
  64710. } else if (pWav->container == drwav_container_rf64) {
  64711. }
  64712. chunkSize += header.paddingSize;
  64713. if (!drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData)) {
  64714. break;
  64715. }
  64716. cursor += chunkSize;
  64717. if (!foundDataChunk) {
  64718. pWav->dataChunkDataPos = cursor;
  64719. }
  64720. }
  64721. pWav->pMetadata = metadataParser.pMetadata;
  64722. pWav->metadataCount = metadataParser.metadataCount;
  64723. if (!foundDataChunk) {
  64724. return DRWAV_FALSE;
  64725. }
  64726. if (!sequential) {
  64727. if (!drwav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData)) {
  64728. return DRWAV_FALSE;
  64729. }
  64730. cursor = pWav->dataChunkDataPos;
  64731. }
  64732. pWav->fmt = fmt;
  64733. pWav->sampleRate = fmt.sampleRate;
  64734. pWav->channels = fmt.channels;
  64735. pWav->bitsPerSample = fmt.bitsPerSample;
  64736. pWav->bytesRemaining = dataChunkSize;
  64737. pWav->translatedFormatTag = translatedFormatTag;
  64738. pWav->dataChunkDataSize = dataChunkSize;
  64739. if (sampleCountFromFactChunk != 0) {
  64740. pWav->totalPCMFrameCount = sampleCountFromFactChunk;
  64741. } else {
  64742. drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  64743. if (bytesPerFrame == 0) {
  64744. return DRWAV_FALSE;
  64745. }
  64746. pWav->totalPCMFrameCount = dataChunkSize / bytesPerFrame;
  64747. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  64748. drwav_uint64 totalBlockHeaderSizeInBytes;
  64749. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  64750. if ((blockCount * fmt.blockAlign) < dataChunkSize) {
  64751. blockCount += 1;
  64752. }
  64753. totalBlockHeaderSizeInBytes = blockCount * (6*fmt.channels);
  64754. pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
  64755. }
  64756. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  64757. drwav_uint64 totalBlockHeaderSizeInBytes;
  64758. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  64759. if ((blockCount * fmt.blockAlign) < dataChunkSize) {
  64760. blockCount += 1;
  64761. }
  64762. totalBlockHeaderSizeInBytes = blockCount * (4*fmt.channels);
  64763. pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
  64764. pWav->totalPCMFrameCount += blockCount;
  64765. }
  64766. }
  64767. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  64768. if (pWav->channels > 2) {
  64769. return DRWAV_FALSE;
  64770. }
  64771. }
  64772. if (drwav_get_bytes_per_pcm_frame(pWav) == 0) {
  64773. return DRWAV_FALSE;
  64774. }
  64775. #ifdef DR_WAV_LIBSNDFILE_COMPAT
  64776. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  64777. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  64778. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels;
  64779. }
  64780. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  64781. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  64782. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels;
  64783. }
  64784. #endif
  64785. return DRWAV_TRUE;
  64786. }
  64787. DRWAV_API drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  64788. {
  64789. return drwav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0, pAllocationCallbacks);
  64790. }
  64791. DRWAV_API drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  64792. {
  64793. if (!drwav_preinit(pWav, onRead, onSeek, pReadSeekUserData, pAllocationCallbacks)) {
  64794. return DRWAV_FALSE;
  64795. }
  64796. return drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
  64797. }
  64798. DRWAV_API drwav_bool32 drwav_init_with_metadata(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  64799. {
  64800. if (!drwav_preinit(pWav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  64801. return DRWAV_FALSE;
  64802. }
  64803. pWav->allowedMetadataTypes = drwav_metadata_type_all_including_unknown;
  64804. return drwav_init__internal(pWav, NULL, NULL, flags);
  64805. }
  64806. DRWAV_API drwav_metadata* drwav_take_ownership_of_metadata(drwav* pWav)
  64807. {
  64808. drwav_metadata *result = pWav->pMetadata;
  64809. pWav->pMetadata = NULL;
  64810. pWav->metadataCount = 0;
  64811. return result;
  64812. }
  64813. DRWAV_PRIVATE size_t drwav__write(drwav* pWav, const void* pData, size_t dataSize)
  64814. {
  64815. DRWAV_ASSERT(pWav != NULL);
  64816. DRWAV_ASSERT(pWav->onWrite != NULL);
  64817. return pWav->onWrite(pWav->pUserData, pData, dataSize);
  64818. }
  64819. DRWAV_PRIVATE size_t drwav__write_byte(drwav* pWav, drwav_uint8 byte)
  64820. {
  64821. DRWAV_ASSERT(pWav != NULL);
  64822. DRWAV_ASSERT(pWav->onWrite != NULL);
  64823. return pWav->onWrite(pWav->pUserData, &byte, 1);
  64824. }
  64825. DRWAV_PRIVATE size_t drwav__write_u16ne_to_le(drwav* pWav, drwav_uint16 value)
  64826. {
  64827. DRWAV_ASSERT(pWav != NULL);
  64828. DRWAV_ASSERT(pWav->onWrite != NULL);
  64829. if (!drwav__is_little_endian()) {
  64830. value = drwav__bswap16(value);
  64831. }
  64832. return drwav__write(pWav, &value, 2);
  64833. }
  64834. DRWAV_PRIVATE size_t drwav__write_u32ne_to_le(drwav* pWav, drwav_uint32 value)
  64835. {
  64836. DRWAV_ASSERT(pWav != NULL);
  64837. DRWAV_ASSERT(pWav->onWrite != NULL);
  64838. if (!drwav__is_little_endian()) {
  64839. value = drwav__bswap32(value);
  64840. }
  64841. return drwav__write(pWav, &value, 4);
  64842. }
  64843. DRWAV_PRIVATE size_t drwav__write_u64ne_to_le(drwav* pWav, drwav_uint64 value)
  64844. {
  64845. DRWAV_ASSERT(pWav != NULL);
  64846. DRWAV_ASSERT(pWav->onWrite != NULL);
  64847. if (!drwav__is_little_endian()) {
  64848. value = drwav__bswap64(value);
  64849. }
  64850. return drwav__write(pWav, &value, 8);
  64851. }
  64852. DRWAV_PRIVATE size_t drwav__write_f32ne_to_le(drwav* pWav, float value)
  64853. {
  64854. union {
  64855. drwav_uint32 u32;
  64856. float f32;
  64857. } u;
  64858. DRWAV_ASSERT(pWav != NULL);
  64859. DRWAV_ASSERT(pWav->onWrite != NULL);
  64860. u.f32 = value;
  64861. if (!drwav__is_little_endian()) {
  64862. u.u32 = drwav__bswap32(u.u32);
  64863. }
  64864. return drwav__write(pWav, &u.u32, 4);
  64865. }
  64866. DRWAV_PRIVATE size_t drwav__write_or_count(drwav* pWav, const void* pData, size_t dataSize)
  64867. {
  64868. if (pWav == NULL) {
  64869. return dataSize;
  64870. }
  64871. return drwav__write(pWav, pData, dataSize);
  64872. }
  64873. DRWAV_PRIVATE size_t drwav__write_or_count_byte(drwav* pWav, drwav_uint8 byte)
  64874. {
  64875. if (pWav == NULL) {
  64876. return 1;
  64877. }
  64878. return drwav__write_byte(pWav, byte);
  64879. }
  64880. DRWAV_PRIVATE size_t drwav__write_or_count_u16ne_to_le(drwav* pWav, drwav_uint16 value)
  64881. {
  64882. if (pWav == NULL) {
  64883. return 2;
  64884. }
  64885. return drwav__write_u16ne_to_le(pWav, value);
  64886. }
  64887. DRWAV_PRIVATE size_t drwav__write_or_count_u32ne_to_le(drwav* pWav, drwav_uint32 value)
  64888. {
  64889. if (pWav == NULL) {
  64890. return 4;
  64891. }
  64892. return drwav__write_u32ne_to_le(pWav, value);
  64893. }
  64894. #if 0
  64895. DRWAV_PRIVATE size_t drwav__write_or_count_u64ne_to_le(drwav* pWav, drwav_uint64 value)
  64896. {
  64897. if (pWav == NULL) {
  64898. return 8;
  64899. }
  64900. return drwav__write_u64ne_to_le(pWav, value);
  64901. }
  64902. #endif
  64903. DRWAV_PRIVATE size_t drwav__write_or_count_f32ne_to_le(drwav* pWav, float value)
  64904. {
  64905. if (pWav == NULL) {
  64906. return 4;
  64907. }
  64908. return drwav__write_f32ne_to_le(pWav, value);
  64909. }
  64910. DRWAV_PRIVATE size_t drwav__write_or_count_string_to_fixed_size_buf(drwav* pWav, char* str, size_t bufFixedSize)
  64911. {
  64912. size_t len;
  64913. if (pWav == NULL) {
  64914. return bufFixedSize;
  64915. }
  64916. len = drwav__strlen_clamped(str, bufFixedSize);
  64917. drwav__write_or_count(pWav, str, len);
  64918. if (len < bufFixedSize) {
  64919. size_t i;
  64920. for (i = 0; i < bufFixedSize - len; ++i) {
  64921. drwav__write_byte(pWav, 0);
  64922. }
  64923. }
  64924. return bufFixedSize;
  64925. }
  64926. DRWAV_PRIVATE size_t drwav__write_or_count_metadata(drwav* pWav, drwav_metadata* pMetadatas, drwav_uint32 metadataCount)
  64927. {
  64928. size_t bytesWritten = 0;
  64929. drwav_bool32 hasListAdtl = DRWAV_FALSE;
  64930. drwav_bool32 hasListInfo = DRWAV_FALSE;
  64931. drwav_uint32 iMetadata;
  64932. if (pMetadatas == NULL || metadataCount == 0) {
  64933. return 0;
  64934. }
  64935. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  64936. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  64937. drwav_uint32 chunkSize = 0;
  64938. if ((pMetadata->type & drwav_metadata_type_list_all_info_strings) || (pMetadata->type == drwav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_info_list)) {
  64939. hasListInfo = DRWAV_TRUE;
  64940. }
  64941. if ((pMetadata->type & drwav_metadata_type_list_all_adtl) || (pMetadata->type == drwav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_adtl_list)) {
  64942. hasListAdtl = DRWAV_TRUE;
  64943. }
  64944. switch (pMetadata->type) {
  64945. case drwav_metadata_type_smpl:
  64946. {
  64947. drwav_uint32 iLoop;
  64948. chunkSize = DRWAV_SMPL_BYTES + DRWAV_SMPL_LOOP_BYTES * pMetadata->data.smpl.sampleLoopCount + pMetadata->data.smpl.samplerSpecificDataSizeInBytes;
  64949. bytesWritten += drwav__write_or_count(pWav, "smpl", 4);
  64950. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  64951. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.manufacturerId);
  64952. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.productId);
  64953. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplePeriodNanoseconds);
  64954. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiUnityNote);
  64955. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiPitchFraction);
  64956. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteFormat);
  64957. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteOffset);
  64958. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.sampleLoopCount);
  64959. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplerSpecificDataSizeInBytes);
  64960. for (iLoop = 0; iLoop < pMetadata->data.smpl.sampleLoopCount; ++iLoop) {
  64961. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].cuePointId);
  64962. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].type);
  64963. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].firstSampleByteOffset);
  64964. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].lastSampleByteOffset);
  64965. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].sampleFraction);
  64966. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].playCount);
  64967. }
  64968. if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) {
  64969. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes);
  64970. }
  64971. } break;
  64972. case drwav_metadata_type_inst:
  64973. {
  64974. chunkSize = DRWAV_INST_BYTES;
  64975. bytesWritten += drwav__write_or_count(pWav, "inst", 4);
  64976. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  64977. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.midiUnityNote, 1);
  64978. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.fineTuneCents, 1);
  64979. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.gainDecibels, 1);
  64980. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.lowNote, 1);
  64981. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.highNote, 1);
  64982. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.lowVelocity, 1);
  64983. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.highVelocity, 1);
  64984. } break;
  64985. case drwav_metadata_type_cue:
  64986. {
  64987. drwav_uint32 iCuePoint;
  64988. chunkSize = DRWAV_CUE_BYTES + DRWAV_CUE_POINT_BYTES * pMetadata->data.cue.cuePointCount;
  64989. bytesWritten += drwav__write_or_count(pWav, "cue ", 4);
  64990. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  64991. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.cuePointCount);
  64992. for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) {
  64993. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].id);
  64994. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition);
  64995. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId, 4);
  64996. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart);
  64997. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].blockStart);
  64998. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset);
  64999. }
  65000. } break;
  65001. case drwav_metadata_type_acid:
  65002. {
  65003. chunkSize = DRWAV_ACID_BYTES;
  65004. bytesWritten += drwav__write_or_count(pWav, "acid", 4);
  65005. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65006. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.flags);
  65007. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.midiUnityNote);
  65008. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.reserved1);
  65009. bytesWritten += drwav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.reserved2);
  65010. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.numBeats);
  65011. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterDenominator);
  65012. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterNumerator);
  65013. bytesWritten += drwav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.tempo);
  65014. } break;
  65015. case drwav_metadata_type_bext:
  65016. {
  65017. char reservedBuf[DRWAV_BEXT_RESERVED_BYTES];
  65018. drwav_uint32 timeReferenceLow;
  65019. drwav_uint32 timeReferenceHigh;
  65020. chunkSize = DRWAV_BEXT_BYTES + pMetadata->data.bext.codingHistorySize;
  65021. bytesWritten += drwav__write_or_count(pWav, "bext", 4);
  65022. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65023. bytesWritten += drwav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pDescription, DRWAV_BEXT_DESCRIPTION_BYTES);
  65024. bytesWritten += drwav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorName, DRWAV_BEXT_ORIGINATOR_NAME_BYTES);
  65025. bytesWritten += drwav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorReference, DRWAV_BEXT_ORIGINATOR_REF_BYTES);
  65026. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate));
  65027. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime));
  65028. timeReferenceLow = (drwav_uint32)(pMetadata->data.bext.timeReference & 0xFFFFFFFF);
  65029. timeReferenceHigh = (drwav_uint32)(pMetadata->data.bext.timeReference >> 32);
  65030. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, timeReferenceLow);
  65031. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, timeReferenceHigh);
  65032. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.version);
  65033. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pUMID, DRWAV_BEXT_UMID_BYTES);
  65034. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessValue);
  65035. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessRange);
  65036. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxTruePeakLevel);
  65037. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxMomentaryLoudness);
  65038. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxShortTermLoudness);
  65039. DRWAV_ZERO_MEMORY(reservedBuf, sizeof(reservedBuf));
  65040. bytesWritten += drwav__write_or_count(pWav, reservedBuf, sizeof(reservedBuf));
  65041. if (pMetadata->data.bext.codingHistorySize > 0) {
  65042. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pCodingHistory, pMetadata->data.bext.codingHistorySize);
  65043. }
  65044. } break;
  65045. case drwav_metadata_type_unknown:
  65046. {
  65047. if (pMetadata->data.unknown.chunkLocation == drwav_metadata_location_top_level) {
  65048. chunkSize = pMetadata->data.unknown.dataSizeInBytes;
  65049. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
  65050. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65051. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes);
  65052. }
  65053. } break;
  65054. default: break;
  65055. }
  65056. if ((chunkSize % 2) != 0) {
  65057. bytesWritten += drwav__write_or_count_byte(pWav, 0);
  65058. }
  65059. }
  65060. if (hasListInfo) {
  65061. drwav_uint32 chunkSize = 4;
  65062. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  65063. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  65064. if ((pMetadata->type & drwav_metadata_type_list_all_info_strings)) {
  65065. chunkSize += 8;
  65066. chunkSize += pMetadata->data.infoText.stringLength + 1;
  65067. } else if (pMetadata->type == drwav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_info_list) {
  65068. chunkSize += 8;
  65069. chunkSize += pMetadata->data.unknown.dataSizeInBytes;
  65070. }
  65071. if ((chunkSize % 2) != 0) {
  65072. chunkSize += 1;
  65073. }
  65074. }
  65075. bytesWritten += drwav__write_or_count(pWav, "LIST", 4);
  65076. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65077. bytesWritten += drwav__write_or_count(pWav, "INFO", 4);
  65078. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  65079. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  65080. drwav_uint32 subchunkSize = 0;
  65081. if (pMetadata->type & drwav_metadata_type_list_all_info_strings) {
  65082. const char* pID = NULL;
  65083. switch (pMetadata->type) {
  65084. case drwav_metadata_type_list_info_software: pID = "ISFT"; break;
  65085. case drwav_metadata_type_list_info_copyright: pID = "ICOP"; break;
  65086. case drwav_metadata_type_list_info_title: pID = "INAM"; break;
  65087. case drwav_metadata_type_list_info_artist: pID = "IART"; break;
  65088. case drwav_metadata_type_list_info_comment: pID = "ICMT"; break;
  65089. case drwav_metadata_type_list_info_date: pID = "ICRD"; break;
  65090. case drwav_metadata_type_list_info_genre: pID = "IGNR"; break;
  65091. case drwav_metadata_type_list_info_album: pID = "IPRD"; break;
  65092. case drwav_metadata_type_list_info_tracknumber: pID = "ITRK"; break;
  65093. default: break;
  65094. }
  65095. DRWAV_ASSERT(pID != NULL);
  65096. if (pMetadata->data.infoText.stringLength) {
  65097. subchunkSize = pMetadata->data.infoText.stringLength + 1;
  65098. bytesWritten += drwav__write_or_count(pWav, pID, 4);
  65099. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  65100. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.infoText.pString, pMetadata->data.infoText.stringLength);
  65101. bytesWritten += drwav__write_or_count_byte(pWav, '\0');
  65102. }
  65103. } else if (pMetadata->type == drwav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_info_list) {
  65104. if (pMetadata->data.unknown.dataSizeInBytes) {
  65105. subchunkSize = pMetadata->data.unknown.dataSizeInBytes;
  65106. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
  65107. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.unknown.dataSizeInBytes);
  65108. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize);
  65109. }
  65110. }
  65111. if ((subchunkSize % 2) != 0) {
  65112. bytesWritten += drwav__write_or_count_byte(pWav, 0);
  65113. }
  65114. }
  65115. }
  65116. if (hasListAdtl) {
  65117. drwav_uint32 chunkSize = 4;
  65118. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  65119. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  65120. switch (pMetadata->type)
  65121. {
  65122. case drwav_metadata_type_list_label:
  65123. case drwav_metadata_type_list_note:
  65124. {
  65125. chunkSize += 8;
  65126. chunkSize += DRWAV_LIST_LABEL_OR_NOTE_BYTES;
  65127. if (pMetadata->data.labelOrNote.stringLength > 0) {
  65128. chunkSize += pMetadata->data.labelOrNote.stringLength + 1;
  65129. }
  65130. } break;
  65131. case drwav_metadata_type_list_labelled_cue_region:
  65132. {
  65133. chunkSize += 8;
  65134. chunkSize += DRWAV_LIST_LABELLED_TEXT_BYTES;
  65135. if (pMetadata->data.labelledCueRegion.stringLength > 0) {
  65136. chunkSize += pMetadata->data.labelledCueRegion.stringLength + 1;
  65137. }
  65138. } break;
  65139. case drwav_metadata_type_unknown:
  65140. {
  65141. if (pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_adtl_list) {
  65142. chunkSize += 8;
  65143. chunkSize += pMetadata->data.unknown.dataSizeInBytes;
  65144. }
  65145. } break;
  65146. default: break;
  65147. }
  65148. if ((chunkSize % 2) != 0) {
  65149. chunkSize += 1;
  65150. }
  65151. }
  65152. bytesWritten += drwav__write_or_count(pWav, "LIST", 4);
  65153. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65154. bytesWritten += drwav__write_or_count(pWav, "adtl", 4);
  65155. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  65156. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  65157. drwav_uint32 subchunkSize = 0;
  65158. switch (pMetadata->type)
  65159. {
  65160. case drwav_metadata_type_list_label:
  65161. case drwav_metadata_type_list_note:
  65162. {
  65163. if (pMetadata->data.labelOrNote.stringLength > 0) {
  65164. const char *pID = NULL;
  65165. if (pMetadata->type == drwav_metadata_type_list_label) {
  65166. pID = "labl";
  65167. }
  65168. else if (pMetadata->type == drwav_metadata_type_list_note) {
  65169. pID = "note";
  65170. }
  65171. DRWAV_ASSERT(pID != NULL);
  65172. DRWAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL);
  65173. subchunkSize = DRWAV_LIST_LABEL_OR_NOTE_BYTES;
  65174. bytesWritten += drwav__write_or_count(pWav, pID, 4);
  65175. subchunkSize += pMetadata->data.labelOrNote.stringLength + 1;
  65176. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  65177. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelOrNote.cuePointId);
  65178. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.labelOrNote.pString, pMetadata->data.labelOrNote.stringLength);
  65179. bytesWritten += drwav__write_or_count_byte(pWav, '\0');
  65180. }
  65181. } break;
  65182. case drwav_metadata_type_list_labelled_cue_region:
  65183. {
  65184. subchunkSize = DRWAV_LIST_LABELLED_TEXT_BYTES;
  65185. bytesWritten += drwav__write_or_count(pWav, "ltxt", 4);
  65186. if (pMetadata->data.labelledCueRegion.stringLength > 0) {
  65187. subchunkSize += pMetadata->data.labelledCueRegion.stringLength + 1;
  65188. }
  65189. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  65190. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.cuePointId);
  65191. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.sampleLength);
  65192. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.labelledCueRegion.purposeId, 4);
  65193. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.country);
  65194. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.language);
  65195. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.dialect);
  65196. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.codePage);
  65197. if (pMetadata->data.labelledCueRegion.stringLength > 0) {
  65198. DRWAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL);
  65199. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.labelledCueRegion.pString, pMetadata->data.labelledCueRegion.stringLength);
  65200. bytesWritten += drwav__write_or_count_byte(pWav, '\0');
  65201. }
  65202. } break;
  65203. case drwav_metadata_type_unknown:
  65204. {
  65205. if (pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_adtl_list) {
  65206. subchunkSize = pMetadata->data.unknown.dataSizeInBytes;
  65207. DRWAV_ASSERT(pMetadata->data.unknown.pData != NULL);
  65208. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
  65209. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  65210. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize);
  65211. }
  65212. } break;
  65213. default: break;
  65214. }
  65215. if ((subchunkSize % 2) != 0) {
  65216. bytesWritten += drwav__write_or_count_byte(pWav, 0);
  65217. }
  65218. }
  65219. }
  65220. DRWAV_ASSERT((bytesWritten % 2) == 0);
  65221. return bytesWritten;
  65222. }
  65223. DRWAV_PRIVATE drwav_uint32 drwav__riff_chunk_size_riff(drwav_uint64 dataChunkSize, drwav_metadata* pMetadata, drwav_uint32 metadataCount)
  65224. {
  65225. drwav_uint64 chunkSize = 4 + 24 + (drwav_uint64)drwav__write_or_count_metadata(NULL, pMetadata, metadataCount) + 8 + dataChunkSize + drwav__chunk_padding_size_riff(dataChunkSize);
  65226. if (chunkSize > 0xFFFFFFFFUL) {
  65227. chunkSize = 0xFFFFFFFFUL;
  65228. }
  65229. return (drwav_uint32)chunkSize;
  65230. }
  65231. DRWAV_PRIVATE drwav_uint32 drwav__data_chunk_size_riff(drwav_uint64 dataChunkSize)
  65232. {
  65233. if (dataChunkSize <= 0xFFFFFFFFUL) {
  65234. return (drwav_uint32)dataChunkSize;
  65235. } else {
  65236. return 0xFFFFFFFFUL;
  65237. }
  65238. }
  65239. DRWAV_PRIVATE drwav_uint64 drwav__riff_chunk_size_w64(drwav_uint64 dataChunkSize)
  65240. {
  65241. drwav_uint64 dataSubchunkPaddingSize = drwav__chunk_padding_size_w64(dataChunkSize);
  65242. return 80 + 24 + dataChunkSize + dataSubchunkPaddingSize;
  65243. }
  65244. DRWAV_PRIVATE drwav_uint64 drwav__data_chunk_size_w64(drwav_uint64 dataChunkSize)
  65245. {
  65246. return 24 + dataChunkSize;
  65247. }
  65248. DRWAV_PRIVATE drwav_uint64 drwav__riff_chunk_size_rf64(drwav_uint64 dataChunkSize, drwav_metadata *metadata, drwav_uint32 numMetadata)
  65249. {
  65250. drwav_uint64 chunkSize = 4 + 36 + 24 + (drwav_uint64)drwav__write_or_count_metadata(NULL, metadata, numMetadata) + 8 + dataChunkSize + drwav__chunk_padding_size_riff(dataChunkSize);
  65251. if (chunkSize > 0xFFFFFFFFUL) {
  65252. chunkSize = 0xFFFFFFFFUL;
  65253. }
  65254. return chunkSize;
  65255. }
  65256. DRWAV_PRIVATE drwav_uint64 drwav__data_chunk_size_rf64(drwav_uint64 dataChunkSize)
  65257. {
  65258. return dataChunkSize;
  65259. }
  65260. DRWAV_PRIVATE drwav_bool32 drwav_preinit_write(drwav* pWav, const drwav_data_format* pFormat, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  65261. {
  65262. if (pWav == NULL || onWrite == NULL) {
  65263. return DRWAV_FALSE;
  65264. }
  65265. if (!isSequential && onSeek == NULL) {
  65266. return DRWAV_FALSE;
  65267. }
  65268. if (pFormat->format == DR_WAVE_FORMAT_EXTENSIBLE) {
  65269. return DRWAV_FALSE;
  65270. }
  65271. if (pFormat->format == DR_WAVE_FORMAT_ADPCM || pFormat->format == DR_WAVE_FORMAT_DVI_ADPCM) {
  65272. return DRWAV_FALSE;
  65273. }
  65274. DRWAV_ZERO_MEMORY(pWav, sizeof(*pWav));
  65275. pWav->onWrite = onWrite;
  65276. pWav->onSeek = onSeek;
  65277. pWav->pUserData = pUserData;
  65278. pWav->allocationCallbacks = drwav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
  65279. if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) {
  65280. return DRWAV_FALSE;
  65281. }
  65282. pWav->fmt.formatTag = (drwav_uint16)pFormat->format;
  65283. pWav->fmt.channels = (drwav_uint16)pFormat->channels;
  65284. pWav->fmt.sampleRate = pFormat->sampleRate;
  65285. pWav->fmt.avgBytesPerSec = (drwav_uint32)((pFormat->bitsPerSample * pFormat->sampleRate * pFormat->channels) / 8);
  65286. pWav->fmt.blockAlign = (drwav_uint16)((pFormat->channels * pFormat->bitsPerSample) / 8);
  65287. pWav->fmt.bitsPerSample = (drwav_uint16)pFormat->bitsPerSample;
  65288. pWav->fmt.extendedSize = 0;
  65289. pWav->isSequentialWrite = isSequential;
  65290. return DRWAV_TRUE;
  65291. }
  65292. DRWAV_PRIVATE drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount)
  65293. {
  65294. size_t runningPos = 0;
  65295. drwav_uint64 initialDataChunkSize = 0;
  65296. drwav_uint64 chunkSizeFMT;
  65297. if (pWav->isSequentialWrite) {
  65298. initialDataChunkSize = (totalSampleCount * pWav->fmt.bitsPerSample) / 8;
  65299. if (pFormat->container == drwav_container_riff) {
  65300. if (initialDataChunkSize > (0xFFFFFFFFUL - 36)) {
  65301. return DRWAV_FALSE;
  65302. }
  65303. }
  65304. }
  65305. pWav->dataChunkDataSizeTargetWrite = initialDataChunkSize;
  65306. if (pFormat->container == drwav_container_riff) {
  65307. drwav_uint32 chunkSizeRIFF = 28 + (drwav_uint32)initialDataChunkSize;
  65308. runningPos += drwav__write(pWav, "RIFF", 4);
  65309. runningPos += drwav__write_u32ne_to_le(pWav, chunkSizeRIFF);
  65310. runningPos += drwav__write(pWav, "WAVE", 4);
  65311. } else if (pFormat->container == drwav_container_w64) {
  65312. drwav_uint64 chunkSizeRIFF = 80 + 24 + initialDataChunkSize;
  65313. runningPos += drwav__write(pWav, drwavGUID_W64_RIFF, 16);
  65314. runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeRIFF);
  65315. runningPos += drwav__write(pWav, drwavGUID_W64_WAVE, 16);
  65316. } else if (pFormat->container == drwav_container_rf64) {
  65317. runningPos += drwav__write(pWav, "RF64", 4);
  65318. runningPos += drwav__write_u32ne_to_le(pWav, 0xFFFFFFFF);
  65319. runningPos += drwav__write(pWav, "WAVE", 4);
  65320. }
  65321. if (pFormat->container == drwav_container_rf64) {
  65322. drwav_uint32 initialds64ChunkSize = 28;
  65323. drwav_uint64 initialRiffChunkSize = 8 + initialds64ChunkSize + initialDataChunkSize;
  65324. runningPos += drwav__write(pWav, "ds64", 4);
  65325. runningPos += drwav__write_u32ne_to_le(pWav, initialds64ChunkSize);
  65326. runningPos += drwav__write_u64ne_to_le(pWav, initialRiffChunkSize);
  65327. runningPos += drwav__write_u64ne_to_le(pWav, initialDataChunkSize);
  65328. runningPos += drwav__write_u64ne_to_le(pWav, totalSampleCount);
  65329. runningPos += drwav__write_u32ne_to_le(pWav, 0);
  65330. }
  65331. if (pFormat->container == drwav_container_riff || pFormat->container == drwav_container_rf64) {
  65332. chunkSizeFMT = 16;
  65333. runningPos += drwav__write(pWav, "fmt ", 4);
  65334. runningPos += drwav__write_u32ne_to_le(pWav, (drwav_uint32)chunkSizeFMT);
  65335. } else if (pFormat->container == drwav_container_w64) {
  65336. chunkSizeFMT = 40;
  65337. runningPos += drwav__write(pWav, drwavGUID_W64_FMT, 16);
  65338. runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeFMT);
  65339. }
  65340. runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.formatTag);
  65341. runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.channels);
  65342. runningPos += drwav__write_u32ne_to_le(pWav, pWav->fmt.sampleRate);
  65343. runningPos += drwav__write_u32ne_to_le(pWav, pWav->fmt.avgBytesPerSec);
  65344. runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.blockAlign);
  65345. runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.bitsPerSample);
  65346. if (!pWav->isSequentialWrite && pWav->pMetadata != NULL && pWav->metadataCount > 0 && (pFormat->container == drwav_container_riff || pFormat->container == drwav_container_rf64)) {
  65347. runningPos += drwav__write_or_count_metadata(pWav, pWav->pMetadata, pWav->metadataCount);
  65348. }
  65349. pWav->dataChunkDataPos = runningPos;
  65350. if (pFormat->container == drwav_container_riff) {
  65351. drwav_uint32 chunkSizeDATA = (drwav_uint32)initialDataChunkSize;
  65352. runningPos += drwav__write(pWav, "data", 4);
  65353. runningPos += drwav__write_u32ne_to_le(pWav, chunkSizeDATA);
  65354. } else if (pFormat->container == drwav_container_w64) {
  65355. drwav_uint64 chunkSizeDATA = 24 + initialDataChunkSize;
  65356. runningPos += drwav__write(pWav, drwavGUID_W64_DATA, 16);
  65357. runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeDATA);
  65358. } else if (pFormat->container == drwav_container_rf64) {
  65359. runningPos += drwav__write(pWav, "data", 4);
  65360. runningPos += drwav__write_u32ne_to_le(pWav, 0xFFFFFFFF);
  65361. }
  65362. pWav->container = pFormat->container;
  65363. pWav->channels = (drwav_uint16)pFormat->channels;
  65364. pWav->sampleRate = pFormat->sampleRate;
  65365. pWav->bitsPerSample = (drwav_uint16)pFormat->bitsPerSample;
  65366. pWav->translatedFormatTag = (drwav_uint16)pFormat->format;
  65367. pWav->dataChunkDataPos = runningPos;
  65368. return DRWAV_TRUE;
  65369. }
  65370. DRWAV_API drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  65371. {
  65372. if (!drwav_preinit_write(pWav, pFormat, DRWAV_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) {
  65373. return DRWAV_FALSE;
  65374. }
  65375. return drwav_init_write__internal(pWav, pFormat, 0);
  65376. }
  65377. DRWAV_API drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  65378. {
  65379. if (!drwav_preinit_write(pWav, pFormat, DRWAV_TRUE, onWrite, NULL, pUserData, pAllocationCallbacks)) {
  65380. return DRWAV_FALSE;
  65381. }
  65382. return drwav_init_write__internal(pWav, pFormat, totalSampleCount);
  65383. }
  65384. DRWAV_API drwav_bool32 drwav_init_write_sequential_pcm_frames(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  65385. {
  65386. if (pFormat == NULL) {
  65387. return DRWAV_FALSE;
  65388. }
  65389. return drwav_init_write_sequential(pWav, pFormat, totalPCMFrameCount*pFormat->channels, onWrite, pUserData, pAllocationCallbacks);
  65390. }
  65391. DRWAV_API drwav_bool32 drwav_init_write_with_metadata(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks, drwav_metadata* pMetadata, drwav_uint32 metadataCount)
  65392. {
  65393. if (!drwav_preinit_write(pWav, pFormat, DRWAV_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) {
  65394. return DRWAV_FALSE;
  65395. }
  65396. pWav->pMetadata = pMetadata;
  65397. pWav->metadataCount = metadataCount;
  65398. return drwav_init_write__internal(pWav, pFormat, 0);
  65399. }
  65400. DRWAV_API drwav_uint64 drwav_target_write_size_bytes(const drwav_data_format* pFormat, drwav_uint64 totalFrameCount, drwav_metadata* pMetadata, drwav_uint32 metadataCount)
  65401. {
  65402. drwav_uint64 targetDataSizeBytes = (drwav_uint64)((drwav_int64)totalFrameCount * pFormat->channels * pFormat->bitsPerSample/8.0);
  65403. drwav_uint64 riffChunkSizeBytes;
  65404. drwav_uint64 fileSizeBytes = 0;
  65405. if (pFormat->container == drwav_container_riff) {
  65406. riffChunkSizeBytes = drwav__riff_chunk_size_riff(targetDataSizeBytes, pMetadata, metadataCount);
  65407. fileSizeBytes = (8 + riffChunkSizeBytes);
  65408. } else if (pFormat->container == drwav_container_w64) {
  65409. riffChunkSizeBytes = drwav__riff_chunk_size_w64(targetDataSizeBytes);
  65410. fileSizeBytes = riffChunkSizeBytes;
  65411. } else if (pFormat->container == drwav_container_rf64) {
  65412. riffChunkSizeBytes = drwav__riff_chunk_size_rf64(targetDataSizeBytes, pMetadata, metadataCount);
  65413. fileSizeBytes = (8 + riffChunkSizeBytes);
  65414. }
  65415. return fileSizeBytes;
  65416. }
  65417. #ifndef DR_WAV_NO_STDIO
  65418. #include <errno.h>
  65419. DRWAV_PRIVATE drwav_result drwav_result_from_errno(int e)
  65420. {
  65421. switch (e)
  65422. {
  65423. case 0: return DRWAV_SUCCESS;
  65424. #ifdef EPERM
  65425. case EPERM: return DRWAV_INVALID_OPERATION;
  65426. #endif
  65427. #ifdef ENOENT
  65428. case ENOENT: return DRWAV_DOES_NOT_EXIST;
  65429. #endif
  65430. #ifdef ESRCH
  65431. case ESRCH: return DRWAV_DOES_NOT_EXIST;
  65432. #endif
  65433. #ifdef EINTR
  65434. case EINTR: return DRWAV_INTERRUPT;
  65435. #endif
  65436. #ifdef EIO
  65437. case EIO: return DRWAV_IO_ERROR;
  65438. #endif
  65439. #ifdef ENXIO
  65440. case ENXIO: return DRWAV_DOES_NOT_EXIST;
  65441. #endif
  65442. #ifdef E2BIG
  65443. case E2BIG: return DRWAV_INVALID_ARGS;
  65444. #endif
  65445. #ifdef ENOEXEC
  65446. case ENOEXEC: return DRWAV_INVALID_FILE;
  65447. #endif
  65448. #ifdef EBADF
  65449. case EBADF: return DRWAV_INVALID_FILE;
  65450. #endif
  65451. #ifdef ECHILD
  65452. case ECHILD: return DRWAV_ERROR;
  65453. #endif
  65454. #ifdef EAGAIN
  65455. case EAGAIN: return DRWAV_UNAVAILABLE;
  65456. #endif
  65457. #ifdef ENOMEM
  65458. case ENOMEM: return DRWAV_OUT_OF_MEMORY;
  65459. #endif
  65460. #ifdef EACCES
  65461. case EACCES: return DRWAV_ACCESS_DENIED;
  65462. #endif
  65463. #ifdef EFAULT
  65464. case EFAULT: return DRWAV_BAD_ADDRESS;
  65465. #endif
  65466. #ifdef ENOTBLK
  65467. case ENOTBLK: return DRWAV_ERROR;
  65468. #endif
  65469. #ifdef EBUSY
  65470. case EBUSY: return DRWAV_BUSY;
  65471. #endif
  65472. #ifdef EEXIST
  65473. case EEXIST: return DRWAV_ALREADY_EXISTS;
  65474. #endif
  65475. #ifdef EXDEV
  65476. case EXDEV: return DRWAV_ERROR;
  65477. #endif
  65478. #ifdef ENODEV
  65479. case ENODEV: return DRWAV_DOES_NOT_EXIST;
  65480. #endif
  65481. #ifdef ENOTDIR
  65482. case ENOTDIR: return DRWAV_NOT_DIRECTORY;
  65483. #endif
  65484. #ifdef EISDIR
  65485. case EISDIR: return DRWAV_IS_DIRECTORY;
  65486. #endif
  65487. #ifdef EINVAL
  65488. case EINVAL: return DRWAV_INVALID_ARGS;
  65489. #endif
  65490. #ifdef ENFILE
  65491. case ENFILE: return DRWAV_TOO_MANY_OPEN_FILES;
  65492. #endif
  65493. #ifdef EMFILE
  65494. case EMFILE: return DRWAV_TOO_MANY_OPEN_FILES;
  65495. #endif
  65496. #ifdef ENOTTY
  65497. case ENOTTY: return DRWAV_INVALID_OPERATION;
  65498. #endif
  65499. #ifdef ETXTBSY
  65500. case ETXTBSY: return DRWAV_BUSY;
  65501. #endif
  65502. #ifdef EFBIG
  65503. case EFBIG: return DRWAV_TOO_BIG;
  65504. #endif
  65505. #ifdef ENOSPC
  65506. case ENOSPC: return DRWAV_NO_SPACE;
  65507. #endif
  65508. #ifdef ESPIPE
  65509. case ESPIPE: return DRWAV_BAD_SEEK;
  65510. #endif
  65511. #ifdef EROFS
  65512. case EROFS: return DRWAV_ACCESS_DENIED;
  65513. #endif
  65514. #ifdef EMLINK
  65515. case EMLINK: return DRWAV_TOO_MANY_LINKS;
  65516. #endif
  65517. #ifdef EPIPE
  65518. case EPIPE: return DRWAV_BAD_PIPE;
  65519. #endif
  65520. #ifdef EDOM
  65521. case EDOM: return DRWAV_OUT_OF_RANGE;
  65522. #endif
  65523. #ifdef ERANGE
  65524. case ERANGE: return DRWAV_OUT_OF_RANGE;
  65525. #endif
  65526. #ifdef EDEADLK
  65527. case EDEADLK: return DRWAV_DEADLOCK;
  65528. #endif
  65529. #ifdef ENAMETOOLONG
  65530. case ENAMETOOLONG: return DRWAV_PATH_TOO_LONG;
  65531. #endif
  65532. #ifdef ENOLCK
  65533. case ENOLCK: return DRWAV_ERROR;
  65534. #endif
  65535. #ifdef ENOSYS
  65536. case ENOSYS: return DRWAV_NOT_IMPLEMENTED;
  65537. #endif
  65538. #ifdef ENOTEMPTY
  65539. case ENOTEMPTY: return DRWAV_DIRECTORY_NOT_EMPTY;
  65540. #endif
  65541. #ifdef ELOOP
  65542. case ELOOP: return DRWAV_TOO_MANY_LINKS;
  65543. #endif
  65544. #ifdef ENOMSG
  65545. case ENOMSG: return DRWAV_NO_MESSAGE;
  65546. #endif
  65547. #ifdef EIDRM
  65548. case EIDRM: return DRWAV_ERROR;
  65549. #endif
  65550. #ifdef ECHRNG
  65551. case ECHRNG: return DRWAV_ERROR;
  65552. #endif
  65553. #ifdef EL2NSYNC
  65554. case EL2NSYNC: return DRWAV_ERROR;
  65555. #endif
  65556. #ifdef EL3HLT
  65557. case EL3HLT: return DRWAV_ERROR;
  65558. #endif
  65559. #ifdef EL3RST
  65560. case EL3RST: return DRWAV_ERROR;
  65561. #endif
  65562. #ifdef ELNRNG
  65563. case ELNRNG: return DRWAV_OUT_OF_RANGE;
  65564. #endif
  65565. #ifdef EUNATCH
  65566. case EUNATCH: return DRWAV_ERROR;
  65567. #endif
  65568. #ifdef ENOCSI
  65569. case ENOCSI: return DRWAV_ERROR;
  65570. #endif
  65571. #ifdef EL2HLT
  65572. case EL2HLT: return DRWAV_ERROR;
  65573. #endif
  65574. #ifdef EBADE
  65575. case EBADE: return DRWAV_ERROR;
  65576. #endif
  65577. #ifdef EBADR
  65578. case EBADR: return DRWAV_ERROR;
  65579. #endif
  65580. #ifdef EXFULL
  65581. case EXFULL: return DRWAV_ERROR;
  65582. #endif
  65583. #ifdef ENOANO
  65584. case ENOANO: return DRWAV_ERROR;
  65585. #endif
  65586. #ifdef EBADRQC
  65587. case EBADRQC: return DRWAV_ERROR;
  65588. #endif
  65589. #ifdef EBADSLT
  65590. case EBADSLT: return DRWAV_ERROR;
  65591. #endif
  65592. #ifdef EBFONT
  65593. case EBFONT: return DRWAV_INVALID_FILE;
  65594. #endif
  65595. #ifdef ENOSTR
  65596. case ENOSTR: return DRWAV_ERROR;
  65597. #endif
  65598. #ifdef ENODATA
  65599. case ENODATA: return DRWAV_NO_DATA_AVAILABLE;
  65600. #endif
  65601. #ifdef ETIME
  65602. case ETIME: return DRWAV_TIMEOUT;
  65603. #endif
  65604. #ifdef ENOSR
  65605. case ENOSR: return DRWAV_NO_DATA_AVAILABLE;
  65606. #endif
  65607. #ifdef ENONET
  65608. case ENONET: return DRWAV_NO_NETWORK;
  65609. #endif
  65610. #ifdef ENOPKG
  65611. case ENOPKG: return DRWAV_ERROR;
  65612. #endif
  65613. #ifdef EREMOTE
  65614. case EREMOTE: return DRWAV_ERROR;
  65615. #endif
  65616. #ifdef ENOLINK
  65617. case ENOLINK: return DRWAV_ERROR;
  65618. #endif
  65619. #ifdef EADV
  65620. case EADV: return DRWAV_ERROR;
  65621. #endif
  65622. #ifdef ESRMNT
  65623. case ESRMNT: return DRWAV_ERROR;
  65624. #endif
  65625. #ifdef ECOMM
  65626. case ECOMM: return DRWAV_ERROR;
  65627. #endif
  65628. #ifdef EPROTO
  65629. case EPROTO: return DRWAV_ERROR;
  65630. #endif
  65631. #ifdef EMULTIHOP
  65632. case EMULTIHOP: return DRWAV_ERROR;
  65633. #endif
  65634. #ifdef EDOTDOT
  65635. case EDOTDOT: return DRWAV_ERROR;
  65636. #endif
  65637. #ifdef EBADMSG
  65638. case EBADMSG: return DRWAV_BAD_MESSAGE;
  65639. #endif
  65640. #ifdef EOVERFLOW
  65641. case EOVERFLOW: return DRWAV_TOO_BIG;
  65642. #endif
  65643. #ifdef ENOTUNIQ
  65644. case ENOTUNIQ: return DRWAV_NOT_UNIQUE;
  65645. #endif
  65646. #ifdef EBADFD
  65647. case EBADFD: return DRWAV_ERROR;
  65648. #endif
  65649. #ifdef EREMCHG
  65650. case EREMCHG: return DRWAV_ERROR;
  65651. #endif
  65652. #ifdef ELIBACC
  65653. case ELIBACC: return DRWAV_ACCESS_DENIED;
  65654. #endif
  65655. #ifdef ELIBBAD
  65656. case ELIBBAD: return DRWAV_INVALID_FILE;
  65657. #endif
  65658. #ifdef ELIBSCN
  65659. case ELIBSCN: return DRWAV_INVALID_FILE;
  65660. #endif
  65661. #ifdef ELIBMAX
  65662. case ELIBMAX: return DRWAV_ERROR;
  65663. #endif
  65664. #ifdef ELIBEXEC
  65665. case ELIBEXEC: return DRWAV_ERROR;
  65666. #endif
  65667. #ifdef EILSEQ
  65668. case EILSEQ: return DRWAV_INVALID_DATA;
  65669. #endif
  65670. #ifdef ERESTART
  65671. case ERESTART: return DRWAV_ERROR;
  65672. #endif
  65673. #ifdef ESTRPIPE
  65674. case ESTRPIPE: return DRWAV_ERROR;
  65675. #endif
  65676. #ifdef EUSERS
  65677. case EUSERS: return DRWAV_ERROR;
  65678. #endif
  65679. #ifdef ENOTSOCK
  65680. case ENOTSOCK: return DRWAV_NOT_SOCKET;
  65681. #endif
  65682. #ifdef EDESTADDRREQ
  65683. case EDESTADDRREQ: return DRWAV_NO_ADDRESS;
  65684. #endif
  65685. #ifdef EMSGSIZE
  65686. case EMSGSIZE: return DRWAV_TOO_BIG;
  65687. #endif
  65688. #ifdef EPROTOTYPE
  65689. case EPROTOTYPE: return DRWAV_BAD_PROTOCOL;
  65690. #endif
  65691. #ifdef ENOPROTOOPT
  65692. case ENOPROTOOPT: return DRWAV_PROTOCOL_UNAVAILABLE;
  65693. #endif
  65694. #ifdef EPROTONOSUPPORT
  65695. case EPROTONOSUPPORT: return DRWAV_PROTOCOL_NOT_SUPPORTED;
  65696. #endif
  65697. #ifdef ESOCKTNOSUPPORT
  65698. case ESOCKTNOSUPPORT: return DRWAV_SOCKET_NOT_SUPPORTED;
  65699. #endif
  65700. #ifdef EOPNOTSUPP
  65701. case EOPNOTSUPP: return DRWAV_INVALID_OPERATION;
  65702. #endif
  65703. #ifdef EPFNOSUPPORT
  65704. case EPFNOSUPPORT: return DRWAV_PROTOCOL_FAMILY_NOT_SUPPORTED;
  65705. #endif
  65706. #ifdef EAFNOSUPPORT
  65707. case EAFNOSUPPORT: return DRWAV_ADDRESS_FAMILY_NOT_SUPPORTED;
  65708. #endif
  65709. #ifdef EADDRINUSE
  65710. case EADDRINUSE: return DRWAV_ALREADY_IN_USE;
  65711. #endif
  65712. #ifdef EADDRNOTAVAIL
  65713. case EADDRNOTAVAIL: return DRWAV_ERROR;
  65714. #endif
  65715. #ifdef ENETDOWN
  65716. case ENETDOWN: return DRWAV_NO_NETWORK;
  65717. #endif
  65718. #ifdef ENETUNREACH
  65719. case ENETUNREACH: return DRWAV_NO_NETWORK;
  65720. #endif
  65721. #ifdef ENETRESET
  65722. case ENETRESET: return DRWAV_NO_NETWORK;
  65723. #endif
  65724. #ifdef ECONNABORTED
  65725. case ECONNABORTED: return DRWAV_NO_NETWORK;
  65726. #endif
  65727. #ifdef ECONNRESET
  65728. case ECONNRESET: return DRWAV_CONNECTION_RESET;
  65729. #endif
  65730. #ifdef ENOBUFS
  65731. case ENOBUFS: return DRWAV_NO_SPACE;
  65732. #endif
  65733. #ifdef EISCONN
  65734. case EISCONN: return DRWAV_ALREADY_CONNECTED;
  65735. #endif
  65736. #ifdef ENOTCONN
  65737. case ENOTCONN: return DRWAV_NOT_CONNECTED;
  65738. #endif
  65739. #ifdef ESHUTDOWN
  65740. case ESHUTDOWN: return DRWAV_ERROR;
  65741. #endif
  65742. #ifdef ETOOMANYREFS
  65743. case ETOOMANYREFS: return DRWAV_ERROR;
  65744. #endif
  65745. #ifdef ETIMEDOUT
  65746. case ETIMEDOUT: return DRWAV_TIMEOUT;
  65747. #endif
  65748. #ifdef ECONNREFUSED
  65749. case ECONNREFUSED: return DRWAV_CONNECTION_REFUSED;
  65750. #endif
  65751. #ifdef EHOSTDOWN
  65752. case EHOSTDOWN: return DRWAV_NO_HOST;
  65753. #endif
  65754. #ifdef EHOSTUNREACH
  65755. case EHOSTUNREACH: return DRWAV_NO_HOST;
  65756. #endif
  65757. #ifdef EALREADY
  65758. case EALREADY: return DRWAV_IN_PROGRESS;
  65759. #endif
  65760. #ifdef EINPROGRESS
  65761. case EINPROGRESS: return DRWAV_IN_PROGRESS;
  65762. #endif
  65763. #ifdef ESTALE
  65764. case ESTALE: return DRWAV_INVALID_FILE;
  65765. #endif
  65766. #ifdef EUCLEAN
  65767. case EUCLEAN: return DRWAV_ERROR;
  65768. #endif
  65769. #ifdef ENOTNAM
  65770. case ENOTNAM: return DRWAV_ERROR;
  65771. #endif
  65772. #ifdef ENAVAIL
  65773. case ENAVAIL: return DRWAV_ERROR;
  65774. #endif
  65775. #ifdef EISNAM
  65776. case EISNAM: return DRWAV_ERROR;
  65777. #endif
  65778. #ifdef EREMOTEIO
  65779. case EREMOTEIO: return DRWAV_IO_ERROR;
  65780. #endif
  65781. #ifdef EDQUOT
  65782. case EDQUOT: return DRWAV_NO_SPACE;
  65783. #endif
  65784. #ifdef ENOMEDIUM
  65785. case ENOMEDIUM: return DRWAV_DOES_NOT_EXIST;
  65786. #endif
  65787. #ifdef EMEDIUMTYPE
  65788. case EMEDIUMTYPE: return DRWAV_ERROR;
  65789. #endif
  65790. #ifdef ECANCELED
  65791. case ECANCELED: return DRWAV_CANCELLED;
  65792. #endif
  65793. #ifdef ENOKEY
  65794. case ENOKEY: return DRWAV_ERROR;
  65795. #endif
  65796. #ifdef EKEYEXPIRED
  65797. case EKEYEXPIRED: return DRWAV_ERROR;
  65798. #endif
  65799. #ifdef EKEYREVOKED
  65800. case EKEYREVOKED: return DRWAV_ERROR;
  65801. #endif
  65802. #ifdef EKEYREJECTED
  65803. case EKEYREJECTED: return DRWAV_ERROR;
  65804. #endif
  65805. #ifdef EOWNERDEAD
  65806. case EOWNERDEAD: return DRWAV_ERROR;
  65807. #endif
  65808. #ifdef ENOTRECOVERABLE
  65809. case ENOTRECOVERABLE: return DRWAV_ERROR;
  65810. #endif
  65811. #ifdef ERFKILL
  65812. case ERFKILL: return DRWAV_ERROR;
  65813. #endif
  65814. #ifdef EHWPOISON
  65815. case EHWPOISON: return DRWAV_ERROR;
  65816. #endif
  65817. default: return DRWAV_ERROR;
  65818. }
  65819. }
  65820. DRWAV_PRIVATE drwav_result drwav_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  65821. {
  65822. #if defined(_MSC_VER) && _MSC_VER >= 1400
  65823. errno_t err;
  65824. #endif
  65825. if (ppFile != NULL) {
  65826. *ppFile = NULL;
  65827. }
  65828. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  65829. return DRWAV_INVALID_ARGS;
  65830. }
  65831. #if defined(_MSC_VER) && _MSC_VER >= 1400
  65832. err = fopen_s(ppFile, pFilePath, pOpenMode);
  65833. if (err != 0) {
  65834. return drwav_result_from_errno(err);
  65835. }
  65836. #else
  65837. #if defined(_WIN32) || defined(__APPLE__)
  65838. *ppFile = fopen(pFilePath, pOpenMode);
  65839. #else
  65840. #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  65841. *ppFile = fopen64(pFilePath, pOpenMode);
  65842. #else
  65843. *ppFile = fopen(pFilePath, pOpenMode);
  65844. #endif
  65845. #endif
  65846. if (*ppFile == NULL) {
  65847. drwav_result result = drwav_result_from_errno(errno);
  65848. if (result == DRWAV_SUCCESS) {
  65849. result = DRWAV_ERROR;
  65850. }
  65851. return result;
  65852. }
  65853. #endif
  65854. return DRWAV_SUCCESS;
  65855. }
  65856. #if defined(_WIN32)
  65857. #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
  65858. #define DRWAV_HAS_WFOPEN
  65859. #endif
  65860. #endif
  65861. #ifndef DR_WAV_NO_WCHAR
  65862. DRWAV_PRIVATE drwav_result drwav_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drwav_allocation_callbacks* pAllocationCallbacks)
  65863. {
  65864. if (ppFile != NULL) {
  65865. *ppFile = NULL;
  65866. }
  65867. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  65868. return DRWAV_INVALID_ARGS;
  65869. }
  65870. #if defined(DRWAV_HAS_WFOPEN)
  65871. {
  65872. #if defined(_MSC_VER) && _MSC_VER >= 1400
  65873. errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  65874. if (err != 0) {
  65875. return drwav_result_from_errno(err);
  65876. }
  65877. #else
  65878. *ppFile = _wfopen(pFilePath, pOpenMode);
  65879. if (*ppFile == NULL) {
  65880. return drwav_result_from_errno(errno);
  65881. }
  65882. #endif
  65883. (void)pAllocationCallbacks;
  65884. }
  65885. #else
  65886. #if defined(__DJGPP__)
  65887. {
  65888. }
  65889. #else
  65890. {
  65891. mbstate_t mbs;
  65892. size_t lenMB;
  65893. const wchar_t* pFilePathTemp = pFilePath;
  65894. char* pFilePathMB = NULL;
  65895. char pOpenModeMB[32] = {0};
  65896. DRWAV_ZERO_OBJECT(&mbs);
  65897. lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  65898. if (lenMB == (size_t)-1) {
  65899. return drwav_result_from_errno(errno);
  65900. }
  65901. pFilePathMB = (char*)drwav__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
  65902. if (pFilePathMB == NULL) {
  65903. return DRWAV_OUT_OF_MEMORY;
  65904. }
  65905. pFilePathTemp = pFilePath;
  65906. DRWAV_ZERO_OBJECT(&mbs);
  65907. wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  65908. {
  65909. size_t i = 0;
  65910. for (;;) {
  65911. if (pOpenMode[i] == 0) {
  65912. pOpenModeMB[i] = '\0';
  65913. break;
  65914. }
  65915. pOpenModeMB[i] = (char)pOpenMode[i];
  65916. i += 1;
  65917. }
  65918. }
  65919. *ppFile = fopen(pFilePathMB, pOpenModeMB);
  65920. drwav__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
  65921. }
  65922. #endif
  65923. if (*ppFile == NULL) {
  65924. return DRWAV_ERROR;
  65925. }
  65926. #endif
  65927. return DRWAV_SUCCESS;
  65928. }
  65929. #endif
  65930. DRWAV_PRIVATE size_t drwav__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead)
  65931. {
  65932. return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData);
  65933. }
  65934. DRWAV_PRIVATE size_t drwav__on_write_stdio(void* pUserData, const void* pData, size_t bytesToWrite)
  65935. {
  65936. return fwrite(pData, 1, bytesToWrite, (FILE*)pUserData);
  65937. }
  65938. DRWAV_PRIVATE drwav_bool32 drwav__on_seek_stdio(void* pUserData, int offset, drwav_seek_origin origin)
  65939. {
  65940. return fseek((FILE*)pUserData, offset, (origin == drwav_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  65941. }
  65942. DRWAV_API drwav_bool32 drwav_init_file(drwav* pWav, const char* filename, const drwav_allocation_callbacks* pAllocationCallbacks)
  65943. {
  65944. return drwav_init_file_ex(pWav, filename, NULL, NULL, 0, pAllocationCallbacks);
  65945. }
  65946. DRWAV_PRIVATE drwav_bool32 drwav_init_file__internal_FILE(drwav* pWav, FILE* pFile, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, drwav_metadata_type allowedMetadataTypes, const drwav_allocation_callbacks* pAllocationCallbacks)
  65947. {
  65948. drwav_bool32 result;
  65949. result = drwav_preinit(pWav, drwav__on_read_stdio, drwav__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  65950. if (result != DRWAV_TRUE) {
  65951. fclose(pFile);
  65952. return result;
  65953. }
  65954. pWav->allowedMetadataTypes = allowedMetadataTypes;
  65955. result = drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
  65956. if (result != DRWAV_TRUE) {
  65957. fclose(pFile);
  65958. return result;
  65959. }
  65960. return DRWAV_TRUE;
  65961. }
  65962. DRWAV_API drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  65963. {
  65964. FILE* pFile;
  65965. if (drwav_fopen(&pFile, filename, "rb") != DRWAV_SUCCESS) {
  65966. return DRWAV_FALSE;
  65967. }
  65968. return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, drwav_metadata_type_none, pAllocationCallbacks);
  65969. }
  65970. #ifndef DR_WAV_NO_WCHAR
  65971. DRWAV_API drwav_bool32 drwav_init_file_w(drwav* pWav, const wchar_t* filename, const drwav_allocation_callbacks* pAllocationCallbacks)
  65972. {
  65973. return drwav_init_file_ex_w(pWav, filename, NULL, NULL, 0, pAllocationCallbacks);
  65974. }
  65975. DRWAV_API drwav_bool32 drwav_init_file_ex_w(drwav* pWav, const wchar_t* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  65976. {
  65977. FILE* pFile;
  65978. if (drwav_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != DRWAV_SUCCESS) {
  65979. return DRWAV_FALSE;
  65980. }
  65981. return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, drwav_metadata_type_none, pAllocationCallbacks);
  65982. }
  65983. #endif
  65984. DRWAV_API drwav_bool32 drwav_init_file_with_metadata(drwav* pWav, const char* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  65985. {
  65986. FILE* pFile;
  65987. if (drwav_fopen(&pFile, filename, "rb") != DRWAV_SUCCESS) {
  65988. return DRWAV_FALSE;
  65989. }
  65990. return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags, drwav_metadata_type_all_including_unknown, pAllocationCallbacks);
  65991. }
  65992. #ifndef DR_WAV_NO_WCHAR
  65993. DRWAV_API drwav_bool32 drwav_init_file_with_metadata_w(drwav* pWav, const wchar_t* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  65994. {
  65995. FILE* pFile;
  65996. if (drwav_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != DRWAV_SUCCESS) {
  65997. return DRWAV_FALSE;
  65998. }
  65999. return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags, drwav_metadata_type_all_including_unknown, pAllocationCallbacks);
  66000. }
  66001. #endif
  66002. DRWAV_PRIVATE drwav_bool32 drwav_init_file_write__internal_FILE(drwav* pWav, FILE* pFile, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
  66003. {
  66004. drwav_bool32 result;
  66005. result = drwav_preinit_write(pWav, pFormat, isSequential, drwav__on_write_stdio, drwav__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  66006. if (result != DRWAV_TRUE) {
  66007. fclose(pFile);
  66008. return result;
  66009. }
  66010. result = drwav_init_write__internal(pWav, pFormat, totalSampleCount);
  66011. if (result != DRWAV_TRUE) {
  66012. fclose(pFile);
  66013. return result;
  66014. }
  66015. return DRWAV_TRUE;
  66016. }
  66017. DRWAV_PRIVATE drwav_bool32 drwav_init_file_write__internal(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
  66018. {
  66019. FILE* pFile;
  66020. if (drwav_fopen(&pFile, filename, "wb") != DRWAV_SUCCESS) {
  66021. return DRWAV_FALSE;
  66022. }
  66023. return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
  66024. }
  66025. #ifndef DR_WAV_NO_WCHAR
  66026. DRWAV_PRIVATE drwav_bool32 drwav_init_file_write_w__internal(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
  66027. {
  66028. FILE* pFile;
  66029. if (drwav_wfopen(&pFile, filename, L"wb", pAllocationCallbacks) != DRWAV_SUCCESS) {
  66030. return DRWAV_FALSE;
  66031. }
  66032. return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
  66033. }
  66034. #endif
  66035. DRWAV_API drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
  66036. {
  66037. return drwav_init_file_write__internal(pWav, filename, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
  66038. }
  66039. DRWAV_API drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  66040. {
  66041. return drwav_init_file_write__internal(pWav, filename, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
  66042. }
  66043. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  66044. {
  66045. if (pFormat == NULL) {
  66046. return DRWAV_FALSE;
  66047. }
  66048. return drwav_init_file_write_sequential(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
  66049. }
  66050. #ifndef DR_WAV_NO_WCHAR
  66051. DRWAV_API drwav_bool32 drwav_init_file_write_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
  66052. {
  66053. return drwav_init_file_write_w__internal(pWav, filename, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
  66054. }
  66055. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  66056. {
  66057. return drwav_init_file_write_w__internal(pWav, filename, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
  66058. }
  66059. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  66060. {
  66061. if (pFormat == NULL) {
  66062. return DRWAV_FALSE;
  66063. }
  66064. return drwav_init_file_write_sequential_w(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
  66065. }
  66066. #endif
  66067. #endif
  66068. DRWAV_PRIVATE size_t drwav__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
  66069. {
  66070. drwav* pWav = (drwav*)pUserData;
  66071. size_t bytesRemaining;
  66072. DRWAV_ASSERT(pWav != NULL);
  66073. DRWAV_ASSERT(pWav->memoryStream.dataSize >= pWav->memoryStream.currentReadPos);
  66074. bytesRemaining = pWav->memoryStream.dataSize - pWav->memoryStream.currentReadPos;
  66075. if (bytesToRead > bytesRemaining) {
  66076. bytesToRead = bytesRemaining;
  66077. }
  66078. if (bytesToRead > 0) {
  66079. DRWAV_COPY_MEMORY(pBufferOut, pWav->memoryStream.data + pWav->memoryStream.currentReadPos, bytesToRead);
  66080. pWav->memoryStream.currentReadPos += bytesToRead;
  66081. }
  66082. return bytesToRead;
  66083. }
  66084. DRWAV_PRIVATE drwav_bool32 drwav__on_seek_memory(void* pUserData, int offset, drwav_seek_origin origin)
  66085. {
  66086. drwav* pWav = (drwav*)pUserData;
  66087. DRWAV_ASSERT(pWav != NULL);
  66088. if (origin == drwav_seek_origin_current) {
  66089. if (offset > 0) {
  66090. if (pWav->memoryStream.currentReadPos + offset > pWav->memoryStream.dataSize) {
  66091. return DRWAV_FALSE;
  66092. }
  66093. } else {
  66094. if (pWav->memoryStream.currentReadPos < (size_t)-offset) {
  66095. return DRWAV_FALSE;
  66096. }
  66097. }
  66098. pWav->memoryStream.currentReadPos += offset;
  66099. } else {
  66100. if ((drwav_uint32)offset <= pWav->memoryStream.dataSize) {
  66101. pWav->memoryStream.currentReadPos = offset;
  66102. } else {
  66103. return DRWAV_FALSE;
  66104. }
  66105. }
  66106. return DRWAV_TRUE;
  66107. }
  66108. DRWAV_PRIVATE size_t drwav__on_write_memory(void* pUserData, const void* pDataIn, size_t bytesToWrite)
  66109. {
  66110. drwav* pWav = (drwav*)pUserData;
  66111. size_t bytesRemaining;
  66112. DRWAV_ASSERT(pWav != NULL);
  66113. DRWAV_ASSERT(pWav->memoryStreamWrite.dataCapacity >= pWav->memoryStreamWrite.currentWritePos);
  66114. bytesRemaining = pWav->memoryStreamWrite.dataCapacity - pWav->memoryStreamWrite.currentWritePos;
  66115. if (bytesRemaining < bytesToWrite) {
  66116. void* pNewData;
  66117. size_t newDataCapacity = (pWav->memoryStreamWrite.dataCapacity == 0) ? 256 : pWav->memoryStreamWrite.dataCapacity * 2;
  66118. if ((newDataCapacity - pWav->memoryStreamWrite.currentWritePos) < bytesToWrite) {
  66119. newDataCapacity = pWav->memoryStreamWrite.currentWritePos + bytesToWrite;
  66120. }
  66121. pNewData = drwav__realloc_from_callbacks(*pWav->memoryStreamWrite.ppData, newDataCapacity, pWav->memoryStreamWrite.dataCapacity, &pWav->allocationCallbacks);
  66122. if (pNewData == NULL) {
  66123. return 0;
  66124. }
  66125. *pWav->memoryStreamWrite.ppData = pNewData;
  66126. pWav->memoryStreamWrite.dataCapacity = newDataCapacity;
  66127. }
  66128. DRWAV_COPY_MEMORY(((drwav_uint8*)(*pWav->memoryStreamWrite.ppData)) + pWav->memoryStreamWrite.currentWritePos, pDataIn, bytesToWrite);
  66129. pWav->memoryStreamWrite.currentWritePos += bytesToWrite;
  66130. if (pWav->memoryStreamWrite.dataSize < pWav->memoryStreamWrite.currentWritePos) {
  66131. pWav->memoryStreamWrite.dataSize = pWav->memoryStreamWrite.currentWritePos;
  66132. }
  66133. *pWav->memoryStreamWrite.pDataSize = pWav->memoryStreamWrite.dataSize;
  66134. return bytesToWrite;
  66135. }
  66136. DRWAV_PRIVATE drwav_bool32 drwav__on_seek_memory_write(void* pUserData, int offset, drwav_seek_origin origin)
  66137. {
  66138. drwav* pWav = (drwav*)pUserData;
  66139. DRWAV_ASSERT(pWav != NULL);
  66140. if (origin == drwav_seek_origin_current) {
  66141. if (offset > 0) {
  66142. if (pWav->memoryStreamWrite.currentWritePos + offset > pWav->memoryStreamWrite.dataSize) {
  66143. offset = (int)(pWav->memoryStreamWrite.dataSize - pWav->memoryStreamWrite.currentWritePos);
  66144. }
  66145. } else {
  66146. if (pWav->memoryStreamWrite.currentWritePos < (size_t)-offset) {
  66147. offset = -(int)pWav->memoryStreamWrite.currentWritePos;
  66148. }
  66149. }
  66150. pWav->memoryStreamWrite.currentWritePos += offset;
  66151. } else {
  66152. if ((drwav_uint32)offset <= pWav->memoryStreamWrite.dataSize) {
  66153. pWav->memoryStreamWrite.currentWritePos = offset;
  66154. } else {
  66155. pWav->memoryStreamWrite.currentWritePos = pWav->memoryStreamWrite.dataSize;
  66156. }
  66157. }
  66158. return DRWAV_TRUE;
  66159. }
  66160. DRWAV_API drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize, const drwav_allocation_callbacks* pAllocationCallbacks)
  66161. {
  66162. return drwav_init_memory_ex(pWav, data, dataSize, NULL, NULL, 0, pAllocationCallbacks);
  66163. }
  66164. DRWAV_API drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  66165. {
  66166. if (data == NULL || dataSize == 0) {
  66167. return DRWAV_FALSE;
  66168. }
  66169. if (!drwav_preinit(pWav, drwav__on_read_memory, drwav__on_seek_memory, pWav, pAllocationCallbacks)) {
  66170. return DRWAV_FALSE;
  66171. }
  66172. pWav->memoryStream.data = (const drwav_uint8*)data;
  66173. pWav->memoryStream.dataSize = dataSize;
  66174. pWav->memoryStream.currentReadPos = 0;
  66175. return drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
  66176. }
  66177. DRWAV_API drwav_bool32 drwav_init_memory_with_metadata(drwav* pWav, const void* data, size_t dataSize, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  66178. {
  66179. if (data == NULL || dataSize == 0) {
  66180. return DRWAV_FALSE;
  66181. }
  66182. if (!drwav_preinit(pWav, drwav__on_read_memory, drwav__on_seek_memory, pWav, pAllocationCallbacks)) {
  66183. return DRWAV_FALSE;
  66184. }
  66185. pWav->memoryStream.data = (const drwav_uint8*)data;
  66186. pWav->memoryStream.dataSize = dataSize;
  66187. pWav->memoryStream.currentReadPos = 0;
  66188. pWav->allowedMetadataTypes = drwav_metadata_type_all_including_unknown;
  66189. return drwav_init__internal(pWav, NULL, NULL, flags);
  66190. }
  66191. DRWAV_PRIVATE drwav_bool32 drwav_init_memory_write__internal(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
  66192. {
  66193. if (ppData == NULL || pDataSize == NULL) {
  66194. return DRWAV_FALSE;
  66195. }
  66196. *ppData = NULL;
  66197. *pDataSize = 0;
  66198. if (!drwav_preinit_write(pWav, pFormat, isSequential, drwav__on_write_memory, drwav__on_seek_memory_write, pWav, pAllocationCallbacks)) {
  66199. return DRWAV_FALSE;
  66200. }
  66201. pWav->memoryStreamWrite.ppData = ppData;
  66202. pWav->memoryStreamWrite.pDataSize = pDataSize;
  66203. pWav->memoryStreamWrite.dataSize = 0;
  66204. pWav->memoryStreamWrite.dataCapacity = 0;
  66205. pWav->memoryStreamWrite.currentWritePos = 0;
  66206. return drwav_init_write__internal(pWav, pFormat, totalSampleCount);
  66207. }
  66208. DRWAV_API drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
  66209. {
  66210. return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
  66211. }
  66212. DRWAV_API drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  66213. {
  66214. return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
  66215. }
  66216. DRWAV_API drwav_bool32 drwav_init_memory_write_sequential_pcm_frames(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  66217. {
  66218. if (pFormat == NULL) {
  66219. return DRWAV_FALSE;
  66220. }
  66221. return drwav_init_memory_write_sequential(pWav, ppData, pDataSize, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
  66222. }
  66223. DRWAV_API drwav_result drwav_uninit(drwav* pWav)
  66224. {
  66225. drwav_result result = DRWAV_SUCCESS;
  66226. if (pWav == NULL) {
  66227. return DRWAV_INVALID_ARGS;
  66228. }
  66229. if (pWav->onWrite != NULL) {
  66230. drwav_uint32 paddingSize = 0;
  66231. if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64) {
  66232. paddingSize = drwav__chunk_padding_size_riff(pWav->dataChunkDataSize);
  66233. } else {
  66234. paddingSize = drwav__chunk_padding_size_w64(pWav->dataChunkDataSize);
  66235. }
  66236. if (paddingSize > 0) {
  66237. drwav_uint64 paddingData = 0;
  66238. drwav__write(pWav, &paddingData, paddingSize);
  66239. }
  66240. if (pWav->onSeek && !pWav->isSequentialWrite) {
  66241. if (pWav->container == drwav_container_riff) {
  66242. if (pWav->onSeek(pWav->pUserData, 4, drwav_seek_origin_start)) {
  66243. drwav_uint32 riffChunkSize = drwav__riff_chunk_size_riff(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount);
  66244. drwav__write_u32ne_to_le(pWav, riffChunkSize);
  66245. }
  66246. if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 4, drwav_seek_origin_start)) {
  66247. drwav_uint32 dataChunkSize = drwav__data_chunk_size_riff(pWav->dataChunkDataSize);
  66248. drwav__write_u32ne_to_le(pWav, dataChunkSize);
  66249. }
  66250. } else if (pWav->container == drwav_container_w64) {
  66251. if (pWav->onSeek(pWav->pUserData, 16, drwav_seek_origin_start)) {
  66252. drwav_uint64 riffChunkSize = drwav__riff_chunk_size_w64(pWav->dataChunkDataSize);
  66253. drwav__write_u64ne_to_le(pWav, riffChunkSize);
  66254. }
  66255. if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 8, drwav_seek_origin_start)) {
  66256. drwav_uint64 dataChunkSize = drwav__data_chunk_size_w64(pWav->dataChunkDataSize);
  66257. drwav__write_u64ne_to_le(pWav, dataChunkSize);
  66258. }
  66259. } else if (pWav->container == drwav_container_rf64) {
  66260. int ds64BodyPos = 12 + 8;
  66261. if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 0, drwav_seek_origin_start)) {
  66262. drwav_uint64 riffChunkSize = drwav__riff_chunk_size_rf64(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount);
  66263. drwav__write_u64ne_to_le(pWav, riffChunkSize);
  66264. }
  66265. if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 8, drwav_seek_origin_start)) {
  66266. drwav_uint64 dataChunkSize = drwav__data_chunk_size_rf64(pWav->dataChunkDataSize);
  66267. drwav__write_u64ne_to_le(pWav, dataChunkSize);
  66268. }
  66269. }
  66270. }
  66271. if (pWav->isSequentialWrite) {
  66272. if (pWav->dataChunkDataSize != pWav->dataChunkDataSizeTargetWrite) {
  66273. result = DRWAV_INVALID_FILE;
  66274. }
  66275. }
  66276. } else {
  66277. if (pWav->pMetadata != NULL) {
  66278. pWav->allocationCallbacks.onFree(pWav->pMetadata, pWav->allocationCallbacks.pUserData);
  66279. }
  66280. }
  66281. #ifndef DR_WAV_NO_STDIO
  66282. if (pWav->onRead == drwav__on_read_stdio || pWav->onWrite == drwav__on_write_stdio) {
  66283. fclose((FILE*)pWav->pUserData);
  66284. }
  66285. #endif
  66286. return result;
  66287. }
  66288. DRWAV_API size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut)
  66289. {
  66290. size_t bytesRead;
  66291. drwav_uint32 bytesPerFrame;
  66292. if (pWav == NULL || bytesToRead == 0) {
  66293. return 0;
  66294. }
  66295. if (bytesToRead > pWav->bytesRemaining) {
  66296. bytesToRead = (size_t)pWav->bytesRemaining;
  66297. }
  66298. if (bytesToRead == 0) {
  66299. return 0;
  66300. }
  66301. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  66302. if (bytesPerFrame == 0) {
  66303. return 0;
  66304. }
  66305. if (pBufferOut != NULL) {
  66306. bytesRead = pWav->onRead(pWav->pUserData, pBufferOut, bytesToRead);
  66307. } else {
  66308. bytesRead = 0;
  66309. while (bytesRead < bytesToRead) {
  66310. size_t bytesToSeek = (bytesToRead - bytesRead);
  66311. if (bytesToSeek > 0x7FFFFFFF) {
  66312. bytesToSeek = 0x7FFFFFFF;
  66313. }
  66314. if (pWav->onSeek(pWav->pUserData, (int)bytesToSeek, drwav_seek_origin_current) == DRWAV_FALSE) {
  66315. break;
  66316. }
  66317. bytesRead += bytesToSeek;
  66318. }
  66319. while (bytesRead < bytesToRead) {
  66320. drwav_uint8 buffer[4096];
  66321. size_t bytesSeeked;
  66322. size_t bytesToSeek = (bytesToRead - bytesRead);
  66323. if (bytesToSeek > sizeof(buffer)) {
  66324. bytesToSeek = sizeof(buffer);
  66325. }
  66326. bytesSeeked = pWav->onRead(pWav->pUserData, buffer, bytesToSeek);
  66327. bytesRead += bytesSeeked;
  66328. if (bytesSeeked < bytesToSeek) {
  66329. break;
  66330. }
  66331. }
  66332. }
  66333. pWav->readCursorInPCMFrames += bytesRead / bytesPerFrame;
  66334. pWav->bytesRemaining -= bytesRead;
  66335. return bytesRead;
  66336. }
  66337. DRWAV_API drwav_uint64 drwav_read_pcm_frames_le(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
  66338. {
  66339. drwav_uint32 bytesPerFrame;
  66340. drwav_uint64 bytesToRead;
  66341. if (pWav == NULL || framesToRead == 0) {
  66342. return 0;
  66343. }
  66344. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  66345. return 0;
  66346. }
  66347. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  66348. if (bytesPerFrame == 0) {
  66349. return 0;
  66350. }
  66351. bytesToRead = framesToRead * bytesPerFrame;
  66352. if (bytesToRead > DRWAV_SIZE_MAX) {
  66353. bytesToRead = (DRWAV_SIZE_MAX / bytesPerFrame) * bytesPerFrame;
  66354. }
  66355. if (bytesToRead == 0) {
  66356. return 0;
  66357. }
  66358. return drwav_read_raw(pWav, (size_t)bytesToRead, pBufferOut) / bytesPerFrame;
  66359. }
  66360. DRWAV_API drwav_uint64 drwav_read_pcm_frames_be(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
  66361. {
  66362. drwav_uint64 framesRead = drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
  66363. if (pBufferOut != NULL) {
  66364. drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  66365. if (bytesPerFrame == 0) {
  66366. return 0;
  66367. }
  66368. drwav__bswap_samples(pBufferOut, framesRead*pWav->channels, bytesPerFrame/pWav->channels, pWav->translatedFormatTag);
  66369. }
  66370. return framesRead;
  66371. }
  66372. DRWAV_API drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
  66373. {
  66374. if (drwav__is_little_endian()) {
  66375. return drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
  66376. } else {
  66377. return drwav_read_pcm_frames_be(pWav, framesToRead, pBufferOut);
  66378. }
  66379. }
  66380. DRWAV_PRIVATE drwav_bool32 drwav_seek_to_first_pcm_frame(drwav* pWav)
  66381. {
  66382. if (pWav->onWrite != NULL) {
  66383. return DRWAV_FALSE;
  66384. }
  66385. if (!pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos, drwav_seek_origin_start)) {
  66386. return DRWAV_FALSE;
  66387. }
  66388. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  66389. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  66390. DRWAV_ZERO_OBJECT(&pWav->msadpcm);
  66391. } else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  66392. DRWAV_ZERO_OBJECT(&pWav->ima);
  66393. } else {
  66394. DRWAV_ASSERT(DRWAV_FALSE);
  66395. }
  66396. }
  66397. pWav->readCursorInPCMFrames = 0;
  66398. pWav->bytesRemaining = pWav->dataChunkDataSize;
  66399. return DRWAV_TRUE;
  66400. }
  66401. DRWAV_API drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex)
  66402. {
  66403. if (pWav == NULL || pWav->onSeek == NULL) {
  66404. return DRWAV_FALSE;
  66405. }
  66406. if (pWav->onWrite != NULL) {
  66407. return DRWAV_FALSE;
  66408. }
  66409. if (pWav->totalPCMFrameCount == 0) {
  66410. return DRWAV_TRUE;
  66411. }
  66412. if (targetFrameIndex > pWav->totalPCMFrameCount) {
  66413. targetFrameIndex = pWav->totalPCMFrameCount;
  66414. }
  66415. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  66416. if (targetFrameIndex < pWav->readCursorInPCMFrames) {
  66417. if (!drwav_seek_to_first_pcm_frame(pWav)) {
  66418. return DRWAV_FALSE;
  66419. }
  66420. }
  66421. if (targetFrameIndex > pWav->readCursorInPCMFrames) {
  66422. drwav_uint64 offsetInFrames = targetFrameIndex - pWav->readCursorInPCMFrames;
  66423. drwav_int16 devnull[2048];
  66424. while (offsetInFrames > 0) {
  66425. drwav_uint64 framesRead = 0;
  66426. drwav_uint64 framesToRead = offsetInFrames;
  66427. if (framesToRead > drwav_countof(devnull)/pWav->channels) {
  66428. framesToRead = drwav_countof(devnull)/pWav->channels;
  66429. }
  66430. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  66431. framesRead = drwav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, devnull);
  66432. } else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  66433. framesRead = drwav_read_pcm_frames_s16__ima(pWav, framesToRead, devnull);
  66434. } else {
  66435. DRWAV_ASSERT(DRWAV_FALSE);
  66436. }
  66437. if (framesRead != framesToRead) {
  66438. return DRWAV_FALSE;
  66439. }
  66440. offsetInFrames -= framesRead;
  66441. }
  66442. }
  66443. } else {
  66444. drwav_uint64 totalSizeInBytes;
  66445. drwav_uint64 currentBytePos;
  66446. drwav_uint64 targetBytePos;
  66447. drwav_uint64 offset;
  66448. drwav_uint32 bytesPerFrame;
  66449. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  66450. if (bytesPerFrame == 0) {
  66451. return DRWAV_FALSE;
  66452. }
  66453. totalSizeInBytes = pWav->totalPCMFrameCount * bytesPerFrame;
  66454. DRWAV_ASSERT(totalSizeInBytes >= pWav->bytesRemaining);
  66455. currentBytePos = totalSizeInBytes - pWav->bytesRemaining;
  66456. targetBytePos = targetFrameIndex * bytesPerFrame;
  66457. if (currentBytePos < targetBytePos) {
  66458. offset = (targetBytePos - currentBytePos);
  66459. } else {
  66460. if (!drwav_seek_to_first_pcm_frame(pWav)) {
  66461. return DRWAV_FALSE;
  66462. }
  66463. offset = targetBytePos;
  66464. }
  66465. while (offset > 0) {
  66466. int offset32 = ((offset > INT_MAX) ? INT_MAX : (int)offset);
  66467. if (!pWav->onSeek(pWav->pUserData, offset32, drwav_seek_origin_current)) {
  66468. return DRWAV_FALSE;
  66469. }
  66470. pWav->readCursorInPCMFrames += offset32 / bytesPerFrame;
  66471. pWav->bytesRemaining -= offset32;
  66472. offset -= offset32;
  66473. }
  66474. }
  66475. return DRWAV_TRUE;
  66476. }
  66477. DRWAV_API drwav_result drwav_get_cursor_in_pcm_frames(drwav* pWav, drwav_uint64* pCursor)
  66478. {
  66479. if (pCursor == NULL) {
  66480. return DRWAV_INVALID_ARGS;
  66481. }
  66482. *pCursor = 0;
  66483. if (pWav == NULL) {
  66484. return DRWAV_INVALID_ARGS;
  66485. }
  66486. *pCursor = pWav->readCursorInPCMFrames;
  66487. return DRWAV_SUCCESS;
  66488. }
  66489. DRWAV_API drwav_result drwav_get_length_in_pcm_frames(drwav* pWav, drwav_uint64* pLength)
  66490. {
  66491. if (pLength == NULL) {
  66492. return DRWAV_INVALID_ARGS;
  66493. }
  66494. *pLength = 0;
  66495. if (pWav == NULL) {
  66496. return DRWAV_INVALID_ARGS;
  66497. }
  66498. *pLength = pWav->totalPCMFrameCount;
  66499. return DRWAV_SUCCESS;
  66500. }
  66501. DRWAV_API size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData)
  66502. {
  66503. size_t bytesWritten;
  66504. if (pWav == NULL || bytesToWrite == 0 || pData == NULL) {
  66505. return 0;
  66506. }
  66507. bytesWritten = pWav->onWrite(pWav->pUserData, pData, bytesToWrite);
  66508. pWav->dataChunkDataSize += bytesWritten;
  66509. return bytesWritten;
  66510. }
  66511. DRWAV_API drwav_uint64 drwav_write_pcm_frames_le(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
  66512. {
  66513. drwav_uint64 bytesToWrite;
  66514. drwav_uint64 bytesWritten;
  66515. const drwav_uint8* pRunningData;
  66516. if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
  66517. return 0;
  66518. }
  66519. bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
  66520. if (bytesToWrite > DRWAV_SIZE_MAX) {
  66521. return 0;
  66522. }
  66523. bytesWritten = 0;
  66524. pRunningData = (const drwav_uint8*)pData;
  66525. while (bytesToWrite > 0) {
  66526. size_t bytesJustWritten;
  66527. drwav_uint64 bytesToWriteThisIteration;
  66528. bytesToWriteThisIteration = bytesToWrite;
  66529. DRWAV_ASSERT(bytesToWriteThisIteration <= DRWAV_SIZE_MAX);
  66530. bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, pRunningData);
  66531. if (bytesJustWritten == 0) {
  66532. break;
  66533. }
  66534. bytesToWrite -= bytesJustWritten;
  66535. bytesWritten += bytesJustWritten;
  66536. pRunningData += bytesJustWritten;
  66537. }
  66538. return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
  66539. }
  66540. DRWAV_API drwav_uint64 drwav_write_pcm_frames_be(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
  66541. {
  66542. drwav_uint64 bytesToWrite;
  66543. drwav_uint64 bytesWritten;
  66544. drwav_uint32 bytesPerSample;
  66545. const drwav_uint8* pRunningData;
  66546. if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
  66547. return 0;
  66548. }
  66549. bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
  66550. if (bytesToWrite > DRWAV_SIZE_MAX) {
  66551. return 0;
  66552. }
  66553. bytesWritten = 0;
  66554. pRunningData = (const drwav_uint8*)pData;
  66555. bytesPerSample = drwav_get_bytes_per_pcm_frame(pWav) / pWav->channels;
  66556. if (bytesPerSample == 0) {
  66557. return 0;
  66558. }
  66559. while (bytesToWrite > 0) {
  66560. drwav_uint8 temp[4096];
  66561. drwav_uint32 sampleCount;
  66562. size_t bytesJustWritten;
  66563. drwav_uint64 bytesToWriteThisIteration;
  66564. bytesToWriteThisIteration = bytesToWrite;
  66565. DRWAV_ASSERT(bytesToWriteThisIteration <= DRWAV_SIZE_MAX);
  66566. sampleCount = sizeof(temp)/bytesPerSample;
  66567. if (bytesToWriteThisIteration > ((drwav_uint64)sampleCount)*bytesPerSample) {
  66568. bytesToWriteThisIteration = ((drwav_uint64)sampleCount)*bytesPerSample;
  66569. }
  66570. DRWAV_COPY_MEMORY(temp, pRunningData, (size_t)bytesToWriteThisIteration);
  66571. drwav__bswap_samples(temp, sampleCount, bytesPerSample, pWav->translatedFormatTag);
  66572. bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, temp);
  66573. if (bytesJustWritten == 0) {
  66574. break;
  66575. }
  66576. bytesToWrite -= bytesJustWritten;
  66577. bytesWritten += bytesJustWritten;
  66578. pRunningData += bytesJustWritten;
  66579. }
  66580. return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
  66581. }
  66582. DRWAV_API drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
  66583. {
  66584. if (drwav__is_little_endian()) {
  66585. return drwav_write_pcm_frames_le(pWav, framesToWrite, pData);
  66586. } else {
  66587. return drwav_write_pcm_frames_be(pWav, framesToWrite, pData);
  66588. }
  66589. }
  66590. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  66591. {
  66592. drwav_uint64 totalFramesRead = 0;
  66593. DRWAV_ASSERT(pWav != NULL);
  66594. DRWAV_ASSERT(framesToRead > 0);
  66595. while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  66596. DRWAV_ASSERT(framesToRead > 0);
  66597. if (pWav->msadpcm.cachedFrameCount == 0 && pWav->msadpcm.bytesRemainingInBlock == 0) {
  66598. if (pWav->channels == 1) {
  66599. drwav_uint8 header[7];
  66600. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  66601. return totalFramesRead;
  66602. }
  66603. pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  66604. pWav->msadpcm.predictor[0] = header[0];
  66605. pWav->msadpcm.delta[0] = drwav_bytes_to_s16(header + 1);
  66606. pWav->msadpcm.prevFrames[0][1] = (drwav_int32)drwav_bytes_to_s16(header + 3);
  66607. pWav->msadpcm.prevFrames[0][0] = (drwav_int32)drwav_bytes_to_s16(header + 5);
  66608. pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][0];
  66609. pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[0][1];
  66610. pWav->msadpcm.cachedFrameCount = 2;
  66611. } else {
  66612. drwav_uint8 header[14];
  66613. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  66614. return totalFramesRead;
  66615. }
  66616. pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  66617. pWav->msadpcm.predictor[0] = header[0];
  66618. pWav->msadpcm.predictor[1] = header[1];
  66619. pWav->msadpcm.delta[0] = drwav_bytes_to_s16(header + 2);
  66620. pWav->msadpcm.delta[1] = drwav_bytes_to_s16(header + 4);
  66621. pWav->msadpcm.prevFrames[0][1] = (drwav_int32)drwav_bytes_to_s16(header + 6);
  66622. pWav->msadpcm.prevFrames[1][1] = (drwav_int32)drwav_bytes_to_s16(header + 8);
  66623. pWav->msadpcm.prevFrames[0][0] = (drwav_int32)drwav_bytes_to_s16(header + 10);
  66624. pWav->msadpcm.prevFrames[1][0] = (drwav_int32)drwav_bytes_to_s16(header + 12);
  66625. pWav->msadpcm.cachedFrames[0] = pWav->msadpcm.prevFrames[0][0];
  66626. pWav->msadpcm.cachedFrames[1] = pWav->msadpcm.prevFrames[1][0];
  66627. pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][1];
  66628. pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[1][1];
  66629. pWav->msadpcm.cachedFrameCount = 2;
  66630. }
  66631. }
  66632. while (framesToRead > 0 && pWav->msadpcm.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  66633. if (pBufferOut != NULL) {
  66634. drwav_uint32 iSample = 0;
  66635. for (iSample = 0; iSample < pWav->channels; iSample += 1) {
  66636. pBufferOut[iSample] = (drwav_int16)pWav->msadpcm.cachedFrames[(drwav_countof(pWav->msadpcm.cachedFrames) - (pWav->msadpcm.cachedFrameCount*pWav->channels)) + iSample];
  66637. }
  66638. pBufferOut += pWav->channels;
  66639. }
  66640. framesToRead -= 1;
  66641. totalFramesRead += 1;
  66642. pWav->readCursorInPCMFrames += 1;
  66643. pWav->msadpcm.cachedFrameCount -= 1;
  66644. }
  66645. if (framesToRead == 0) {
  66646. break;
  66647. }
  66648. if (pWav->msadpcm.cachedFrameCount == 0) {
  66649. if (pWav->msadpcm.bytesRemainingInBlock == 0) {
  66650. continue;
  66651. } else {
  66652. static drwav_int32 adaptationTable[] = {
  66653. 230, 230, 230, 230, 307, 409, 512, 614,
  66654. 768, 614, 512, 409, 307, 230, 230, 230
  66655. };
  66656. static drwav_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 };
  66657. static drwav_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 };
  66658. drwav_uint8 nibbles;
  66659. drwav_int32 nibble0;
  66660. drwav_int32 nibble1;
  66661. if (pWav->onRead(pWav->pUserData, &nibbles, 1) != 1) {
  66662. return totalFramesRead;
  66663. }
  66664. pWav->msadpcm.bytesRemainingInBlock -= 1;
  66665. nibble0 = ((nibbles & 0xF0) >> 4); if ((nibbles & 0x80)) { nibble0 |= 0xFFFFFFF0UL; }
  66666. nibble1 = ((nibbles & 0x0F) >> 0); if ((nibbles & 0x08)) { nibble1 |= 0xFFFFFFF0UL; }
  66667. if (pWav->channels == 1) {
  66668. drwav_int32 newSample0;
  66669. drwav_int32 newSample1;
  66670. newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  66671. newSample0 += nibble0 * pWav->msadpcm.delta[0];
  66672. newSample0 = drwav_clamp(newSample0, -32768, 32767);
  66673. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
  66674. if (pWav->msadpcm.delta[0] < 16) {
  66675. pWav->msadpcm.delta[0] = 16;
  66676. }
  66677. pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
  66678. pWav->msadpcm.prevFrames[0][1] = newSample0;
  66679. newSample1 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  66680. newSample1 += nibble1 * pWav->msadpcm.delta[0];
  66681. newSample1 = drwav_clamp(newSample1, -32768, 32767);
  66682. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[0]) >> 8;
  66683. if (pWav->msadpcm.delta[0] < 16) {
  66684. pWav->msadpcm.delta[0] = 16;
  66685. }
  66686. pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
  66687. pWav->msadpcm.prevFrames[0][1] = newSample1;
  66688. pWav->msadpcm.cachedFrames[2] = newSample0;
  66689. pWav->msadpcm.cachedFrames[3] = newSample1;
  66690. pWav->msadpcm.cachedFrameCount = 2;
  66691. } else {
  66692. drwav_int32 newSample0;
  66693. drwav_int32 newSample1;
  66694. newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  66695. newSample0 += nibble0 * pWav->msadpcm.delta[0];
  66696. newSample0 = drwav_clamp(newSample0, -32768, 32767);
  66697. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
  66698. if (pWav->msadpcm.delta[0] < 16) {
  66699. pWav->msadpcm.delta[0] = 16;
  66700. }
  66701. pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
  66702. pWav->msadpcm.prevFrames[0][1] = newSample0;
  66703. newSample1 = ((pWav->msadpcm.prevFrames[1][1] * coeff1Table[pWav->msadpcm.predictor[1]]) + (pWav->msadpcm.prevFrames[1][0] * coeff2Table[pWav->msadpcm.predictor[1]])) >> 8;
  66704. newSample1 += nibble1 * pWav->msadpcm.delta[1];
  66705. newSample1 = drwav_clamp(newSample1, -32768, 32767);
  66706. pWav->msadpcm.delta[1] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[1]) >> 8;
  66707. if (pWav->msadpcm.delta[1] < 16) {
  66708. pWav->msadpcm.delta[1] = 16;
  66709. }
  66710. pWav->msadpcm.prevFrames[1][0] = pWav->msadpcm.prevFrames[1][1];
  66711. pWav->msadpcm.prevFrames[1][1] = newSample1;
  66712. pWav->msadpcm.cachedFrames[2] = newSample0;
  66713. pWav->msadpcm.cachedFrames[3] = newSample1;
  66714. pWav->msadpcm.cachedFrameCount = 1;
  66715. }
  66716. }
  66717. }
  66718. }
  66719. return totalFramesRead;
  66720. }
  66721. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ima(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  66722. {
  66723. drwav_uint64 totalFramesRead = 0;
  66724. drwav_uint32 iChannel;
  66725. static drwav_int32 indexTable[16] = {
  66726. -1, -1, -1, -1, 2, 4, 6, 8,
  66727. -1, -1, -1, -1, 2, 4, 6, 8
  66728. };
  66729. static drwav_int32 stepTable[89] = {
  66730. 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
  66731. 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
  66732. 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
  66733. 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
  66734. 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
  66735. 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
  66736. 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
  66737. 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
  66738. 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
  66739. };
  66740. DRWAV_ASSERT(pWav != NULL);
  66741. DRWAV_ASSERT(framesToRead > 0);
  66742. while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  66743. DRWAV_ASSERT(framesToRead > 0);
  66744. if (pWav->ima.cachedFrameCount == 0 && pWav->ima.bytesRemainingInBlock == 0) {
  66745. if (pWav->channels == 1) {
  66746. drwav_uint8 header[4];
  66747. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  66748. return totalFramesRead;
  66749. }
  66750. pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  66751. if (header[2] >= drwav_countof(stepTable)) {
  66752. pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, drwav_seek_origin_current);
  66753. pWav->ima.bytesRemainingInBlock = 0;
  66754. return totalFramesRead;
  66755. }
  66756. pWav->ima.predictor[0] = drwav_bytes_to_s16(header + 0);
  66757. pWav->ima.stepIndex[0] = drwav_clamp(header[2], 0, (drwav_int32)drwav_countof(stepTable)-1);
  66758. pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[0];
  66759. pWav->ima.cachedFrameCount = 1;
  66760. } else {
  66761. drwav_uint8 header[8];
  66762. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  66763. return totalFramesRead;
  66764. }
  66765. pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  66766. if (header[2] >= drwav_countof(stepTable) || header[6] >= drwav_countof(stepTable)) {
  66767. pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, drwav_seek_origin_current);
  66768. pWav->ima.bytesRemainingInBlock = 0;
  66769. return totalFramesRead;
  66770. }
  66771. pWav->ima.predictor[0] = drwav_bytes_to_s16(header + 0);
  66772. pWav->ima.stepIndex[0] = drwav_clamp(header[2], 0, (drwav_int32)drwav_countof(stepTable)-1);
  66773. pWav->ima.predictor[1] = drwav_bytes_to_s16(header + 4);
  66774. pWav->ima.stepIndex[1] = drwav_clamp(header[6], 0, (drwav_int32)drwav_countof(stepTable)-1);
  66775. pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 2] = pWav->ima.predictor[0];
  66776. pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[1];
  66777. pWav->ima.cachedFrameCount = 1;
  66778. }
  66779. }
  66780. while (framesToRead > 0 && pWav->ima.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  66781. if (pBufferOut != NULL) {
  66782. drwav_uint32 iSample;
  66783. for (iSample = 0; iSample < pWav->channels; iSample += 1) {
  66784. pBufferOut[iSample] = (drwav_int16)pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + iSample];
  66785. }
  66786. pBufferOut += pWav->channels;
  66787. }
  66788. framesToRead -= 1;
  66789. totalFramesRead += 1;
  66790. pWav->readCursorInPCMFrames += 1;
  66791. pWav->ima.cachedFrameCount -= 1;
  66792. }
  66793. if (framesToRead == 0) {
  66794. break;
  66795. }
  66796. if (pWav->ima.cachedFrameCount == 0) {
  66797. if (pWav->ima.bytesRemainingInBlock == 0) {
  66798. continue;
  66799. } else {
  66800. pWav->ima.cachedFrameCount = 8;
  66801. for (iChannel = 0; iChannel < pWav->channels; ++iChannel) {
  66802. drwav_uint32 iByte;
  66803. drwav_uint8 nibbles[4];
  66804. if (pWav->onRead(pWav->pUserData, &nibbles, 4) != 4) {
  66805. pWav->ima.cachedFrameCount = 0;
  66806. return totalFramesRead;
  66807. }
  66808. pWav->ima.bytesRemainingInBlock -= 4;
  66809. for (iByte = 0; iByte < 4; ++iByte) {
  66810. drwav_uint8 nibble0 = ((nibbles[iByte] & 0x0F) >> 0);
  66811. drwav_uint8 nibble1 = ((nibbles[iByte] & 0xF0) >> 4);
  66812. drwav_int32 step = stepTable[pWav->ima.stepIndex[iChannel]];
  66813. drwav_int32 predictor = pWav->ima.predictor[iChannel];
  66814. drwav_int32 diff = step >> 3;
  66815. if (nibble0 & 1) diff += step >> 2;
  66816. if (nibble0 & 2) diff += step >> 1;
  66817. if (nibble0 & 4) diff += step;
  66818. if (nibble0 & 8) diff = -diff;
  66819. predictor = drwav_clamp(predictor + diff, -32768, 32767);
  66820. pWav->ima.predictor[iChannel] = predictor;
  66821. pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble0], 0, (drwav_int32)drwav_countof(stepTable)-1);
  66822. pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+0)*pWav->channels + iChannel] = predictor;
  66823. step = stepTable[pWav->ima.stepIndex[iChannel]];
  66824. predictor = pWav->ima.predictor[iChannel];
  66825. diff = step >> 3;
  66826. if (nibble1 & 1) diff += step >> 2;
  66827. if (nibble1 & 2) diff += step >> 1;
  66828. if (nibble1 & 4) diff += step;
  66829. if (nibble1 & 8) diff = -diff;
  66830. predictor = drwav_clamp(predictor + diff, -32768, 32767);
  66831. pWav->ima.predictor[iChannel] = predictor;
  66832. pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble1], 0, (drwav_int32)drwav_countof(stepTable)-1);
  66833. pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+1)*pWav->channels + iChannel] = predictor;
  66834. }
  66835. }
  66836. }
  66837. }
  66838. }
  66839. return totalFramesRead;
  66840. }
  66841. #ifndef DR_WAV_NO_CONVERSION_API
  66842. static unsigned short g_drwavAlawTable[256] = {
  66843. 0xEA80, 0xEB80, 0xE880, 0xE980, 0xEE80, 0xEF80, 0xEC80, 0xED80, 0xE280, 0xE380, 0xE080, 0xE180, 0xE680, 0xE780, 0xE480, 0xE580,
  66844. 0xF540, 0xF5C0, 0xF440, 0xF4C0, 0xF740, 0xF7C0, 0xF640, 0xF6C0, 0xF140, 0xF1C0, 0xF040, 0xF0C0, 0xF340, 0xF3C0, 0xF240, 0xF2C0,
  66845. 0xAA00, 0xAE00, 0xA200, 0xA600, 0xBA00, 0xBE00, 0xB200, 0xB600, 0x8A00, 0x8E00, 0x8200, 0x8600, 0x9A00, 0x9E00, 0x9200, 0x9600,
  66846. 0xD500, 0xD700, 0xD100, 0xD300, 0xDD00, 0xDF00, 0xD900, 0xDB00, 0xC500, 0xC700, 0xC100, 0xC300, 0xCD00, 0xCF00, 0xC900, 0xCB00,
  66847. 0xFEA8, 0xFEB8, 0xFE88, 0xFE98, 0xFEE8, 0xFEF8, 0xFEC8, 0xFED8, 0xFE28, 0xFE38, 0xFE08, 0xFE18, 0xFE68, 0xFE78, 0xFE48, 0xFE58,
  66848. 0xFFA8, 0xFFB8, 0xFF88, 0xFF98, 0xFFE8, 0xFFF8, 0xFFC8, 0xFFD8, 0xFF28, 0xFF38, 0xFF08, 0xFF18, 0xFF68, 0xFF78, 0xFF48, 0xFF58,
  66849. 0xFAA0, 0xFAE0, 0xFA20, 0xFA60, 0xFBA0, 0xFBE0, 0xFB20, 0xFB60, 0xF8A0, 0xF8E0, 0xF820, 0xF860, 0xF9A0, 0xF9E0, 0xF920, 0xF960,
  66850. 0xFD50, 0xFD70, 0xFD10, 0xFD30, 0xFDD0, 0xFDF0, 0xFD90, 0xFDB0, 0xFC50, 0xFC70, 0xFC10, 0xFC30, 0xFCD0, 0xFCF0, 0xFC90, 0xFCB0,
  66851. 0x1580, 0x1480, 0x1780, 0x1680, 0x1180, 0x1080, 0x1380, 0x1280, 0x1D80, 0x1C80, 0x1F80, 0x1E80, 0x1980, 0x1880, 0x1B80, 0x1A80,
  66852. 0x0AC0, 0x0A40, 0x0BC0, 0x0B40, 0x08C0, 0x0840, 0x09C0, 0x0940, 0x0EC0, 0x0E40, 0x0FC0, 0x0F40, 0x0CC0, 0x0C40, 0x0DC0, 0x0D40,
  66853. 0x5600, 0x5200, 0x5E00, 0x5A00, 0x4600, 0x4200, 0x4E00, 0x4A00, 0x7600, 0x7200, 0x7E00, 0x7A00, 0x6600, 0x6200, 0x6E00, 0x6A00,
  66854. 0x2B00, 0x2900, 0x2F00, 0x2D00, 0x2300, 0x2100, 0x2700, 0x2500, 0x3B00, 0x3900, 0x3F00, 0x3D00, 0x3300, 0x3100, 0x3700, 0x3500,
  66855. 0x0158, 0x0148, 0x0178, 0x0168, 0x0118, 0x0108, 0x0138, 0x0128, 0x01D8, 0x01C8, 0x01F8, 0x01E8, 0x0198, 0x0188, 0x01B8, 0x01A8,
  66856. 0x0058, 0x0048, 0x0078, 0x0068, 0x0018, 0x0008, 0x0038, 0x0028, 0x00D8, 0x00C8, 0x00F8, 0x00E8, 0x0098, 0x0088, 0x00B8, 0x00A8,
  66857. 0x0560, 0x0520, 0x05E0, 0x05A0, 0x0460, 0x0420, 0x04E0, 0x04A0, 0x0760, 0x0720, 0x07E0, 0x07A0, 0x0660, 0x0620, 0x06E0, 0x06A0,
  66858. 0x02B0, 0x0290, 0x02F0, 0x02D0, 0x0230, 0x0210, 0x0270, 0x0250, 0x03B0, 0x0390, 0x03F0, 0x03D0, 0x0330, 0x0310, 0x0370, 0x0350
  66859. };
  66860. static unsigned short g_drwavMulawTable[256] = {
  66861. 0x8284, 0x8684, 0x8A84, 0x8E84, 0x9284, 0x9684, 0x9A84, 0x9E84, 0xA284, 0xA684, 0xAA84, 0xAE84, 0xB284, 0xB684, 0xBA84, 0xBE84,
  66862. 0xC184, 0xC384, 0xC584, 0xC784, 0xC984, 0xCB84, 0xCD84, 0xCF84, 0xD184, 0xD384, 0xD584, 0xD784, 0xD984, 0xDB84, 0xDD84, 0xDF84,
  66863. 0xE104, 0xE204, 0xE304, 0xE404, 0xE504, 0xE604, 0xE704, 0xE804, 0xE904, 0xEA04, 0xEB04, 0xEC04, 0xED04, 0xEE04, 0xEF04, 0xF004,
  66864. 0xF0C4, 0xF144, 0xF1C4, 0xF244, 0xF2C4, 0xF344, 0xF3C4, 0xF444, 0xF4C4, 0xF544, 0xF5C4, 0xF644, 0xF6C4, 0xF744, 0xF7C4, 0xF844,
  66865. 0xF8A4, 0xF8E4, 0xF924, 0xF964, 0xF9A4, 0xF9E4, 0xFA24, 0xFA64, 0xFAA4, 0xFAE4, 0xFB24, 0xFB64, 0xFBA4, 0xFBE4, 0xFC24, 0xFC64,
  66866. 0xFC94, 0xFCB4, 0xFCD4, 0xFCF4, 0xFD14, 0xFD34, 0xFD54, 0xFD74, 0xFD94, 0xFDB4, 0xFDD4, 0xFDF4, 0xFE14, 0xFE34, 0xFE54, 0xFE74,
  66867. 0xFE8C, 0xFE9C, 0xFEAC, 0xFEBC, 0xFECC, 0xFEDC, 0xFEEC, 0xFEFC, 0xFF0C, 0xFF1C, 0xFF2C, 0xFF3C, 0xFF4C, 0xFF5C, 0xFF6C, 0xFF7C,
  66868. 0xFF88, 0xFF90, 0xFF98, 0xFFA0, 0xFFA8, 0xFFB0, 0xFFB8, 0xFFC0, 0xFFC8, 0xFFD0, 0xFFD8, 0xFFE0, 0xFFE8, 0xFFF0, 0xFFF8, 0x0000,
  66869. 0x7D7C, 0x797C, 0x757C, 0x717C, 0x6D7C, 0x697C, 0x657C, 0x617C, 0x5D7C, 0x597C, 0x557C, 0x517C, 0x4D7C, 0x497C, 0x457C, 0x417C,
  66870. 0x3E7C, 0x3C7C, 0x3A7C, 0x387C, 0x367C, 0x347C, 0x327C, 0x307C, 0x2E7C, 0x2C7C, 0x2A7C, 0x287C, 0x267C, 0x247C, 0x227C, 0x207C,
  66871. 0x1EFC, 0x1DFC, 0x1CFC, 0x1BFC, 0x1AFC, 0x19FC, 0x18FC, 0x17FC, 0x16FC, 0x15FC, 0x14FC, 0x13FC, 0x12FC, 0x11FC, 0x10FC, 0x0FFC,
  66872. 0x0F3C, 0x0EBC, 0x0E3C, 0x0DBC, 0x0D3C, 0x0CBC, 0x0C3C, 0x0BBC, 0x0B3C, 0x0ABC, 0x0A3C, 0x09BC, 0x093C, 0x08BC, 0x083C, 0x07BC,
  66873. 0x075C, 0x071C, 0x06DC, 0x069C, 0x065C, 0x061C, 0x05DC, 0x059C, 0x055C, 0x051C, 0x04DC, 0x049C, 0x045C, 0x041C, 0x03DC, 0x039C,
  66874. 0x036C, 0x034C, 0x032C, 0x030C, 0x02EC, 0x02CC, 0x02AC, 0x028C, 0x026C, 0x024C, 0x022C, 0x020C, 0x01EC, 0x01CC, 0x01AC, 0x018C,
  66875. 0x0174, 0x0164, 0x0154, 0x0144, 0x0134, 0x0124, 0x0114, 0x0104, 0x00F4, 0x00E4, 0x00D4, 0x00C4, 0x00B4, 0x00A4, 0x0094, 0x0084,
  66876. 0x0078, 0x0070, 0x0068, 0x0060, 0x0058, 0x0050, 0x0048, 0x0040, 0x0038, 0x0030, 0x0028, 0x0020, 0x0018, 0x0010, 0x0008, 0x0000
  66877. };
  66878. static DRWAV_INLINE drwav_int16 drwav__alaw_to_s16(drwav_uint8 sampleIn)
  66879. {
  66880. return (short)g_drwavAlawTable[sampleIn];
  66881. }
  66882. static DRWAV_INLINE drwav_int16 drwav__mulaw_to_s16(drwav_uint8 sampleIn)
  66883. {
  66884. return (short)g_drwavMulawTable[sampleIn];
  66885. }
  66886. DRWAV_PRIVATE void drwav__pcm_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  66887. {
  66888. size_t i;
  66889. if (bytesPerSample == 1) {
  66890. drwav_u8_to_s16(pOut, pIn, totalSampleCount);
  66891. return;
  66892. }
  66893. if (bytesPerSample == 2) {
  66894. for (i = 0; i < totalSampleCount; ++i) {
  66895. *pOut++ = ((const drwav_int16*)pIn)[i];
  66896. }
  66897. return;
  66898. }
  66899. if (bytesPerSample == 3) {
  66900. drwav_s24_to_s16(pOut, pIn, totalSampleCount);
  66901. return;
  66902. }
  66903. if (bytesPerSample == 4) {
  66904. drwav_s32_to_s16(pOut, (const drwav_int32*)pIn, totalSampleCount);
  66905. return;
  66906. }
  66907. if (bytesPerSample > 8) {
  66908. DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  66909. return;
  66910. }
  66911. for (i = 0; i < totalSampleCount; ++i) {
  66912. drwav_uint64 sample = 0;
  66913. unsigned int shift = (8 - bytesPerSample) * 8;
  66914. unsigned int j;
  66915. for (j = 0; j < bytesPerSample; j += 1) {
  66916. DRWAV_ASSERT(j < 8);
  66917. sample |= (drwav_uint64)(pIn[j]) << shift;
  66918. shift += 8;
  66919. }
  66920. pIn += j;
  66921. *pOut++ = (drwav_int16)((drwav_int64)sample >> 48);
  66922. }
  66923. }
  66924. DRWAV_PRIVATE void drwav__ieee_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  66925. {
  66926. if (bytesPerSample == 4) {
  66927. drwav_f32_to_s16(pOut, (const float*)pIn, totalSampleCount);
  66928. return;
  66929. } else if (bytesPerSample == 8) {
  66930. drwav_f64_to_s16(pOut, (const double*)pIn, totalSampleCount);
  66931. return;
  66932. } else {
  66933. DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  66934. return;
  66935. }
  66936. }
  66937. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__pcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  66938. {
  66939. drwav_uint64 totalFramesRead;
  66940. drwav_uint8 sampleData[4096] = {0};
  66941. drwav_uint32 bytesPerFrame;
  66942. drwav_uint32 bytesPerSample;
  66943. drwav_uint64 samplesRead;
  66944. if ((pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 16) || pBufferOut == NULL) {
  66945. return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
  66946. }
  66947. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  66948. if (bytesPerFrame == 0) {
  66949. return 0;
  66950. }
  66951. bytesPerSample = bytesPerFrame / pWav->channels;
  66952. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  66953. return 0;
  66954. }
  66955. totalFramesRead = 0;
  66956. while (framesToRead > 0) {
  66957. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  66958. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  66959. if (framesRead == 0) {
  66960. break;
  66961. }
  66962. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  66963. samplesRead = framesRead * pWav->channels;
  66964. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  66965. DRWAV_ASSERT(DRWAV_FALSE);
  66966. break;
  66967. }
  66968. drwav__pcm_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  66969. pBufferOut += samplesRead;
  66970. framesToRead -= framesRead;
  66971. totalFramesRead += framesRead;
  66972. }
  66973. return totalFramesRead;
  66974. }
  66975. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ieee(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  66976. {
  66977. drwav_uint64 totalFramesRead;
  66978. drwav_uint8 sampleData[4096] = {0};
  66979. drwav_uint32 bytesPerFrame;
  66980. drwav_uint32 bytesPerSample;
  66981. drwav_uint64 samplesRead;
  66982. if (pBufferOut == NULL) {
  66983. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  66984. }
  66985. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  66986. if (bytesPerFrame == 0) {
  66987. return 0;
  66988. }
  66989. bytesPerSample = bytesPerFrame / pWav->channels;
  66990. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  66991. return 0;
  66992. }
  66993. totalFramesRead = 0;
  66994. while (framesToRead > 0) {
  66995. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  66996. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  66997. if (framesRead == 0) {
  66998. break;
  66999. }
  67000. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67001. samplesRead = framesRead * pWav->channels;
  67002. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67003. DRWAV_ASSERT(DRWAV_FALSE);
  67004. break;
  67005. }
  67006. drwav__ieee_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67007. pBufferOut += samplesRead;
  67008. framesToRead -= framesRead;
  67009. totalFramesRead += framesRead;
  67010. }
  67011. return totalFramesRead;
  67012. }
  67013. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__alaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  67014. {
  67015. drwav_uint64 totalFramesRead;
  67016. drwav_uint8 sampleData[4096] = {0};
  67017. drwav_uint32 bytesPerFrame;
  67018. drwav_uint32 bytesPerSample;
  67019. drwav_uint64 samplesRead;
  67020. if (pBufferOut == NULL) {
  67021. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  67022. }
  67023. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67024. if (bytesPerFrame == 0) {
  67025. return 0;
  67026. }
  67027. bytesPerSample = bytesPerFrame / pWav->channels;
  67028. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67029. return 0;
  67030. }
  67031. totalFramesRead = 0;
  67032. while (framesToRead > 0) {
  67033. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67034. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67035. if (framesRead == 0) {
  67036. break;
  67037. }
  67038. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67039. samplesRead = framesRead * pWav->channels;
  67040. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67041. DRWAV_ASSERT(DRWAV_FALSE);
  67042. break;
  67043. }
  67044. drwav_alaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
  67045. pBufferOut += samplesRead;
  67046. framesToRead -= framesRead;
  67047. totalFramesRead += framesRead;
  67048. }
  67049. return totalFramesRead;
  67050. }
  67051. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__mulaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  67052. {
  67053. drwav_uint64 totalFramesRead;
  67054. drwav_uint8 sampleData[4096] = {0};
  67055. drwav_uint32 bytesPerFrame;
  67056. drwav_uint32 bytesPerSample;
  67057. drwav_uint64 samplesRead;
  67058. if (pBufferOut == NULL) {
  67059. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  67060. }
  67061. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67062. if (bytesPerFrame == 0) {
  67063. return 0;
  67064. }
  67065. bytesPerSample = bytesPerFrame / pWav->channels;
  67066. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67067. return 0;
  67068. }
  67069. totalFramesRead = 0;
  67070. while (framesToRead > 0) {
  67071. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67072. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67073. if (framesRead == 0) {
  67074. break;
  67075. }
  67076. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67077. samplesRead = framesRead * pWav->channels;
  67078. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67079. DRWAV_ASSERT(DRWAV_FALSE);
  67080. break;
  67081. }
  67082. drwav_mulaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
  67083. pBufferOut += samplesRead;
  67084. framesToRead -= framesRead;
  67085. totalFramesRead += framesRead;
  67086. }
  67087. return totalFramesRead;
  67088. }
  67089. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  67090. {
  67091. if (pWav == NULL || framesToRead == 0) {
  67092. return 0;
  67093. }
  67094. if (pBufferOut == NULL) {
  67095. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  67096. }
  67097. if (framesToRead * pWav->channels * sizeof(drwav_int16) > DRWAV_SIZE_MAX) {
  67098. framesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int16) / pWav->channels;
  67099. }
  67100. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
  67101. return drwav_read_pcm_frames_s16__pcm(pWav, framesToRead, pBufferOut);
  67102. }
  67103. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
  67104. return drwav_read_pcm_frames_s16__ieee(pWav, framesToRead, pBufferOut);
  67105. }
  67106. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
  67107. return drwav_read_pcm_frames_s16__alaw(pWav, framesToRead, pBufferOut);
  67108. }
  67109. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  67110. return drwav_read_pcm_frames_s16__mulaw(pWav, framesToRead, pBufferOut);
  67111. }
  67112. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  67113. return drwav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, pBufferOut);
  67114. }
  67115. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  67116. return drwav_read_pcm_frames_s16__ima(pWav, framesToRead, pBufferOut);
  67117. }
  67118. return 0;
  67119. }
  67120. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16le(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  67121. {
  67122. drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
  67123. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
  67124. drwav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
  67125. }
  67126. return framesRead;
  67127. }
  67128. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16be(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  67129. {
  67130. drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
  67131. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
  67132. drwav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
  67133. }
  67134. return framesRead;
  67135. }
  67136. DRWAV_API void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67137. {
  67138. int r;
  67139. size_t i;
  67140. for (i = 0; i < sampleCount; ++i) {
  67141. int x = pIn[i];
  67142. r = x << 8;
  67143. r = r - 32768;
  67144. pOut[i] = (short)r;
  67145. }
  67146. }
  67147. DRWAV_API void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67148. {
  67149. int r;
  67150. size_t i;
  67151. for (i = 0; i < sampleCount; ++i) {
  67152. int x = ((int)(((unsigned int)(((const drwav_uint8*)pIn)[i*3+0]) << 8) | ((unsigned int)(((const drwav_uint8*)pIn)[i*3+1]) << 16) | ((unsigned int)(((const drwav_uint8*)pIn)[i*3+2])) << 24)) >> 8;
  67153. r = x >> 8;
  67154. pOut[i] = (short)r;
  67155. }
  67156. }
  67157. DRWAV_API void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount)
  67158. {
  67159. int r;
  67160. size_t i;
  67161. for (i = 0; i < sampleCount; ++i) {
  67162. int x = pIn[i];
  67163. r = x >> 16;
  67164. pOut[i] = (short)r;
  67165. }
  67166. }
  67167. DRWAV_API void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount)
  67168. {
  67169. int r;
  67170. size_t i;
  67171. for (i = 0; i < sampleCount; ++i) {
  67172. float x = pIn[i];
  67173. float c;
  67174. c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  67175. c = c + 1;
  67176. r = (int)(c * 32767.5f);
  67177. r = r - 32768;
  67178. pOut[i] = (short)r;
  67179. }
  67180. }
  67181. DRWAV_API void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount)
  67182. {
  67183. int r;
  67184. size_t i;
  67185. for (i = 0; i < sampleCount; ++i) {
  67186. double x = pIn[i];
  67187. double c;
  67188. c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  67189. c = c + 1;
  67190. r = (int)(c * 32767.5);
  67191. r = r - 32768;
  67192. pOut[i] = (short)r;
  67193. }
  67194. }
  67195. DRWAV_API void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67196. {
  67197. size_t i;
  67198. for (i = 0; i < sampleCount; ++i) {
  67199. pOut[i] = drwav__alaw_to_s16(pIn[i]);
  67200. }
  67201. }
  67202. DRWAV_API void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67203. {
  67204. size_t i;
  67205. for (i = 0; i < sampleCount; ++i) {
  67206. pOut[i] = drwav__mulaw_to_s16(pIn[i]);
  67207. }
  67208. }
  67209. DRWAV_PRIVATE void drwav__pcm_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
  67210. {
  67211. unsigned int i;
  67212. if (bytesPerSample == 1) {
  67213. drwav_u8_to_f32(pOut, pIn, sampleCount);
  67214. return;
  67215. }
  67216. if (bytesPerSample == 2) {
  67217. drwav_s16_to_f32(pOut, (const drwav_int16*)pIn, sampleCount);
  67218. return;
  67219. }
  67220. if (bytesPerSample == 3) {
  67221. drwav_s24_to_f32(pOut, pIn, sampleCount);
  67222. return;
  67223. }
  67224. if (bytesPerSample == 4) {
  67225. drwav_s32_to_f32(pOut, (const drwav_int32*)pIn, sampleCount);
  67226. return;
  67227. }
  67228. if (bytesPerSample > 8) {
  67229. DRWAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
  67230. return;
  67231. }
  67232. for (i = 0; i < sampleCount; ++i) {
  67233. drwav_uint64 sample = 0;
  67234. unsigned int shift = (8 - bytesPerSample) * 8;
  67235. unsigned int j;
  67236. for (j = 0; j < bytesPerSample; j += 1) {
  67237. DRWAV_ASSERT(j < 8);
  67238. sample |= (drwav_uint64)(pIn[j]) << shift;
  67239. shift += 8;
  67240. }
  67241. pIn += j;
  67242. *pOut++ = (float)((drwav_int64)sample / 9223372036854775807.0);
  67243. }
  67244. }
  67245. DRWAV_PRIVATE void drwav__ieee_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
  67246. {
  67247. if (bytesPerSample == 4) {
  67248. unsigned int i;
  67249. for (i = 0; i < sampleCount; ++i) {
  67250. *pOut++ = ((const float*)pIn)[i];
  67251. }
  67252. return;
  67253. } else if (bytesPerSample == 8) {
  67254. drwav_f64_to_f32(pOut, (const double*)pIn, sampleCount);
  67255. return;
  67256. } else {
  67257. DRWAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
  67258. return;
  67259. }
  67260. }
  67261. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__pcm(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  67262. {
  67263. drwav_uint64 totalFramesRead;
  67264. drwav_uint8 sampleData[4096] = {0};
  67265. drwav_uint32 bytesPerFrame;
  67266. drwav_uint32 bytesPerSample;
  67267. drwav_uint64 samplesRead;
  67268. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67269. if (bytesPerFrame == 0) {
  67270. return 0;
  67271. }
  67272. bytesPerSample = bytesPerFrame / pWav->channels;
  67273. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67274. return 0;
  67275. }
  67276. totalFramesRead = 0;
  67277. while (framesToRead > 0) {
  67278. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67279. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67280. if (framesRead == 0) {
  67281. break;
  67282. }
  67283. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67284. samplesRead = framesRead * pWav->channels;
  67285. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67286. DRWAV_ASSERT(DRWAV_FALSE);
  67287. break;
  67288. }
  67289. drwav__pcm_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67290. pBufferOut += samplesRead;
  67291. framesToRead -= framesRead;
  67292. totalFramesRead += framesRead;
  67293. }
  67294. return totalFramesRead;
  67295. }
  67296. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__msadpcm_ima(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  67297. {
  67298. drwav_uint64 totalFramesRead;
  67299. drwav_int16 samples16[2048];
  67300. totalFramesRead = 0;
  67301. while (framesToRead > 0) {
  67302. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels);
  67303. drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16);
  67304. if (framesRead == 0) {
  67305. break;
  67306. }
  67307. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67308. drwav_s16_to_f32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
  67309. pBufferOut += framesRead*pWav->channels;
  67310. framesToRead -= framesRead;
  67311. totalFramesRead += framesRead;
  67312. }
  67313. return totalFramesRead;
  67314. }
  67315. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__ieee(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  67316. {
  67317. drwav_uint64 totalFramesRead;
  67318. drwav_uint8 sampleData[4096] = {0};
  67319. drwav_uint32 bytesPerFrame;
  67320. drwav_uint32 bytesPerSample;
  67321. drwav_uint64 samplesRead;
  67322. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT && pWav->bitsPerSample == 32) {
  67323. return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
  67324. }
  67325. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67326. if (bytesPerFrame == 0) {
  67327. return 0;
  67328. }
  67329. bytesPerSample = bytesPerFrame / pWav->channels;
  67330. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67331. return 0;
  67332. }
  67333. totalFramesRead = 0;
  67334. while (framesToRead > 0) {
  67335. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67336. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67337. if (framesRead == 0) {
  67338. break;
  67339. }
  67340. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67341. samplesRead = framesRead * pWav->channels;
  67342. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67343. DRWAV_ASSERT(DRWAV_FALSE);
  67344. break;
  67345. }
  67346. drwav__ieee_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67347. pBufferOut += samplesRead;
  67348. framesToRead -= framesRead;
  67349. totalFramesRead += framesRead;
  67350. }
  67351. return totalFramesRead;
  67352. }
  67353. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__alaw(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  67354. {
  67355. drwav_uint64 totalFramesRead;
  67356. drwav_uint8 sampleData[4096] = {0};
  67357. drwav_uint32 bytesPerFrame;
  67358. drwav_uint32 bytesPerSample;
  67359. drwav_uint64 samplesRead;
  67360. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67361. if (bytesPerFrame == 0) {
  67362. return 0;
  67363. }
  67364. bytesPerSample = bytesPerFrame / pWav->channels;
  67365. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67366. return 0;
  67367. }
  67368. totalFramesRead = 0;
  67369. while (framesToRead > 0) {
  67370. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67371. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67372. if (framesRead == 0) {
  67373. break;
  67374. }
  67375. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67376. samplesRead = framesRead * pWav->channels;
  67377. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67378. DRWAV_ASSERT(DRWAV_FALSE);
  67379. break;
  67380. }
  67381. drwav_alaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
  67382. pBufferOut += samplesRead;
  67383. framesToRead -= framesRead;
  67384. totalFramesRead += framesRead;
  67385. }
  67386. return totalFramesRead;
  67387. }
  67388. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__mulaw(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  67389. {
  67390. drwav_uint64 totalFramesRead;
  67391. drwav_uint8 sampleData[4096] = {0};
  67392. drwav_uint32 bytesPerFrame;
  67393. drwav_uint32 bytesPerSample;
  67394. drwav_uint64 samplesRead;
  67395. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67396. if (bytesPerFrame == 0) {
  67397. return 0;
  67398. }
  67399. bytesPerSample = bytesPerFrame / pWav->channels;
  67400. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67401. return 0;
  67402. }
  67403. totalFramesRead = 0;
  67404. while (framesToRead > 0) {
  67405. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67406. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67407. if (framesRead == 0) {
  67408. break;
  67409. }
  67410. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67411. samplesRead = framesRead * pWav->channels;
  67412. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67413. DRWAV_ASSERT(DRWAV_FALSE);
  67414. break;
  67415. }
  67416. drwav_mulaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
  67417. pBufferOut += samplesRead;
  67418. framesToRead -= framesRead;
  67419. totalFramesRead += framesRead;
  67420. }
  67421. return totalFramesRead;
  67422. }
  67423. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  67424. {
  67425. if (pWav == NULL || framesToRead == 0) {
  67426. return 0;
  67427. }
  67428. if (pBufferOut == NULL) {
  67429. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  67430. }
  67431. if (framesToRead * pWav->channels * sizeof(float) > DRWAV_SIZE_MAX) {
  67432. framesToRead = DRWAV_SIZE_MAX / sizeof(float) / pWav->channels;
  67433. }
  67434. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
  67435. return drwav_read_pcm_frames_f32__pcm(pWav, framesToRead, pBufferOut);
  67436. }
  67437. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  67438. return drwav_read_pcm_frames_f32__msadpcm_ima(pWav, framesToRead, pBufferOut);
  67439. }
  67440. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
  67441. return drwav_read_pcm_frames_f32__ieee(pWav, framesToRead, pBufferOut);
  67442. }
  67443. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
  67444. return drwav_read_pcm_frames_f32__alaw(pWav, framesToRead, pBufferOut);
  67445. }
  67446. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  67447. return drwav_read_pcm_frames_f32__mulaw(pWav, framesToRead, pBufferOut);
  67448. }
  67449. return 0;
  67450. }
  67451. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32le(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  67452. {
  67453. drwav_uint64 framesRead = drwav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
  67454. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
  67455. drwav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
  67456. }
  67457. return framesRead;
  67458. }
  67459. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32be(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  67460. {
  67461. drwav_uint64 framesRead = drwav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
  67462. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
  67463. drwav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
  67464. }
  67465. return framesRead;
  67466. }
  67467. DRWAV_API void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67468. {
  67469. size_t i;
  67470. if (pOut == NULL || pIn == NULL) {
  67471. return;
  67472. }
  67473. #ifdef DR_WAV_LIBSNDFILE_COMPAT
  67474. for (i = 0; i < sampleCount; ++i) {
  67475. *pOut++ = (pIn[i] / 256.0f) * 2 - 1;
  67476. }
  67477. #else
  67478. for (i = 0; i < sampleCount; ++i) {
  67479. float x = pIn[i];
  67480. x = x * 0.00784313725490196078f;
  67481. x = x - 1;
  67482. *pOut++ = x;
  67483. }
  67484. #endif
  67485. }
  67486. DRWAV_API void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount)
  67487. {
  67488. size_t i;
  67489. if (pOut == NULL || pIn == NULL) {
  67490. return;
  67491. }
  67492. for (i = 0; i < sampleCount; ++i) {
  67493. *pOut++ = pIn[i] * 0.000030517578125f;
  67494. }
  67495. }
  67496. DRWAV_API void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67497. {
  67498. size_t i;
  67499. if (pOut == NULL || pIn == NULL) {
  67500. return;
  67501. }
  67502. for (i = 0; i < sampleCount; ++i) {
  67503. double x;
  67504. drwav_uint32 a = ((drwav_uint32)(pIn[i*3+0]) << 8);
  67505. drwav_uint32 b = ((drwav_uint32)(pIn[i*3+1]) << 16);
  67506. drwav_uint32 c = ((drwav_uint32)(pIn[i*3+2]) << 24);
  67507. x = (double)((drwav_int32)(a | b | c) >> 8);
  67508. *pOut++ = (float)(x * 0.00000011920928955078125);
  67509. }
  67510. }
  67511. DRWAV_API void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount)
  67512. {
  67513. size_t i;
  67514. if (pOut == NULL || pIn == NULL) {
  67515. return;
  67516. }
  67517. for (i = 0; i < sampleCount; ++i) {
  67518. *pOut++ = (float)(pIn[i] / 2147483648.0);
  67519. }
  67520. }
  67521. DRWAV_API void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount)
  67522. {
  67523. size_t i;
  67524. if (pOut == NULL || pIn == NULL) {
  67525. return;
  67526. }
  67527. for (i = 0; i < sampleCount; ++i) {
  67528. *pOut++ = (float)pIn[i];
  67529. }
  67530. }
  67531. DRWAV_API void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67532. {
  67533. size_t i;
  67534. if (pOut == NULL || pIn == NULL) {
  67535. return;
  67536. }
  67537. for (i = 0; i < sampleCount; ++i) {
  67538. *pOut++ = drwav__alaw_to_s16(pIn[i]) / 32768.0f;
  67539. }
  67540. }
  67541. DRWAV_API void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67542. {
  67543. size_t i;
  67544. if (pOut == NULL || pIn == NULL) {
  67545. return;
  67546. }
  67547. for (i = 0; i < sampleCount; ++i) {
  67548. *pOut++ = drwav__mulaw_to_s16(pIn[i]) / 32768.0f;
  67549. }
  67550. }
  67551. DRWAV_PRIVATE void drwav__pcm_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  67552. {
  67553. unsigned int i;
  67554. if (bytesPerSample == 1) {
  67555. drwav_u8_to_s32(pOut, pIn, totalSampleCount);
  67556. return;
  67557. }
  67558. if (bytesPerSample == 2) {
  67559. drwav_s16_to_s32(pOut, (const drwav_int16*)pIn, totalSampleCount);
  67560. return;
  67561. }
  67562. if (bytesPerSample == 3) {
  67563. drwav_s24_to_s32(pOut, pIn, totalSampleCount);
  67564. return;
  67565. }
  67566. if (bytesPerSample == 4) {
  67567. for (i = 0; i < totalSampleCount; ++i) {
  67568. *pOut++ = ((const drwav_int32*)pIn)[i];
  67569. }
  67570. return;
  67571. }
  67572. if (bytesPerSample > 8) {
  67573. DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  67574. return;
  67575. }
  67576. for (i = 0; i < totalSampleCount; ++i) {
  67577. drwav_uint64 sample = 0;
  67578. unsigned int shift = (8 - bytesPerSample) * 8;
  67579. unsigned int j;
  67580. for (j = 0; j < bytesPerSample; j += 1) {
  67581. DRWAV_ASSERT(j < 8);
  67582. sample |= (drwav_uint64)(pIn[j]) << shift;
  67583. shift += 8;
  67584. }
  67585. pIn += j;
  67586. *pOut++ = (drwav_int32)((drwav_int64)sample >> 32);
  67587. }
  67588. }
  67589. DRWAV_PRIVATE void drwav__ieee_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  67590. {
  67591. if (bytesPerSample == 4) {
  67592. drwav_f32_to_s32(pOut, (const float*)pIn, totalSampleCount);
  67593. return;
  67594. } else if (bytesPerSample == 8) {
  67595. drwav_f64_to_s32(pOut, (const double*)pIn, totalSampleCount);
  67596. return;
  67597. } else {
  67598. DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  67599. return;
  67600. }
  67601. }
  67602. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__pcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  67603. {
  67604. drwav_uint64 totalFramesRead;
  67605. drwav_uint8 sampleData[4096] = {0};
  67606. drwav_uint32 bytesPerFrame;
  67607. drwav_uint32 bytesPerSample;
  67608. drwav_uint64 samplesRead;
  67609. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 32) {
  67610. return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
  67611. }
  67612. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67613. if (bytesPerFrame == 0) {
  67614. return 0;
  67615. }
  67616. bytesPerSample = bytesPerFrame / pWav->channels;
  67617. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67618. return 0;
  67619. }
  67620. totalFramesRead = 0;
  67621. while (framesToRead > 0) {
  67622. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67623. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67624. if (framesRead == 0) {
  67625. break;
  67626. }
  67627. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67628. samplesRead = framesRead * pWav->channels;
  67629. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67630. DRWAV_ASSERT(DRWAV_FALSE);
  67631. break;
  67632. }
  67633. drwav__pcm_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67634. pBufferOut += samplesRead;
  67635. framesToRead -= framesRead;
  67636. totalFramesRead += framesRead;
  67637. }
  67638. return totalFramesRead;
  67639. }
  67640. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__msadpcm_ima(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  67641. {
  67642. drwav_uint64 totalFramesRead = 0;
  67643. drwav_int16 samples16[2048];
  67644. while (framesToRead > 0) {
  67645. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels);
  67646. drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16);
  67647. if (framesRead == 0) {
  67648. break;
  67649. }
  67650. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67651. drwav_s16_to_s32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
  67652. pBufferOut += framesRead*pWav->channels;
  67653. framesToRead -= framesRead;
  67654. totalFramesRead += framesRead;
  67655. }
  67656. return totalFramesRead;
  67657. }
  67658. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__ieee(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  67659. {
  67660. drwav_uint64 totalFramesRead;
  67661. drwav_uint8 sampleData[4096] = {0};
  67662. drwav_uint32 bytesPerFrame;
  67663. drwav_uint32 bytesPerSample;
  67664. drwav_uint64 samplesRead;
  67665. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67666. if (bytesPerFrame == 0) {
  67667. return 0;
  67668. }
  67669. bytesPerSample = bytesPerFrame / pWav->channels;
  67670. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67671. return 0;
  67672. }
  67673. totalFramesRead = 0;
  67674. while (framesToRead > 0) {
  67675. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67676. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67677. if (framesRead == 0) {
  67678. break;
  67679. }
  67680. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67681. samplesRead = framesRead * pWav->channels;
  67682. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67683. DRWAV_ASSERT(DRWAV_FALSE);
  67684. break;
  67685. }
  67686. drwav__ieee_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67687. pBufferOut += samplesRead;
  67688. framesToRead -= framesRead;
  67689. totalFramesRead += framesRead;
  67690. }
  67691. return totalFramesRead;
  67692. }
  67693. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__alaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  67694. {
  67695. drwav_uint64 totalFramesRead;
  67696. drwav_uint8 sampleData[4096] = {0};
  67697. drwav_uint32 bytesPerFrame;
  67698. drwav_uint32 bytesPerSample;
  67699. drwav_uint64 samplesRead;
  67700. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67701. if (bytesPerFrame == 0) {
  67702. return 0;
  67703. }
  67704. bytesPerSample = bytesPerFrame / pWav->channels;
  67705. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67706. return 0;
  67707. }
  67708. totalFramesRead = 0;
  67709. while (framesToRead > 0) {
  67710. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67711. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67712. if (framesRead == 0) {
  67713. break;
  67714. }
  67715. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67716. samplesRead = framesRead * pWav->channels;
  67717. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67718. DRWAV_ASSERT(DRWAV_FALSE);
  67719. break;
  67720. }
  67721. drwav_alaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
  67722. pBufferOut += samplesRead;
  67723. framesToRead -= framesRead;
  67724. totalFramesRead += framesRead;
  67725. }
  67726. return totalFramesRead;
  67727. }
  67728. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__mulaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  67729. {
  67730. drwav_uint64 totalFramesRead;
  67731. drwav_uint8 sampleData[4096] = {0};
  67732. drwav_uint32 bytesPerFrame;
  67733. drwav_uint32 bytesPerSample;
  67734. drwav_uint64 samplesRead;
  67735. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  67736. if (bytesPerFrame == 0) {
  67737. return 0;
  67738. }
  67739. bytesPerSample = bytesPerFrame / pWav->channels;
  67740. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67741. return 0;
  67742. }
  67743. totalFramesRead = 0;
  67744. while (framesToRead > 0) {
  67745. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67746. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67747. if (framesRead == 0) {
  67748. break;
  67749. }
  67750. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  67751. samplesRead = framesRead * pWav->channels;
  67752. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67753. DRWAV_ASSERT(DRWAV_FALSE);
  67754. break;
  67755. }
  67756. drwav_mulaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
  67757. pBufferOut += samplesRead;
  67758. framesToRead -= framesRead;
  67759. totalFramesRead += framesRead;
  67760. }
  67761. return totalFramesRead;
  67762. }
  67763. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  67764. {
  67765. if (pWav == NULL || framesToRead == 0) {
  67766. return 0;
  67767. }
  67768. if (pBufferOut == NULL) {
  67769. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  67770. }
  67771. if (framesToRead * pWav->channels * sizeof(drwav_int32) > DRWAV_SIZE_MAX) {
  67772. framesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int32) / pWav->channels;
  67773. }
  67774. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
  67775. return drwav_read_pcm_frames_s32__pcm(pWav, framesToRead, pBufferOut);
  67776. }
  67777. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  67778. return drwav_read_pcm_frames_s32__msadpcm_ima(pWav, framesToRead, pBufferOut);
  67779. }
  67780. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
  67781. return drwav_read_pcm_frames_s32__ieee(pWav, framesToRead, pBufferOut);
  67782. }
  67783. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
  67784. return drwav_read_pcm_frames_s32__alaw(pWav, framesToRead, pBufferOut);
  67785. }
  67786. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  67787. return drwav_read_pcm_frames_s32__mulaw(pWav, framesToRead, pBufferOut);
  67788. }
  67789. return 0;
  67790. }
  67791. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32le(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  67792. {
  67793. drwav_uint64 framesRead = drwav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
  67794. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
  67795. drwav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
  67796. }
  67797. return framesRead;
  67798. }
  67799. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32be(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  67800. {
  67801. drwav_uint64 framesRead = drwav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
  67802. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
  67803. drwav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
  67804. }
  67805. return framesRead;
  67806. }
  67807. DRWAV_API void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67808. {
  67809. size_t i;
  67810. if (pOut == NULL || pIn == NULL) {
  67811. return;
  67812. }
  67813. for (i = 0; i < sampleCount; ++i) {
  67814. *pOut++ = ((int)pIn[i] - 128) << 24;
  67815. }
  67816. }
  67817. DRWAV_API void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount)
  67818. {
  67819. size_t i;
  67820. if (pOut == NULL || pIn == NULL) {
  67821. return;
  67822. }
  67823. for (i = 0; i < sampleCount; ++i) {
  67824. *pOut++ = pIn[i] << 16;
  67825. }
  67826. }
  67827. DRWAV_API void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67828. {
  67829. size_t i;
  67830. if (pOut == NULL || pIn == NULL) {
  67831. return;
  67832. }
  67833. for (i = 0; i < sampleCount; ++i) {
  67834. unsigned int s0 = pIn[i*3 + 0];
  67835. unsigned int s1 = pIn[i*3 + 1];
  67836. unsigned int s2 = pIn[i*3 + 2];
  67837. drwav_int32 sample32 = (drwav_int32)((s0 << 8) | (s1 << 16) | (s2 << 24));
  67838. *pOut++ = sample32;
  67839. }
  67840. }
  67841. DRWAV_API void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount)
  67842. {
  67843. size_t i;
  67844. if (pOut == NULL || pIn == NULL) {
  67845. return;
  67846. }
  67847. for (i = 0; i < sampleCount; ++i) {
  67848. *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]);
  67849. }
  67850. }
  67851. DRWAV_API void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount)
  67852. {
  67853. size_t i;
  67854. if (pOut == NULL || pIn == NULL) {
  67855. return;
  67856. }
  67857. for (i = 0; i < sampleCount; ++i) {
  67858. *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]);
  67859. }
  67860. }
  67861. DRWAV_API void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67862. {
  67863. size_t i;
  67864. if (pOut == NULL || pIn == NULL) {
  67865. return;
  67866. }
  67867. for (i = 0; i < sampleCount; ++i) {
  67868. *pOut++ = ((drwav_int32)drwav__alaw_to_s16(pIn[i])) << 16;
  67869. }
  67870. }
  67871. DRWAV_API void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  67872. {
  67873. size_t i;
  67874. if (pOut == NULL || pIn == NULL) {
  67875. return;
  67876. }
  67877. for (i= 0; i < sampleCount; ++i) {
  67878. *pOut++ = ((drwav_int32)drwav__mulaw_to_s16(pIn[i])) << 16;
  67879. }
  67880. }
  67881. DRWAV_PRIVATE drwav_int16* drwav__read_pcm_frames_and_close_s16(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
  67882. {
  67883. drwav_uint64 sampleDataSize;
  67884. drwav_int16* pSampleData;
  67885. drwav_uint64 framesRead;
  67886. DRWAV_ASSERT(pWav != NULL);
  67887. sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(drwav_int16);
  67888. if (sampleDataSize > DRWAV_SIZE_MAX) {
  67889. drwav_uninit(pWav);
  67890. return NULL;
  67891. }
  67892. pSampleData = (drwav_int16*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
  67893. if (pSampleData == NULL) {
  67894. drwav_uninit(pWav);
  67895. return NULL;
  67896. }
  67897. framesRead = drwav_read_pcm_frames_s16(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
  67898. if (framesRead != pWav->totalPCMFrameCount) {
  67899. drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
  67900. drwav_uninit(pWav);
  67901. return NULL;
  67902. }
  67903. drwav_uninit(pWav);
  67904. if (sampleRate) {
  67905. *sampleRate = pWav->sampleRate;
  67906. }
  67907. if (channels) {
  67908. *channels = pWav->channels;
  67909. }
  67910. if (totalFrameCount) {
  67911. *totalFrameCount = pWav->totalPCMFrameCount;
  67912. }
  67913. return pSampleData;
  67914. }
  67915. DRWAV_PRIVATE float* drwav__read_pcm_frames_and_close_f32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
  67916. {
  67917. drwav_uint64 sampleDataSize;
  67918. float* pSampleData;
  67919. drwav_uint64 framesRead;
  67920. DRWAV_ASSERT(pWav != NULL);
  67921. sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(float);
  67922. if (sampleDataSize > DRWAV_SIZE_MAX) {
  67923. drwav_uninit(pWav);
  67924. return NULL;
  67925. }
  67926. pSampleData = (float*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
  67927. if (pSampleData == NULL) {
  67928. drwav_uninit(pWav);
  67929. return NULL;
  67930. }
  67931. framesRead = drwav_read_pcm_frames_f32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
  67932. if (framesRead != pWav->totalPCMFrameCount) {
  67933. drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
  67934. drwav_uninit(pWav);
  67935. return NULL;
  67936. }
  67937. drwav_uninit(pWav);
  67938. if (sampleRate) {
  67939. *sampleRate = pWav->sampleRate;
  67940. }
  67941. if (channels) {
  67942. *channels = pWav->channels;
  67943. }
  67944. if (totalFrameCount) {
  67945. *totalFrameCount = pWav->totalPCMFrameCount;
  67946. }
  67947. return pSampleData;
  67948. }
  67949. DRWAV_PRIVATE drwav_int32* drwav__read_pcm_frames_and_close_s32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
  67950. {
  67951. drwav_uint64 sampleDataSize;
  67952. drwav_int32* pSampleData;
  67953. drwav_uint64 framesRead;
  67954. DRWAV_ASSERT(pWav != NULL);
  67955. sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(drwav_int32);
  67956. if (sampleDataSize > DRWAV_SIZE_MAX) {
  67957. drwav_uninit(pWav);
  67958. return NULL;
  67959. }
  67960. pSampleData = (drwav_int32*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
  67961. if (pSampleData == NULL) {
  67962. drwav_uninit(pWav);
  67963. return NULL;
  67964. }
  67965. framesRead = drwav_read_pcm_frames_s32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
  67966. if (framesRead != pWav->totalPCMFrameCount) {
  67967. drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
  67968. drwav_uninit(pWav);
  67969. return NULL;
  67970. }
  67971. drwav_uninit(pWav);
  67972. if (sampleRate) {
  67973. *sampleRate = pWav->sampleRate;
  67974. }
  67975. if (channels) {
  67976. *channels = pWav->channels;
  67977. }
  67978. if (totalFrameCount) {
  67979. *totalFrameCount = pWav->totalPCMFrameCount;
  67980. }
  67981. return pSampleData;
  67982. }
  67983. DRWAV_API drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  67984. {
  67985. drwav wav;
  67986. if (channelsOut) {
  67987. *channelsOut = 0;
  67988. }
  67989. if (sampleRateOut) {
  67990. *sampleRateOut = 0;
  67991. }
  67992. if (totalFrameCountOut) {
  67993. *totalFrameCountOut = 0;
  67994. }
  67995. if (!drwav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  67996. return NULL;
  67997. }
  67998. return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  67999. }
  68000. DRWAV_API float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68001. {
  68002. drwav wav;
  68003. if (channelsOut) {
  68004. *channelsOut = 0;
  68005. }
  68006. if (sampleRateOut) {
  68007. *sampleRateOut = 0;
  68008. }
  68009. if (totalFrameCountOut) {
  68010. *totalFrameCountOut = 0;
  68011. }
  68012. if (!drwav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  68013. return NULL;
  68014. }
  68015. return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68016. }
  68017. DRWAV_API drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68018. {
  68019. drwav wav;
  68020. if (channelsOut) {
  68021. *channelsOut = 0;
  68022. }
  68023. if (sampleRateOut) {
  68024. *sampleRateOut = 0;
  68025. }
  68026. if (totalFrameCountOut) {
  68027. *totalFrameCountOut = 0;
  68028. }
  68029. if (!drwav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  68030. return NULL;
  68031. }
  68032. return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68033. }
  68034. #ifndef DR_WAV_NO_STDIO
  68035. DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68036. {
  68037. drwav wav;
  68038. if (channelsOut) {
  68039. *channelsOut = 0;
  68040. }
  68041. if (sampleRateOut) {
  68042. *sampleRateOut = 0;
  68043. }
  68044. if (totalFrameCountOut) {
  68045. *totalFrameCountOut = 0;
  68046. }
  68047. if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
  68048. return NULL;
  68049. }
  68050. return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68051. }
  68052. DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68053. {
  68054. drwav wav;
  68055. if (channelsOut) {
  68056. *channelsOut = 0;
  68057. }
  68058. if (sampleRateOut) {
  68059. *sampleRateOut = 0;
  68060. }
  68061. if (totalFrameCountOut) {
  68062. *totalFrameCountOut = 0;
  68063. }
  68064. if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
  68065. return NULL;
  68066. }
  68067. return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68068. }
  68069. DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68070. {
  68071. drwav wav;
  68072. if (channelsOut) {
  68073. *channelsOut = 0;
  68074. }
  68075. if (sampleRateOut) {
  68076. *sampleRateOut = 0;
  68077. }
  68078. if (totalFrameCountOut) {
  68079. *totalFrameCountOut = 0;
  68080. }
  68081. if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
  68082. return NULL;
  68083. }
  68084. return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68085. }
  68086. #ifndef DR_WAV_NO_WCHAR
  68087. DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68088. {
  68089. drwav wav;
  68090. if (sampleRateOut) {
  68091. *sampleRateOut = 0;
  68092. }
  68093. if (channelsOut) {
  68094. *channelsOut = 0;
  68095. }
  68096. if (totalFrameCountOut) {
  68097. *totalFrameCountOut = 0;
  68098. }
  68099. if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
  68100. return NULL;
  68101. }
  68102. return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68103. }
  68104. DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68105. {
  68106. drwav wav;
  68107. if (sampleRateOut) {
  68108. *sampleRateOut = 0;
  68109. }
  68110. if (channelsOut) {
  68111. *channelsOut = 0;
  68112. }
  68113. if (totalFrameCountOut) {
  68114. *totalFrameCountOut = 0;
  68115. }
  68116. if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
  68117. return NULL;
  68118. }
  68119. return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68120. }
  68121. DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68122. {
  68123. drwav wav;
  68124. if (sampleRateOut) {
  68125. *sampleRateOut = 0;
  68126. }
  68127. if (channelsOut) {
  68128. *channelsOut = 0;
  68129. }
  68130. if (totalFrameCountOut) {
  68131. *totalFrameCountOut = 0;
  68132. }
  68133. if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
  68134. return NULL;
  68135. }
  68136. return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68137. }
  68138. #endif
  68139. #endif
  68140. DRWAV_API drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68141. {
  68142. drwav wav;
  68143. if (channelsOut) {
  68144. *channelsOut = 0;
  68145. }
  68146. if (sampleRateOut) {
  68147. *sampleRateOut = 0;
  68148. }
  68149. if (totalFrameCountOut) {
  68150. *totalFrameCountOut = 0;
  68151. }
  68152. if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
  68153. return NULL;
  68154. }
  68155. return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68156. }
  68157. DRWAV_API float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68158. {
  68159. drwav wav;
  68160. if (channelsOut) {
  68161. *channelsOut = 0;
  68162. }
  68163. if (sampleRateOut) {
  68164. *sampleRateOut = 0;
  68165. }
  68166. if (totalFrameCountOut) {
  68167. *totalFrameCountOut = 0;
  68168. }
  68169. if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
  68170. return NULL;
  68171. }
  68172. return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68173. }
  68174. DRWAV_API drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  68175. {
  68176. drwav wav;
  68177. if (channelsOut) {
  68178. *channelsOut = 0;
  68179. }
  68180. if (sampleRateOut) {
  68181. *sampleRateOut = 0;
  68182. }
  68183. if (totalFrameCountOut) {
  68184. *totalFrameCountOut = 0;
  68185. }
  68186. if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
  68187. return NULL;
  68188. }
  68189. return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68190. }
  68191. #endif
  68192. DRWAV_API void drwav_free(void* p, const drwav_allocation_callbacks* pAllocationCallbacks)
  68193. {
  68194. if (pAllocationCallbacks != NULL) {
  68195. drwav__free_from_callbacks(p, pAllocationCallbacks);
  68196. } else {
  68197. drwav__free_default(p, NULL);
  68198. }
  68199. }
  68200. DRWAV_API drwav_uint16 drwav_bytes_to_u16(const drwav_uint8* data)
  68201. {
  68202. return ((drwav_uint16)data[0] << 0) | ((drwav_uint16)data[1] << 8);
  68203. }
  68204. DRWAV_API drwav_int16 drwav_bytes_to_s16(const drwav_uint8* data)
  68205. {
  68206. return (drwav_int16)drwav_bytes_to_u16(data);
  68207. }
  68208. DRWAV_API drwav_uint32 drwav_bytes_to_u32(const drwav_uint8* data)
  68209. {
  68210. return ((drwav_uint32)data[0] << 0) | ((drwav_uint32)data[1] << 8) | ((drwav_uint32)data[2] << 16) | ((drwav_uint32)data[3] << 24);
  68211. }
  68212. DRWAV_API float drwav_bytes_to_f32(const drwav_uint8* data)
  68213. {
  68214. union {
  68215. drwav_uint32 u32;
  68216. float f32;
  68217. } value;
  68218. value.u32 = drwav_bytes_to_u32(data);
  68219. return value.f32;
  68220. }
  68221. DRWAV_API drwav_int32 drwav_bytes_to_s32(const drwav_uint8* data)
  68222. {
  68223. return (drwav_int32)drwav_bytes_to_u32(data);
  68224. }
  68225. DRWAV_API drwav_uint64 drwav_bytes_to_u64(const drwav_uint8* data)
  68226. {
  68227. return
  68228. ((drwav_uint64)data[0] << 0) | ((drwav_uint64)data[1] << 8) | ((drwav_uint64)data[2] << 16) | ((drwav_uint64)data[3] << 24) |
  68229. ((drwav_uint64)data[4] << 32) | ((drwav_uint64)data[5] << 40) | ((drwav_uint64)data[6] << 48) | ((drwav_uint64)data[7] << 56);
  68230. }
  68231. DRWAV_API drwav_int64 drwav_bytes_to_s64(const drwav_uint8* data)
  68232. {
  68233. return (drwav_int64)drwav_bytes_to_u64(data);
  68234. }
  68235. DRWAV_API drwav_bool32 drwav_guid_equal(const drwav_uint8 a[16], const drwav_uint8 b[16])
  68236. {
  68237. int i;
  68238. for (i = 0; i < 16; i += 1) {
  68239. if (a[i] != b[i]) {
  68240. return DRWAV_FALSE;
  68241. }
  68242. }
  68243. return DRWAV_TRUE;
  68244. }
  68245. DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b)
  68246. {
  68247. return
  68248. a[0] == b[0] &&
  68249. a[1] == b[1] &&
  68250. a[2] == b[2] &&
  68251. a[3] == b[3];
  68252. }
  68253. #ifdef __MRC__
  68254. #pragma options opt reset
  68255. #endif
  68256. #endif
  68257. /* dr_wav_c end */
  68258. #endif /* DRWAV_IMPLEMENTATION */
  68259. #endif /* MA_NO_WAV */
  68260. #if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING)
  68261. #if !defined(DR_FLAC_IMPLEMENTATION) && !defined(DRFLAC_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
  68262. /* dr_flac_c begin */
  68263. #ifndef dr_flac_c
  68264. #define dr_flac_c
  68265. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  68266. #pragma GCC diagnostic push
  68267. #if __GNUC__ >= 7
  68268. #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  68269. #endif
  68270. #endif
  68271. #ifdef __linux__
  68272. #ifndef _BSD_SOURCE
  68273. #define _BSD_SOURCE
  68274. #endif
  68275. #ifndef _DEFAULT_SOURCE
  68276. #define _DEFAULT_SOURCE
  68277. #endif
  68278. #ifndef __USE_BSD
  68279. #define __USE_BSD
  68280. #endif
  68281. #include <endian.h>
  68282. #endif
  68283. #include <stdlib.h>
  68284. #include <string.h>
  68285. #ifdef _MSC_VER
  68286. #define DRFLAC_INLINE __forceinline
  68287. #elif defined(__GNUC__)
  68288. #if defined(__STRICT_ANSI__)
  68289. #define DRFLAC_GNUC_INLINE_HINT __inline__
  68290. #else
  68291. #define DRFLAC_GNUC_INLINE_HINT inline
  68292. #endif
  68293. #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
  68294. #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT __attribute__((always_inline))
  68295. #else
  68296. #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT
  68297. #endif
  68298. #elif defined(__WATCOMC__)
  68299. #define DRFLAC_INLINE __inline
  68300. #else
  68301. #define DRFLAC_INLINE
  68302. #endif
  68303. #if defined(__x86_64__) || defined(_M_X64)
  68304. #define DRFLAC_X64
  68305. #elif defined(__i386) || defined(_M_IX86)
  68306. #define DRFLAC_X86
  68307. #elif defined(__arm__) || defined(_M_ARM) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
  68308. #define DRFLAC_ARM
  68309. #endif
  68310. #if !defined(DR_FLAC_NO_SIMD)
  68311. #if defined(DRFLAC_X64) || defined(DRFLAC_X86)
  68312. #if defined(_MSC_VER) && !defined(__clang__)
  68313. #if _MSC_VER >= 1400 && !defined(DRFLAC_NO_SSE2)
  68314. #define DRFLAC_SUPPORT_SSE2
  68315. #endif
  68316. #if _MSC_VER >= 1600 && !defined(DRFLAC_NO_SSE41)
  68317. #define DRFLAC_SUPPORT_SSE41
  68318. #endif
  68319. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)))
  68320. #if defined(__SSE2__) && !defined(DRFLAC_NO_SSE2)
  68321. #define DRFLAC_SUPPORT_SSE2
  68322. #endif
  68323. #if defined(__SSE4_1__) && !defined(DRFLAC_NO_SSE41)
  68324. #define DRFLAC_SUPPORT_SSE41
  68325. #endif
  68326. #endif
  68327. #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
  68328. #if !defined(DRFLAC_SUPPORT_SSE2) && !defined(DRFLAC_NO_SSE2) && __has_include(<emmintrin.h>)
  68329. #define DRFLAC_SUPPORT_SSE2
  68330. #endif
  68331. #if !defined(DRFLAC_SUPPORT_SSE41) && !defined(DRFLAC_NO_SSE41) && __has_include(<smmintrin.h>)
  68332. #define DRFLAC_SUPPORT_SSE41
  68333. #endif
  68334. #endif
  68335. #if defined(DRFLAC_SUPPORT_SSE41)
  68336. #include <smmintrin.h>
  68337. #elif defined(DRFLAC_SUPPORT_SSE2)
  68338. #include <emmintrin.h>
  68339. #endif
  68340. #endif
  68341. #if defined(DRFLAC_ARM)
  68342. #if !defined(DRFLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  68343. #define DRFLAC_SUPPORT_NEON
  68344. #include <arm_neon.h>
  68345. #endif
  68346. #endif
  68347. #endif
  68348. #if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
  68349. #if defined(_MSC_VER) && !defined(__clang__)
  68350. #if _MSC_VER >= 1400
  68351. #include <intrin.h>
  68352. static void drflac__cpuid(int info[4], int fid)
  68353. {
  68354. __cpuid(info, fid);
  68355. }
  68356. #else
  68357. #define DRFLAC_NO_CPUID
  68358. #endif
  68359. #else
  68360. #if defined(__GNUC__) || defined(__clang__)
  68361. static void drflac__cpuid(int info[4], int fid)
  68362. {
  68363. #if defined(DRFLAC_X86) && defined(__PIC__)
  68364. __asm__ __volatile__ (
  68365. "xchg{l} {%%}ebx, %k1;"
  68366. "cpuid;"
  68367. "xchg{l} {%%}ebx, %k1;"
  68368. : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  68369. );
  68370. #else
  68371. __asm__ __volatile__ (
  68372. "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  68373. );
  68374. #endif
  68375. }
  68376. #else
  68377. #define DRFLAC_NO_CPUID
  68378. #endif
  68379. #endif
  68380. #else
  68381. #define DRFLAC_NO_CPUID
  68382. #endif
  68383. static DRFLAC_INLINE drflac_bool32 drflac_has_sse2(void)
  68384. {
  68385. #if defined(DRFLAC_SUPPORT_SSE2)
  68386. #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE2)
  68387. #if defined(DRFLAC_X64)
  68388. return DRFLAC_TRUE;
  68389. #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
  68390. return DRFLAC_TRUE;
  68391. #else
  68392. #if defined(DRFLAC_NO_CPUID)
  68393. return DRFLAC_FALSE;
  68394. #else
  68395. int info[4];
  68396. drflac__cpuid(info, 1);
  68397. return (info[3] & (1 << 26)) != 0;
  68398. #endif
  68399. #endif
  68400. #else
  68401. return DRFLAC_FALSE;
  68402. #endif
  68403. #else
  68404. return DRFLAC_FALSE;
  68405. #endif
  68406. }
  68407. static DRFLAC_INLINE drflac_bool32 drflac_has_sse41(void)
  68408. {
  68409. #if defined(DRFLAC_SUPPORT_SSE41)
  68410. #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE41)
  68411. #if defined(__SSE4_1__) || defined(__AVX__)
  68412. return DRFLAC_TRUE;
  68413. #else
  68414. #if defined(DRFLAC_NO_CPUID)
  68415. return DRFLAC_FALSE;
  68416. #else
  68417. int info[4];
  68418. drflac__cpuid(info, 1);
  68419. return (info[2] & (1 << 19)) != 0;
  68420. #endif
  68421. #endif
  68422. #else
  68423. return DRFLAC_FALSE;
  68424. #endif
  68425. #else
  68426. return DRFLAC_FALSE;
  68427. #endif
  68428. }
  68429. #if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64)) && !defined(__clang__)
  68430. #define DRFLAC_HAS_LZCNT_INTRINSIC
  68431. #elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
  68432. #define DRFLAC_HAS_LZCNT_INTRINSIC
  68433. #elif defined(__clang__)
  68434. #if defined(__has_builtin)
  68435. #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl)
  68436. #define DRFLAC_HAS_LZCNT_INTRINSIC
  68437. #endif
  68438. #endif
  68439. #endif
  68440. #if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__clang__)
  68441. #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  68442. #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  68443. #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  68444. #elif defined(__clang__)
  68445. #if defined(__has_builtin)
  68446. #if __has_builtin(__builtin_bswap16)
  68447. #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  68448. #endif
  68449. #if __has_builtin(__builtin_bswap32)
  68450. #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  68451. #endif
  68452. #if __has_builtin(__builtin_bswap64)
  68453. #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  68454. #endif
  68455. #endif
  68456. #elif defined(__GNUC__)
  68457. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  68458. #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  68459. #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  68460. #endif
  68461. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  68462. #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  68463. #endif
  68464. #elif defined(__WATCOMC__) && defined(__386__)
  68465. #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  68466. #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  68467. #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  68468. extern __inline drflac_uint16 _watcom_bswap16(drflac_uint16);
  68469. extern __inline drflac_uint32 _watcom_bswap32(drflac_uint32);
  68470. extern __inline drflac_uint64 _watcom_bswap64(drflac_uint64);
  68471. #pragma aux _watcom_bswap16 = \
  68472. "xchg al, ah" \
  68473. parm [ax] \
  68474. value [ax] \
  68475. modify nomemory;
  68476. #pragma aux _watcom_bswap32 = \
  68477. "bswap eax" \
  68478. parm [eax] \
  68479. value [eax] \
  68480. modify nomemory;
  68481. #pragma aux _watcom_bswap64 = \
  68482. "bswap eax" \
  68483. "bswap edx" \
  68484. "xchg eax,edx" \
  68485. parm [eax edx] \
  68486. value [eax edx] \
  68487. modify nomemory;
  68488. #endif
  68489. #ifndef DRFLAC_ASSERT
  68490. #include <assert.h>
  68491. #define DRFLAC_ASSERT(expression) assert(expression)
  68492. #endif
  68493. #ifndef DRFLAC_MALLOC
  68494. #define DRFLAC_MALLOC(sz) malloc((sz))
  68495. #endif
  68496. #ifndef DRFLAC_REALLOC
  68497. #define DRFLAC_REALLOC(p, sz) realloc((p), (sz))
  68498. #endif
  68499. #ifndef DRFLAC_FREE
  68500. #define DRFLAC_FREE(p) free((p))
  68501. #endif
  68502. #ifndef DRFLAC_COPY_MEMORY
  68503. #define DRFLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  68504. #endif
  68505. #ifndef DRFLAC_ZERO_MEMORY
  68506. #define DRFLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  68507. #endif
  68508. #ifndef DRFLAC_ZERO_OBJECT
  68509. #define DRFLAC_ZERO_OBJECT(p) DRFLAC_ZERO_MEMORY((p), sizeof(*(p)))
  68510. #endif
  68511. #define DRFLAC_MAX_SIMD_VECTOR_SIZE 64
  68512. typedef drflac_int32 drflac_result;
  68513. #define DRFLAC_SUCCESS 0
  68514. #define DRFLAC_ERROR -1
  68515. #define DRFLAC_INVALID_ARGS -2
  68516. #define DRFLAC_INVALID_OPERATION -3
  68517. #define DRFLAC_OUT_OF_MEMORY -4
  68518. #define DRFLAC_OUT_OF_RANGE -5
  68519. #define DRFLAC_ACCESS_DENIED -6
  68520. #define DRFLAC_DOES_NOT_EXIST -7
  68521. #define DRFLAC_ALREADY_EXISTS -8
  68522. #define DRFLAC_TOO_MANY_OPEN_FILES -9
  68523. #define DRFLAC_INVALID_FILE -10
  68524. #define DRFLAC_TOO_BIG -11
  68525. #define DRFLAC_PATH_TOO_LONG -12
  68526. #define DRFLAC_NAME_TOO_LONG -13
  68527. #define DRFLAC_NOT_DIRECTORY -14
  68528. #define DRFLAC_IS_DIRECTORY -15
  68529. #define DRFLAC_DIRECTORY_NOT_EMPTY -16
  68530. #define DRFLAC_END_OF_FILE -17
  68531. #define DRFLAC_NO_SPACE -18
  68532. #define DRFLAC_BUSY -19
  68533. #define DRFLAC_IO_ERROR -20
  68534. #define DRFLAC_INTERRUPT -21
  68535. #define DRFLAC_UNAVAILABLE -22
  68536. #define DRFLAC_ALREADY_IN_USE -23
  68537. #define DRFLAC_BAD_ADDRESS -24
  68538. #define DRFLAC_BAD_SEEK -25
  68539. #define DRFLAC_BAD_PIPE -26
  68540. #define DRFLAC_DEADLOCK -27
  68541. #define DRFLAC_TOO_MANY_LINKS -28
  68542. #define DRFLAC_NOT_IMPLEMENTED -29
  68543. #define DRFLAC_NO_MESSAGE -30
  68544. #define DRFLAC_BAD_MESSAGE -31
  68545. #define DRFLAC_NO_DATA_AVAILABLE -32
  68546. #define DRFLAC_INVALID_DATA -33
  68547. #define DRFLAC_TIMEOUT -34
  68548. #define DRFLAC_NO_NETWORK -35
  68549. #define DRFLAC_NOT_UNIQUE -36
  68550. #define DRFLAC_NOT_SOCKET -37
  68551. #define DRFLAC_NO_ADDRESS -38
  68552. #define DRFLAC_BAD_PROTOCOL -39
  68553. #define DRFLAC_PROTOCOL_UNAVAILABLE -40
  68554. #define DRFLAC_PROTOCOL_NOT_SUPPORTED -41
  68555. #define DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED -42
  68556. #define DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED -43
  68557. #define DRFLAC_SOCKET_NOT_SUPPORTED -44
  68558. #define DRFLAC_CONNECTION_RESET -45
  68559. #define DRFLAC_ALREADY_CONNECTED -46
  68560. #define DRFLAC_NOT_CONNECTED -47
  68561. #define DRFLAC_CONNECTION_REFUSED -48
  68562. #define DRFLAC_NO_HOST -49
  68563. #define DRFLAC_IN_PROGRESS -50
  68564. #define DRFLAC_CANCELLED -51
  68565. #define DRFLAC_MEMORY_ALREADY_MAPPED -52
  68566. #define DRFLAC_AT_END -53
  68567. #define DRFLAC_CRC_MISMATCH -128
  68568. #define DRFLAC_SUBFRAME_CONSTANT 0
  68569. #define DRFLAC_SUBFRAME_VERBATIM 1
  68570. #define DRFLAC_SUBFRAME_FIXED 8
  68571. #define DRFLAC_SUBFRAME_LPC 32
  68572. #define DRFLAC_SUBFRAME_RESERVED 255
  68573. #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0
  68574. #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1
  68575. #define DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0
  68576. #define DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8
  68577. #define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9
  68578. #define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10
  68579. #define DRFLAC_SEEKPOINT_SIZE_IN_BYTES 18
  68580. #define DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES 36
  68581. #define DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES 12
  68582. #define drflac_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
  68583. DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision)
  68584. {
  68585. if (pMajor) {
  68586. *pMajor = DRFLAC_VERSION_MAJOR;
  68587. }
  68588. if (pMinor) {
  68589. *pMinor = DRFLAC_VERSION_MINOR;
  68590. }
  68591. if (pRevision) {
  68592. *pRevision = DRFLAC_VERSION_REVISION;
  68593. }
  68594. }
  68595. DRFLAC_API const char* drflac_version_string(void)
  68596. {
  68597. return DRFLAC_VERSION_STRING;
  68598. }
  68599. #if defined(__has_feature)
  68600. #if __has_feature(thread_sanitizer)
  68601. #define DRFLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread")))
  68602. #else
  68603. #define DRFLAC_NO_THREAD_SANITIZE
  68604. #endif
  68605. #else
  68606. #define DRFLAC_NO_THREAD_SANITIZE
  68607. #endif
  68608. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
  68609. static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE;
  68610. #endif
  68611. #ifndef DRFLAC_NO_CPUID
  68612. static drflac_bool32 drflac__gIsSSE2Supported = DRFLAC_FALSE;
  68613. static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE;
  68614. DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
  68615. {
  68616. static drflac_bool32 isCPUCapsInitialized = DRFLAC_FALSE;
  68617. if (!isCPUCapsInitialized) {
  68618. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
  68619. int info[4] = {0};
  68620. drflac__cpuid(info, 0x80000001);
  68621. drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0;
  68622. #endif
  68623. drflac__gIsSSE2Supported = drflac_has_sse2();
  68624. drflac__gIsSSE41Supported = drflac_has_sse41();
  68625. isCPUCapsInitialized = DRFLAC_TRUE;
  68626. }
  68627. }
  68628. #else
  68629. static drflac_bool32 drflac__gIsNEONSupported = DRFLAC_FALSE;
  68630. static DRFLAC_INLINE drflac_bool32 drflac__has_neon(void)
  68631. {
  68632. #if defined(DRFLAC_SUPPORT_NEON)
  68633. #if defined(DRFLAC_ARM) && !defined(DRFLAC_NO_NEON)
  68634. #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  68635. return DRFLAC_TRUE;
  68636. #else
  68637. return DRFLAC_FALSE;
  68638. #endif
  68639. #else
  68640. return DRFLAC_FALSE;
  68641. #endif
  68642. #else
  68643. return DRFLAC_FALSE;
  68644. #endif
  68645. }
  68646. DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
  68647. {
  68648. drflac__gIsNEONSupported = drflac__has_neon();
  68649. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
  68650. drflac__gIsLZCNTSupported = DRFLAC_TRUE;
  68651. #endif
  68652. }
  68653. #endif
  68654. static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian(void)
  68655. {
  68656. #if defined(DRFLAC_X86) || defined(DRFLAC_X64)
  68657. return DRFLAC_TRUE;
  68658. #elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
  68659. return DRFLAC_TRUE;
  68660. #else
  68661. int n = 1;
  68662. return (*(char*)&n) == 1;
  68663. #endif
  68664. }
  68665. static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n)
  68666. {
  68667. #ifdef DRFLAC_HAS_BYTESWAP16_INTRINSIC
  68668. #if defined(_MSC_VER) && !defined(__clang__)
  68669. return _byteswap_ushort(n);
  68670. #elif defined(__GNUC__) || defined(__clang__)
  68671. return __builtin_bswap16(n);
  68672. #elif defined(__WATCOMC__) && defined(__386__)
  68673. return _watcom_bswap16(n);
  68674. #else
  68675. #error "This compiler does not support the byte swap intrinsic."
  68676. #endif
  68677. #else
  68678. return ((n & 0xFF00) >> 8) |
  68679. ((n & 0x00FF) << 8);
  68680. #endif
  68681. }
  68682. static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n)
  68683. {
  68684. #ifdef DRFLAC_HAS_BYTESWAP32_INTRINSIC
  68685. #if defined(_MSC_VER) && !defined(__clang__)
  68686. return _byteswap_ulong(n);
  68687. #elif defined(__GNUC__) || defined(__clang__)
  68688. #if defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(DRFLAC_64BIT)
  68689. drflac_uint32 r;
  68690. __asm__ __volatile__ (
  68691. #if defined(DRFLAC_64BIT)
  68692. "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n)
  68693. #else
  68694. "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  68695. #endif
  68696. );
  68697. return r;
  68698. #else
  68699. return __builtin_bswap32(n);
  68700. #endif
  68701. #elif defined(__WATCOMC__) && defined(__386__)
  68702. return _watcom_bswap32(n);
  68703. #else
  68704. #error "This compiler does not support the byte swap intrinsic."
  68705. #endif
  68706. #else
  68707. return ((n & 0xFF000000) >> 24) |
  68708. ((n & 0x00FF0000) >> 8) |
  68709. ((n & 0x0000FF00) << 8) |
  68710. ((n & 0x000000FF) << 24);
  68711. #endif
  68712. }
  68713. static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n)
  68714. {
  68715. #ifdef DRFLAC_HAS_BYTESWAP64_INTRINSIC
  68716. #if defined(_MSC_VER) && !defined(__clang__)
  68717. return _byteswap_uint64(n);
  68718. #elif defined(__GNUC__) || defined(__clang__)
  68719. return __builtin_bswap64(n);
  68720. #elif defined(__WATCOMC__) && defined(__386__)
  68721. return _watcom_bswap64(n);
  68722. #else
  68723. #error "This compiler does not support the byte swap intrinsic."
  68724. #endif
  68725. #else
  68726. return ((n & ((drflac_uint64)0xFF000000 << 32)) >> 56) |
  68727. ((n & ((drflac_uint64)0x00FF0000 << 32)) >> 40) |
  68728. ((n & ((drflac_uint64)0x0000FF00 << 32)) >> 24) |
  68729. ((n & ((drflac_uint64)0x000000FF << 32)) >> 8) |
  68730. ((n & ((drflac_uint64)0xFF000000 )) << 8) |
  68731. ((n & ((drflac_uint64)0x00FF0000 )) << 24) |
  68732. ((n & ((drflac_uint64)0x0000FF00 )) << 40) |
  68733. ((n & ((drflac_uint64)0x000000FF )) << 56);
  68734. #endif
  68735. }
  68736. static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n)
  68737. {
  68738. if (drflac__is_little_endian()) {
  68739. return drflac__swap_endian_uint16(n);
  68740. }
  68741. return n;
  68742. }
  68743. static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n)
  68744. {
  68745. if (drflac__is_little_endian()) {
  68746. return drflac__swap_endian_uint32(n);
  68747. }
  68748. return n;
  68749. }
  68750. static DRFLAC_INLINE drflac_uint32 drflac__be2host_32_ptr_unaligned(const void* pData)
  68751. {
  68752. const drflac_uint8* pNum = (drflac_uint8*)pData;
  68753. return *(pNum) << 24 | *(pNum+1) << 16 | *(pNum+2) << 8 | *(pNum+3);
  68754. }
  68755. static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n)
  68756. {
  68757. if (drflac__is_little_endian()) {
  68758. return drflac__swap_endian_uint64(n);
  68759. }
  68760. return n;
  68761. }
  68762. static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n)
  68763. {
  68764. if (!drflac__is_little_endian()) {
  68765. return drflac__swap_endian_uint32(n);
  68766. }
  68767. return n;
  68768. }
  68769. static DRFLAC_INLINE drflac_uint32 drflac__le2host_32_ptr_unaligned(const void* pData)
  68770. {
  68771. const drflac_uint8* pNum = (drflac_uint8*)pData;
  68772. return *pNum | *(pNum+1) << 8 | *(pNum+2) << 16 | *(pNum+3) << 24;
  68773. }
  68774. static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n)
  68775. {
  68776. drflac_uint32 result = 0;
  68777. result |= (n & 0x7F000000) >> 3;
  68778. result |= (n & 0x007F0000) >> 2;
  68779. result |= (n & 0x00007F00) >> 1;
  68780. result |= (n & 0x0000007F) >> 0;
  68781. return result;
  68782. }
  68783. static drflac_uint8 drflac__crc8_table[] = {
  68784. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  68785. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  68786. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  68787. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  68788. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  68789. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  68790. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  68791. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  68792. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  68793. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  68794. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  68795. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  68796. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  68797. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  68798. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  68799. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  68800. };
  68801. static drflac_uint16 drflac__crc16_table[] = {
  68802. 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
  68803. 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
  68804. 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
  68805. 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
  68806. 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
  68807. 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
  68808. 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
  68809. 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
  68810. 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
  68811. 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
  68812. 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
  68813. 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
  68814. 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
  68815. 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
  68816. 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
  68817. 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
  68818. 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
  68819. 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
  68820. 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
  68821. 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
  68822. 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
  68823. 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
  68824. 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
  68825. 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
  68826. 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
  68827. 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
  68828. 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
  68829. 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
  68830. 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
  68831. 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
  68832. 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
  68833. 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
  68834. };
  68835. static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint8 data)
  68836. {
  68837. return drflac__crc8_table[crc ^ data];
  68838. }
  68839. static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count)
  68840. {
  68841. #ifdef DR_FLAC_NO_CRC
  68842. (void)crc;
  68843. (void)data;
  68844. (void)count;
  68845. return 0;
  68846. #else
  68847. #if 0
  68848. drflac_uint8 p = 0x07;
  68849. for (int i = count-1; i >= 0; --i) {
  68850. drflac_uint8 bit = (data & (1 << i)) >> i;
  68851. if (crc & 0x80) {
  68852. crc = ((crc << 1) | bit) ^ p;
  68853. } else {
  68854. crc = ((crc << 1) | bit);
  68855. }
  68856. }
  68857. return crc;
  68858. #else
  68859. drflac_uint32 wholeBytes;
  68860. drflac_uint32 leftoverBits;
  68861. drflac_uint64 leftoverDataMask;
  68862. static drflac_uint64 leftoverDataMaskTable[8] = {
  68863. 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  68864. };
  68865. DRFLAC_ASSERT(count <= 32);
  68866. wholeBytes = count >> 3;
  68867. leftoverBits = count - (wholeBytes*8);
  68868. leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  68869. switch (wholeBytes) {
  68870. case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
  68871. case 3: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
  68872. case 2: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
  68873. case 1: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
  68874. case 0: if (leftoverBits > 0) crc = (drflac_uint8)((crc << leftoverBits) ^ drflac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)]);
  68875. }
  68876. return crc;
  68877. #endif
  68878. #endif
  68879. }
  68880. static DRFLAC_INLINE drflac_uint16 drflac_crc16_byte(drflac_uint16 crc, drflac_uint8 data)
  68881. {
  68882. return (crc << 8) ^ drflac__crc16_table[(drflac_uint8)(crc >> 8) ^ data];
  68883. }
  68884. static DRFLAC_INLINE drflac_uint16 drflac_crc16_cache(drflac_uint16 crc, drflac_cache_t data)
  68885. {
  68886. #ifdef DRFLAC_64BIT
  68887. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
  68888. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
  68889. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
  68890. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
  68891. #endif
  68892. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
  68893. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
  68894. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
  68895. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
  68896. return crc;
  68897. }
  68898. static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 byteCount)
  68899. {
  68900. switch (byteCount)
  68901. {
  68902. #ifdef DRFLAC_64BIT
  68903. case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
  68904. case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
  68905. case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
  68906. case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
  68907. #endif
  68908. case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
  68909. case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
  68910. case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
  68911. case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
  68912. }
  68913. return crc;
  68914. }
  68915. #if 0
  68916. static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count)
  68917. {
  68918. #ifdef DR_FLAC_NO_CRC
  68919. (void)crc;
  68920. (void)data;
  68921. (void)count;
  68922. return 0;
  68923. #else
  68924. #if 0
  68925. drflac_uint16 p = 0x8005;
  68926. for (int i = count-1; i >= 0; --i) {
  68927. drflac_uint16 bit = (data & (1ULL << i)) >> i;
  68928. if (r & 0x8000) {
  68929. r = ((r << 1) | bit) ^ p;
  68930. } else {
  68931. r = ((r << 1) | bit);
  68932. }
  68933. }
  68934. return crc;
  68935. #else
  68936. drflac_uint32 wholeBytes;
  68937. drflac_uint32 leftoverBits;
  68938. drflac_uint64 leftoverDataMask;
  68939. static drflac_uint64 leftoverDataMaskTable[8] = {
  68940. 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  68941. };
  68942. DRFLAC_ASSERT(count <= 64);
  68943. wholeBytes = count >> 3;
  68944. leftoverBits = count & 7;
  68945. leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  68946. switch (wholeBytes) {
  68947. default:
  68948. case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
  68949. case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
  68950. case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
  68951. case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
  68952. case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
  68953. }
  68954. return crc;
  68955. #endif
  68956. #endif
  68957. }
  68958. static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count)
  68959. {
  68960. #ifdef DR_FLAC_NO_CRC
  68961. (void)crc;
  68962. (void)data;
  68963. (void)count;
  68964. return 0;
  68965. #else
  68966. drflac_uint32 wholeBytes;
  68967. drflac_uint32 leftoverBits;
  68968. drflac_uint64 leftoverDataMask;
  68969. static drflac_uint64 leftoverDataMaskTable[8] = {
  68970. 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  68971. };
  68972. DRFLAC_ASSERT(count <= 64);
  68973. wholeBytes = count >> 3;
  68974. leftoverBits = count & 7;
  68975. leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  68976. switch (wholeBytes) {
  68977. default:
  68978. case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 << 32) << leftoverBits)) >> (56 + leftoverBits)));
  68979. case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits)));
  68980. case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits)));
  68981. case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits)));
  68982. case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 ) << leftoverBits)) >> (24 + leftoverBits)));
  68983. case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 ) << leftoverBits)) >> (16 + leftoverBits)));
  68984. case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 ) << leftoverBits)) >> ( 8 + leftoverBits)));
  68985. case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF ) << leftoverBits)) >> ( 0 + leftoverBits)));
  68986. case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
  68987. }
  68988. return crc;
  68989. #endif
  68990. }
  68991. static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 count)
  68992. {
  68993. #ifdef DRFLAC_64BIT
  68994. return drflac_crc16__64bit(crc, data, count);
  68995. #else
  68996. return drflac_crc16__32bit(crc, data, count);
  68997. #endif
  68998. }
  68999. #endif
  69000. #ifdef DRFLAC_64BIT
  69001. #define drflac__be2host__cache_line drflac__be2host_64
  69002. #else
  69003. #define drflac__be2host__cache_line drflac__be2host_32
  69004. #endif
  69005. #define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache))
  69006. #define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8)
  69007. #define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits)
  69008. #define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(drflac_cache_t)0) >> (_bitCount)))
  69009. #define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount))
  69010. #define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount))
  69011. #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)))
  69012. #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, _bitCount)(DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> (DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)) & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1)))
  69013. #define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2))
  69014. #define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0]))
  69015. #define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line)
  69016. #ifndef DR_FLAC_NO_CRC
  69017. static DRFLAC_INLINE void drflac__reset_crc16(drflac_bs* bs)
  69018. {
  69019. bs->crc16 = 0;
  69020. bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  69021. }
  69022. static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs)
  69023. {
  69024. if (bs->crc16CacheIgnoredBytes == 0) {
  69025. bs->crc16 = drflac_crc16_cache(bs->crc16, bs->crc16Cache);
  69026. } else {
  69027. bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache, DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes);
  69028. bs->crc16CacheIgnoredBytes = 0;
  69029. }
  69030. }
  69031. static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs)
  69032. {
  69033. DRFLAC_ASSERT((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0);
  69034. if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0) {
  69035. drflac__update_crc16(bs);
  69036. } else {
  69037. bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes);
  69038. bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  69039. }
  69040. return bs->crc16;
  69041. }
  69042. #endif
  69043. static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs)
  69044. {
  69045. size_t bytesRead;
  69046. size_t alignedL1LineCount;
  69047. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  69048. bs->cache = bs->cacheL2[bs->nextL2Line++];
  69049. return DRFLAC_TRUE;
  69050. }
  69051. if (bs->unalignedByteCount > 0) {
  69052. return DRFLAC_FALSE;
  69053. }
  69054. bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs));
  69055. bs->nextL2Line = 0;
  69056. if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs)) {
  69057. bs->cache = bs->cacheL2[bs->nextL2Line++];
  69058. return DRFLAC_TRUE;
  69059. }
  69060. alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs);
  69061. bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs));
  69062. if (bs->unalignedByteCount > 0) {
  69063. bs->unalignedCache = bs->cacheL2[alignedL1LineCount];
  69064. }
  69065. if (alignedL1LineCount > 0) {
  69066. size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount;
  69067. size_t i;
  69068. for (i = alignedL1LineCount; i > 0; --i) {
  69069. bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1];
  69070. }
  69071. bs->nextL2Line = (drflac_uint32)offset;
  69072. bs->cache = bs->cacheL2[bs->nextL2Line++];
  69073. return DRFLAC_TRUE;
  69074. } else {
  69075. bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
  69076. return DRFLAC_FALSE;
  69077. }
  69078. }
  69079. static drflac_bool32 drflac__reload_cache(drflac_bs* bs)
  69080. {
  69081. size_t bytesRead;
  69082. #ifndef DR_FLAC_NO_CRC
  69083. drflac__update_crc16(bs);
  69084. #endif
  69085. if (drflac__reload_l1_cache_from_l2(bs)) {
  69086. bs->cache = drflac__be2host__cache_line(bs->cache);
  69087. bs->consumedBits = 0;
  69088. #ifndef DR_FLAC_NO_CRC
  69089. bs->crc16Cache = bs->cache;
  69090. #endif
  69091. return DRFLAC_TRUE;
  69092. }
  69093. bytesRead = bs->unalignedByteCount;
  69094. if (bytesRead == 0) {
  69095. bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
  69096. return DRFLAC_FALSE;
  69097. }
  69098. DRFLAC_ASSERT(bytesRead < DRFLAC_CACHE_L1_SIZE_BYTES(bs));
  69099. bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8;
  69100. bs->cache = drflac__be2host__cache_line(bs->unalignedCache);
  69101. bs->cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_BITS_REMAINING(bs));
  69102. bs->unalignedByteCount = 0;
  69103. #ifndef DR_FLAC_NO_CRC
  69104. bs->crc16Cache = bs->cache >> bs->consumedBits;
  69105. bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  69106. #endif
  69107. return DRFLAC_TRUE;
  69108. }
  69109. static void drflac__reset_cache(drflac_bs* bs)
  69110. {
  69111. bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
  69112. bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
  69113. bs->cache = 0;
  69114. bs->unalignedByteCount = 0;
  69115. bs->unalignedCache = 0;
  69116. #ifndef DR_FLAC_NO_CRC
  69117. bs->crc16Cache = 0;
  69118. bs->crc16CacheIgnoredBytes = 0;
  69119. #endif
  69120. }
  69121. static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned int bitCount, drflac_uint32* pResultOut)
  69122. {
  69123. DRFLAC_ASSERT(bs != NULL);
  69124. DRFLAC_ASSERT(pResultOut != NULL);
  69125. DRFLAC_ASSERT(bitCount > 0);
  69126. DRFLAC_ASSERT(bitCount <= 32);
  69127. if (bs->consumedBits == DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  69128. if (!drflac__reload_cache(bs)) {
  69129. return DRFLAC_FALSE;
  69130. }
  69131. }
  69132. if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69133. #ifdef DRFLAC_64BIT
  69134. *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
  69135. bs->consumedBits += bitCount;
  69136. bs->cache <<= bitCount;
  69137. #else
  69138. if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  69139. *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
  69140. bs->consumedBits += bitCount;
  69141. bs->cache <<= bitCount;
  69142. } else {
  69143. *pResultOut = (drflac_uint32)bs->cache;
  69144. bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
  69145. bs->cache = 0;
  69146. }
  69147. #endif
  69148. return DRFLAC_TRUE;
  69149. } else {
  69150. drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  69151. drflac_uint32 bitCountLo = bitCount - bitCountHi;
  69152. drflac_uint32 resultHi;
  69153. DRFLAC_ASSERT(bitCountHi > 0);
  69154. DRFLAC_ASSERT(bitCountHi < 32);
  69155. resultHi = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi);
  69156. if (!drflac__reload_cache(bs)) {
  69157. return DRFLAC_FALSE;
  69158. }
  69159. if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69160. return DRFLAC_FALSE;
  69161. }
  69162. *pResultOut = (resultHi << bitCountLo) | (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo);
  69163. bs->consumedBits += bitCountLo;
  69164. bs->cache <<= bitCountLo;
  69165. return DRFLAC_TRUE;
  69166. }
  69167. }
  69168. static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult)
  69169. {
  69170. drflac_uint32 result;
  69171. DRFLAC_ASSERT(bs != NULL);
  69172. DRFLAC_ASSERT(pResult != NULL);
  69173. DRFLAC_ASSERT(bitCount > 0);
  69174. DRFLAC_ASSERT(bitCount <= 32);
  69175. if (!drflac__read_uint32(bs, bitCount, &result)) {
  69176. return DRFLAC_FALSE;
  69177. }
  69178. if (bitCount < 32) {
  69179. drflac_uint32 signbit;
  69180. signbit = ((result >> (bitCount-1)) & 0x01);
  69181. result |= (~signbit + 1) << bitCount;
  69182. }
  69183. *pResult = (drflac_int32)result;
  69184. return DRFLAC_TRUE;
  69185. }
  69186. #ifdef DRFLAC_64BIT
  69187. static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut)
  69188. {
  69189. drflac_uint32 resultHi;
  69190. drflac_uint32 resultLo;
  69191. DRFLAC_ASSERT(bitCount <= 64);
  69192. DRFLAC_ASSERT(bitCount > 32);
  69193. if (!drflac__read_uint32(bs, bitCount - 32, &resultHi)) {
  69194. return DRFLAC_FALSE;
  69195. }
  69196. if (!drflac__read_uint32(bs, 32, &resultLo)) {
  69197. return DRFLAC_FALSE;
  69198. }
  69199. *pResultOut = (((drflac_uint64)resultHi) << 32) | ((drflac_uint64)resultLo);
  69200. return DRFLAC_TRUE;
  69201. }
  69202. #endif
  69203. #if 0
  69204. static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut)
  69205. {
  69206. drflac_uint64 result;
  69207. drflac_uint64 signbit;
  69208. DRFLAC_ASSERT(bitCount <= 64);
  69209. if (!drflac__read_uint64(bs, bitCount, &result)) {
  69210. return DRFLAC_FALSE;
  69211. }
  69212. signbit = ((result >> (bitCount-1)) & 0x01);
  69213. result |= (~signbit + 1) << bitCount;
  69214. *pResultOut = (drflac_int64)result;
  69215. return DRFLAC_TRUE;
  69216. }
  69217. #endif
  69218. static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult)
  69219. {
  69220. drflac_uint32 result;
  69221. DRFLAC_ASSERT(bs != NULL);
  69222. DRFLAC_ASSERT(pResult != NULL);
  69223. DRFLAC_ASSERT(bitCount > 0);
  69224. DRFLAC_ASSERT(bitCount <= 16);
  69225. if (!drflac__read_uint32(bs, bitCount, &result)) {
  69226. return DRFLAC_FALSE;
  69227. }
  69228. *pResult = (drflac_uint16)result;
  69229. return DRFLAC_TRUE;
  69230. }
  69231. #if 0
  69232. static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult)
  69233. {
  69234. drflac_int32 result;
  69235. DRFLAC_ASSERT(bs != NULL);
  69236. DRFLAC_ASSERT(pResult != NULL);
  69237. DRFLAC_ASSERT(bitCount > 0);
  69238. DRFLAC_ASSERT(bitCount <= 16);
  69239. if (!drflac__read_int32(bs, bitCount, &result)) {
  69240. return DRFLAC_FALSE;
  69241. }
  69242. *pResult = (drflac_int16)result;
  69243. return DRFLAC_TRUE;
  69244. }
  69245. #endif
  69246. static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult)
  69247. {
  69248. drflac_uint32 result;
  69249. DRFLAC_ASSERT(bs != NULL);
  69250. DRFLAC_ASSERT(pResult != NULL);
  69251. DRFLAC_ASSERT(bitCount > 0);
  69252. DRFLAC_ASSERT(bitCount <= 8);
  69253. if (!drflac__read_uint32(bs, bitCount, &result)) {
  69254. return DRFLAC_FALSE;
  69255. }
  69256. *pResult = (drflac_uint8)result;
  69257. return DRFLAC_TRUE;
  69258. }
  69259. static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult)
  69260. {
  69261. drflac_int32 result;
  69262. DRFLAC_ASSERT(bs != NULL);
  69263. DRFLAC_ASSERT(pResult != NULL);
  69264. DRFLAC_ASSERT(bitCount > 0);
  69265. DRFLAC_ASSERT(bitCount <= 8);
  69266. if (!drflac__read_int32(bs, bitCount, &result)) {
  69267. return DRFLAC_FALSE;
  69268. }
  69269. *pResult = (drflac_int8)result;
  69270. return DRFLAC_TRUE;
  69271. }
  69272. static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek)
  69273. {
  69274. if (bitsToSeek <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69275. bs->consumedBits += (drflac_uint32)bitsToSeek;
  69276. bs->cache <<= bitsToSeek;
  69277. return DRFLAC_TRUE;
  69278. } else {
  69279. bitsToSeek -= DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  69280. bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  69281. bs->cache = 0;
  69282. #ifdef DRFLAC_64BIT
  69283. while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  69284. drflac_uint64 bin;
  69285. if (!drflac__read_uint64(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
  69286. return DRFLAC_FALSE;
  69287. }
  69288. bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
  69289. }
  69290. #else
  69291. while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  69292. drflac_uint32 bin;
  69293. if (!drflac__read_uint32(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
  69294. return DRFLAC_FALSE;
  69295. }
  69296. bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
  69297. }
  69298. #endif
  69299. while (bitsToSeek >= 8) {
  69300. drflac_uint8 bin;
  69301. if (!drflac__read_uint8(bs, 8, &bin)) {
  69302. return DRFLAC_FALSE;
  69303. }
  69304. bitsToSeek -= 8;
  69305. }
  69306. if (bitsToSeek > 0) {
  69307. drflac_uint8 bin;
  69308. if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin)) {
  69309. return DRFLAC_FALSE;
  69310. }
  69311. bitsToSeek = 0;
  69312. }
  69313. DRFLAC_ASSERT(bitsToSeek == 0);
  69314. return DRFLAC_TRUE;
  69315. }
  69316. }
  69317. static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs)
  69318. {
  69319. DRFLAC_ASSERT(bs != NULL);
  69320. if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
  69321. return DRFLAC_FALSE;
  69322. }
  69323. for (;;) {
  69324. drflac_uint8 hi;
  69325. #ifndef DR_FLAC_NO_CRC
  69326. drflac__reset_crc16(bs);
  69327. #endif
  69328. if (!drflac__read_uint8(bs, 8, &hi)) {
  69329. return DRFLAC_FALSE;
  69330. }
  69331. if (hi == 0xFF) {
  69332. drflac_uint8 lo;
  69333. if (!drflac__read_uint8(bs, 6, &lo)) {
  69334. return DRFLAC_FALSE;
  69335. }
  69336. if (lo == 0x3E) {
  69337. return DRFLAC_TRUE;
  69338. } else {
  69339. if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
  69340. return DRFLAC_FALSE;
  69341. }
  69342. }
  69343. }
  69344. }
  69345. }
  69346. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
  69347. #define DRFLAC_IMPLEMENT_CLZ_LZCNT
  69348. #endif
  69349. #if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(__clang__)
  69350. #define DRFLAC_IMPLEMENT_CLZ_MSVC
  69351. #endif
  69352. #if defined(__WATCOMC__) && defined(__386__)
  69353. #define DRFLAC_IMPLEMENT_CLZ_WATCOM
  69354. #endif
  69355. #ifdef __MRC__
  69356. #include <intrinsics.h>
  69357. #define DRFLAC_IMPLEMENT_CLZ_MRC
  69358. #endif
  69359. static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x)
  69360. {
  69361. drflac_uint32 n;
  69362. static drflac_uint32 clz_table_4[] = {
  69363. 0,
  69364. 4,
  69365. 3, 3,
  69366. 2, 2, 2, 2,
  69367. 1, 1, 1, 1, 1, 1, 1, 1
  69368. };
  69369. if (x == 0) {
  69370. return sizeof(x)*8;
  69371. }
  69372. n = clz_table_4[x >> (sizeof(x)*8 - 4)];
  69373. if (n == 0) {
  69374. #ifdef DRFLAC_64BIT
  69375. if ((x & ((drflac_uint64)0xFFFFFFFF << 32)) == 0) { n = 32; x <<= 32; }
  69376. if ((x & ((drflac_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; }
  69377. if ((x & ((drflac_uint64)0xFF000000 << 32)) == 0) { n += 8; x <<= 8; }
  69378. if ((x & ((drflac_uint64)0xF0000000 << 32)) == 0) { n += 4; x <<= 4; }
  69379. #else
  69380. if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; }
  69381. if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; }
  69382. if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; }
  69383. #endif
  69384. n += clz_table_4[x >> (sizeof(x)*8 - 4)];
  69385. }
  69386. return n - 1;
  69387. }
  69388. #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
  69389. static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported(void)
  69390. {
  69391. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
  69392. return DRFLAC_TRUE;
  69393. #elif defined(__MRC__)
  69394. return DRFLAC_TRUE;
  69395. #else
  69396. #ifdef DRFLAC_HAS_LZCNT_INTRINSIC
  69397. return drflac__gIsLZCNTSupported;
  69398. #else
  69399. return DRFLAC_FALSE;
  69400. #endif
  69401. #endif
  69402. }
  69403. static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x)
  69404. {
  69405. #if defined(_MSC_VER)
  69406. #ifdef DRFLAC_64BIT
  69407. return (drflac_uint32)__lzcnt64(x);
  69408. #else
  69409. return (drflac_uint32)__lzcnt(x);
  69410. #endif
  69411. #else
  69412. #if defined(__GNUC__) || defined(__clang__)
  69413. #if defined(DRFLAC_X64)
  69414. {
  69415. drflac_uint64 r;
  69416. __asm__ __volatile__ (
  69417. "lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
  69418. );
  69419. return (drflac_uint32)r;
  69420. }
  69421. #elif defined(DRFLAC_X86)
  69422. {
  69423. drflac_uint32 r;
  69424. __asm__ __volatile__ (
  69425. "lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
  69426. );
  69427. return r;
  69428. }
  69429. #elif defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) && !defined(DRFLAC_64BIT)
  69430. {
  69431. unsigned int r;
  69432. __asm__ __volatile__ (
  69433. #if defined(DRFLAC_64BIT)
  69434. "clz %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(x)
  69435. #else
  69436. "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x)
  69437. #endif
  69438. );
  69439. return r;
  69440. }
  69441. #else
  69442. if (x == 0) {
  69443. return sizeof(x)*8;
  69444. }
  69445. #ifdef DRFLAC_64BIT
  69446. return (drflac_uint32)__builtin_clzll((drflac_uint64)x);
  69447. #else
  69448. return (drflac_uint32)__builtin_clzl((drflac_uint32)x);
  69449. #endif
  69450. #endif
  69451. #else
  69452. #error "This compiler does not support the lzcnt intrinsic."
  69453. #endif
  69454. #endif
  69455. }
  69456. #endif
  69457. #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
  69458. #include <intrin.h>
  69459. static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x)
  69460. {
  69461. drflac_uint32 n;
  69462. if (x == 0) {
  69463. return sizeof(x)*8;
  69464. }
  69465. #ifdef DRFLAC_64BIT
  69466. _BitScanReverse64((unsigned long*)&n, x);
  69467. #else
  69468. _BitScanReverse((unsigned long*)&n, x);
  69469. #endif
  69470. return sizeof(x)*8 - n - 1;
  69471. }
  69472. #endif
  69473. #ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM
  69474. static __inline drflac_uint32 drflac__clz_watcom (drflac_uint32);
  69475. #ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT
  69476. #pragma aux drflac__clz_watcom_lzcnt = \
  69477. "db 0F3h, 0Fh, 0BDh, 0C0h" \
  69478. parm [eax] \
  69479. value [eax] \
  69480. modify nomemory;
  69481. #else
  69482. #pragma aux drflac__clz_watcom = \
  69483. "bsr eax, eax" \
  69484. "xor eax, 31" \
  69485. parm [eax] nomemory \
  69486. value [eax] \
  69487. modify exact [eax] nomemory;
  69488. #endif
  69489. #endif
  69490. static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x)
  69491. {
  69492. #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
  69493. if (drflac__is_lzcnt_supported()) {
  69494. return drflac__clz_lzcnt(x);
  69495. } else
  69496. #endif
  69497. {
  69498. #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
  69499. return drflac__clz_msvc(x);
  69500. #elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT)
  69501. return drflac__clz_watcom_lzcnt(x);
  69502. #elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM)
  69503. return (x == 0) ? sizeof(x)*8 : drflac__clz_watcom(x);
  69504. #elif defined(__MRC__)
  69505. return __cntlzw(x);
  69506. #else
  69507. return drflac__clz_software(x);
  69508. #endif
  69509. }
  69510. }
  69511. static DRFLAC_INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut)
  69512. {
  69513. drflac_uint32 zeroCounter = 0;
  69514. drflac_uint32 setBitOffsetPlus1;
  69515. while (bs->cache == 0) {
  69516. zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  69517. if (!drflac__reload_cache(bs)) {
  69518. return DRFLAC_FALSE;
  69519. }
  69520. }
  69521. if (bs->cache == 1) {
  69522. *pOffsetOut = zeroCounter + (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs) - 1;
  69523. if (!drflac__reload_cache(bs)) {
  69524. return DRFLAC_FALSE;
  69525. }
  69526. return DRFLAC_TRUE;
  69527. }
  69528. setBitOffsetPlus1 = drflac__clz(bs->cache);
  69529. setBitOffsetPlus1 += 1;
  69530. if (setBitOffsetPlus1 > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69531. return DRFLAC_FALSE;
  69532. }
  69533. bs->consumedBits += setBitOffsetPlus1;
  69534. bs->cache <<= setBitOffsetPlus1;
  69535. *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
  69536. return DRFLAC_TRUE;
  69537. }
  69538. static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart)
  69539. {
  69540. DRFLAC_ASSERT(bs != NULL);
  69541. DRFLAC_ASSERT(offsetFromStart > 0);
  69542. if (offsetFromStart > 0x7FFFFFFF) {
  69543. drflac_uint64 bytesRemaining = offsetFromStart;
  69544. if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
  69545. return DRFLAC_FALSE;
  69546. }
  69547. bytesRemaining -= 0x7FFFFFFF;
  69548. while (bytesRemaining > 0x7FFFFFFF) {
  69549. if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
  69550. return DRFLAC_FALSE;
  69551. }
  69552. bytesRemaining -= 0x7FFFFFFF;
  69553. }
  69554. if (bytesRemaining > 0) {
  69555. if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, drflac_seek_origin_current)) {
  69556. return DRFLAC_FALSE;
  69557. }
  69558. }
  69559. } else {
  69560. if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, drflac_seek_origin_start)) {
  69561. return DRFLAC_FALSE;
  69562. }
  69563. }
  69564. drflac__reset_cache(bs);
  69565. return DRFLAC_TRUE;
  69566. }
  69567. static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut)
  69568. {
  69569. drflac_uint8 crc;
  69570. drflac_uint64 result;
  69571. drflac_uint8 utf8[7] = {0};
  69572. int byteCount;
  69573. int i;
  69574. DRFLAC_ASSERT(bs != NULL);
  69575. DRFLAC_ASSERT(pNumberOut != NULL);
  69576. DRFLAC_ASSERT(pCRCOut != NULL);
  69577. crc = *pCRCOut;
  69578. if (!drflac__read_uint8(bs, 8, utf8)) {
  69579. *pNumberOut = 0;
  69580. return DRFLAC_AT_END;
  69581. }
  69582. crc = drflac_crc8(crc, utf8[0], 8);
  69583. if ((utf8[0] & 0x80) == 0) {
  69584. *pNumberOut = utf8[0];
  69585. *pCRCOut = crc;
  69586. return DRFLAC_SUCCESS;
  69587. }
  69588. if ((utf8[0] & 0xE0) == 0xC0) {
  69589. byteCount = 2;
  69590. } else if ((utf8[0] & 0xF0) == 0xE0) {
  69591. byteCount = 3;
  69592. } else if ((utf8[0] & 0xF8) == 0xF0) {
  69593. byteCount = 4;
  69594. } else if ((utf8[0] & 0xFC) == 0xF8) {
  69595. byteCount = 5;
  69596. } else if ((utf8[0] & 0xFE) == 0xFC) {
  69597. byteCount = 6;
  69598. } else if ((utf8[0] & 0xFF) == 0xFE) {
  69599. byteCount = 7;
  69600. } else {
  69601. *pNumberOut = 0;
  69602. return DRFLAC_CRC_MISMATCH;
  69603. }
  69604. DRFLAC_ASSERT(byteCount > 1);
  69605. result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
  69606. for (i = 1; i < byteCount; ++i) {
  69607. if (!drflac__read_uint8(bs, 8, utf8 + i)) {
  69608. *pNumberOut = 0;
  69609. return DRFLAC_AT_END;
  69610. }
  69611. crc = drflac_crc8(crc, utf8[i], 8);
  69612. result = (result << 6) | (utf8[i] & 0x3F);
  69613. }
  69614. *pNumberOut = result;
  69615. *pCRCOut = crc;
  69616. return DRFLAC_SUCCESS;
  69617. }
  69618. static DRFLAC_INLINE drflac_uint32 drflac__ilog2_u32(drflac_uint32 x)
  69619. {
  69620. #if 1
  69621. drflac_uint32 result = 0;
  69622. while (x > 0) {
  69623. result += 1;
  69624. x >>= 1;
  69625. }
  69626. return result;
  69627. #endif
  69628. }
  69629. static DRFLAC_INLINE drflac_bool32 drflac__use_64_bit_prediction(drflac_uint32 bitsPerSample, drflac_uint32 order, drflac_uint32 precision)
  69630. {
  69631. return bitsPerSample + precision + drflac__ilog2_u32(order) > 32;
  69632. }
  69633. #if defined(__clang__)
  69634. __attribute__((no_sanitize("signed-integer-overflow")))
  69635. #endif
  69636. static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
  69637. {
  69638. drflac_int32 prediction = 0;
  69639. DRFLAC_ASSERT(order <= 32);
  69640. switch (order)
  69641. {
  69642. case 32: prediction += coefficients[31] * pDecodedSamples[-32];
  69643. case 31: prediction += coefficients[30] * pDecodedSamples[-31];
  69644. case 30: prediction += coefficients[29] * pDecodedSamples[-30];
  69645. case 29: prediction += coefficients[28] * pDecodedSamples[-29];
  69646. case 28: prediction += coefficients[27] * pDecodedSamples[-28];
  69647. case 27: prediction += coefficients[26] * pDecodedSamples[-27];
  69648. case 26: prediction += coefficients[25] * pDecodedSamples[-26];
  69649. case 25: prediction += coefficients[24] * pDecodedSamples[-25];
  69650. case 24: prediction += coefficients[23] * pDecodedSamples[-24];
  69651. case 23: prediction += coefficients[22] * pDecodedSamples[-23];
  69652. case 22: prediction += coefficients[21] * pDecodedSamples[-22];
  69653. case 21: prediction += coefficients[20] * pDecodedSamples[-21];
  69654. case 20: prediction += coefficients[19] * pDecodedSamples[-20];
  69655. case 19: prediction += coefficients[18] * pDecodedSamples[-19];
  69656. case 18: prediction += coefficients[17] * pDecodedSamples[-18];
  69657. case 17: prediction += coefficients[16] * pDecodedSamples[-17];
  69658. case 16: prediction += coefficients[15] * pDecodedSamples[-16];
  69659. case 15: prediction += coefficients[14] * pDecodedSamples[-15];
  69660. case 14: prediction += coefficients[13] * pDecodedSamples[-14];
  69661. case 13: prediction += coefficients[12] * pDecodedSamples[-13];
  69662. case 12: prediction += coefficients[11] * pDecodedSamples[-12];
  69663. case 11: prediction += coefficients[10] * pDecodedSamples[-11];
  69664. case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
  69665. case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
  69666. case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
  69667. case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
  69668. case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
  69669. case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
  69670. case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
  69671. case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
  69672. case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
  69673. case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
  69674. }
  69675. return (drflac_int32)(prediction >> shift);
  69676. }
  69677. static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
  69678. {
  69679. drflac_int64 prediction;
  69680. DRFLAC_ASSERT(order <= 32);
  69681. #ifndef DRFLAC_64BIT
  69682. if (order == 8)
  69683. {
  69684. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69685. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69686. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69687. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  69688. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  69689. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  69690. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  69691. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  69692. }
  69693. else if (order == 7)
  69694. {
  69695. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69696. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69697. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69698. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  69699. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  69700. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  69701. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  69702. }
  69703. else if (order == 3)
  69704. {
  69705. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69706. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69707. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69708. }
  69709. else if (order == 6)
  69710. {
  69711. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69712. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69713. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69714. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  69715. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  69716. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  69717. }
  69718. else if (order == 5)
  69719. {
  69720. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69721. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69722. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69723. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  69724. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  69725. }
  69726. else if (order == 4)
  69727. {
  69728. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69729. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69730. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69731. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  69732. }
  69733. else if (order == 12)
  69734. {
  69735. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69736. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69737. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69738. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  69739. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  69740. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  69741. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  69742. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  69743. prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
  69744. prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
  69745. prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
  69746. prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
  69747. }
  69748. else if (order == 2)
  69749. {
  69750. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69751. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69752. }
  69753. else if (order == 1)
  69754. {
  69755. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69756. }
  69757. else if (order == 10)
  69758. {
  69759. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69760. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69761. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69762. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  69763. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  69764. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  69765. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  69766. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  69767. prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
  69768. prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
  69769. }
  69770. else if (order == 9)
  69771. {
  69772. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69773. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69774. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69775. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  69776. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  69777. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  69778. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  69779. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  69780. prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
  69781. }
  69782. else if (order == 11)
  69783. {
  69784. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  69785. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  69786. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  69787. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  69788. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  69789. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  69790. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  69791. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  69792. prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
  69793. prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
  69794. prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
  69795. }
  69796. else
  69797. {
  69798. int j;
  69799. prediction = 0;
  69800. for (j = 0; j < (int)order; ++j) {
  69801. prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1];
  69802. }
  69803. }
  69804. #endif
  69805. #ifdef DRFLAC_64BIT
  69806. prediction = 0;
  69807. switch (order)
  69808. {
  69809. case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32];
  69810. case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31];
  69811. case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30];
  69812. case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29];
  69813. case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28];
  69814. case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27];
  69815. case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26];
  69816. case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25];
  69817. case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24];
  69818. case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23];
  69819. case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22];
  69820. case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21];
  69821. case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20];
  69822. case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19];
  69823. case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18];
  69824. case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17];
  69825. case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16];
  69826. case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15];
  69827. case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14];
  69828. case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13];
  69829. case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
  69830. case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
  69831. case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10];
  69832. case 9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9];
  69833. case 8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8];
  69834. case 7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7];
  69835. case 6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6];
  69836. case 5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5];
  69837. case 4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4];
  69838. case 3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3];
  69839. case 2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2];
  69840. case 1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1];
  69841. }
  69842. #endif
  69843. return (drflac_int32)(prediction >> shift);
  69844. }
  69845. #if 0
  69846. static drflac_bool32 drflac__decode_samples_with_residual__rice__reference(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  69847. {
  69848. drflac_uint32 i;
  69849. DRFLAC_ASSERT(bs != NULL);
  69850. DRFLAC_ASSERT(pSamplesOut != NULL);
  69851. for (i = 0; i < count; ++i) {
  69852. drflac_uint32 zeroCounter = 0;
  69853. for (;;) {
  69854. drflac_uint8 bit;
  69855. if (!drflac__read_uint8(bs, 1, &bit)) {
  69856. return DRFLAC_FALSE;
  69857. }
  69858. if (bit == 0) {
  69859. zeroCounter += 1;
  69860. } else {
  69861. break;
  69862. }
  69863. }
  69864. drflac_uint32 decodedRice;
  69865. if (riceParam > 0) {
  69866. if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
  69867. return DRFLAC_FALSE;
  69868. }
  69869. } else {
  69870. decodedRice = 0;
  69871. }
  69872. decodedRice |= (zeroCounter << riceParam);
  69873. if ((decodedRice & 0x01)) {
  69874. decodedRice = ~(decodedRice >> 1);
  69875. } else {
  69876. decodedRice = (decodedRice >> 1);
  69877. }
  69878. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  69879. pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  69880. } else {
  69881. pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  69882. }
  69883. }
  69884. return DRFLAC_TRUE;
  69885. }
  69886. #endif
  69887. #if 0
  69888. static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
  69889. {
  69890. drflac_uint32 zeroCounter = 0;
  69891. drflac_uint32 decodedRice;
  69892. for (;;) {
  69893. drflac_uint8 bit;
  69894. if (!drflac__read_uint8(bs, 1, &bit)) {
  69895. return DRFLAC_FALSE;
  69896. }
  69897. if (bit == 0) {
  69898. zeroCounter += 1;
  69899. } else {
  69900. break;
  69901. }
  69902. }
  69903. if (riceParam > 0) {
  69904. if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
  69905. return DRFLAC_FALSE;
  69906. }
  69907. } else {
  69908. decodedRice = 0;
  69909. }
  69910. *pZeroCounterOut = zeroCounter;
  69911. *pRiceParamPartOut = decodedRice;
  69912. return DRFLAC_TRUE;
  69913. }
  69914. #endif
  69915. #if 0
  69916. static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
  69917. {
  69918. drflac_cache_t riceParamMask;
  69919. drflac_uint32 zeroCounter;
  69920. drflac_uint32 setBitOffsetPlus1;
  69921. drflac_uint32 riceParamPart;
  69922. drflac_uint32 riceLength;
  69923. DRFLAC_ASSERT(riceParam > 0);
  69924. riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam);
  69925. zeroCounter = 0;
  69926. while (bs->cache == 0) {
  69927. zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  69928. if (!drflac__reload_cache(bs)) {
  69929. return DRFLAC_FALSE;
  69930. }
  69931. }
  69932. setBitOffsetPlus1 = drflac__clz(bs->cache);
  69933. zeroCounter += setBitOffsetPlus1;
  69934. setBitOffsetPlus1 += 1;
  69935. riceLength = setBitOffsetPlus1 + riceParam;
  69936. if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69937. riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
  69938. bs->consumedBits += riceLength;
  69939. bs->cache <<= riceLength;
  69940. } else {
  69941. drflac_uint32 bitCountLo;
  69942. drflac_cache_t resultHi;
  69943. bs->consumedBits += riceLength;
  69944. bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1);
  69945. bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
  69946. resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam);
  69947. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  69948. #ifndef DR_FLAC_NO_CRC
  69949. drflac__update_crc16(bs);
  69950. #endif
  69951. bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  69952. bs->consumedBits = 0;
  69953. #ifndef DR_FLAC_NO_CRC
  69954. bs->crc16Cache = bs->cache;
  69955. #endif
  69956. } else {
  69957. if (!drflac__reload_cache(bs)) {
  69958. return DRFLAC_FALSE;
  69959. }
  69960. if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69961. return DRFLAC_FALSE;
  69962. }
  69963. }
  69964. riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
  69965. bs->consumedBits += bitCountLo;
  69966. bs->cache <<= bitCountLo;
  69967. }
  69968. pZeroCounterOut[0] = zeroCounter;
  69969. pRiceParamPartOut[0] = riceParamPart;
  69970. return DRFLAC_TRUE;
  69971. }
  69972. #endif
  69973. static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x1(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
  69974. {
  69975. drflac_uint32 riceParamPlus1 = riceParam + 1;
  69976. drflac_uint32 riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1);
  69977. drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
  69978. drflac_cache_t bs_cache = bs->cache;
  69979. drflac_uint32 bs_consumedBits = bs->consumedBits;
  69980. drflac_uint32 lzcount = drflac__clz(bs_cache);
  69981. if (lzcount < sizeof(bs_cache)*8) {
  69982. pZeroCounterOut[0] = lzcount;
  69983. extract_rice_param_part:
  69984. bs_cache <<= lzcount;
  69985. bs_consumedBits += lzcount;
  69986. if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
  69987. pRiceParamPartOut[0] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
  69988. bs_cache <<= riceParamPlus1;
  69989. bs_consumedBits += riceParamPlus1;
  69990. } else {
  69991. drflac_uint32 riceParamPartHi;
  69992. drflac_uint32 riceParamPartLo;
  69993. drflac_uint32 riceParamPartLoBitCount;
  69994. riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
  69995. riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
  69996. DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
  69997. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  69998. #ifndef DR_FLAC_NO_CRC
  69999. drflac__update_crc16(bs);
  70000. #endif
  70001. bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  70002. bs_consumedBits = riceParamPartLoBitCount;
  70003. #ifndef DR_FLAC_NO_CRC
  70004. bs->crc16Cache = bs_cache;
  70005. #endif
  70006. } else {
  70007. if (!drflac__reload_cache(bs)) {
  70008. return DRFLAC_FALSE;
  70009. }
  70010. if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  70011. return DRFLAC_FALSE;
  70012. }
  70013. bs_cache = bs->cache;
  70014. bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
  70015. }
  70016. riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount)));
  70017. pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo;
  70018. bs_cache <<= riceParamPartLoBitCount;
  70019. }
  70020. } else {
  70021. drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits);
  70022. for (;;) {
  70023. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  70024. #ifndef DR_FLAC_NO_CRC
  70025. drflac__update_crc16(bs);
  70026. #endif
  70027. bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  70028. bs_consumedBits = 0;
  70029. #ifndef DR_FLAC_NO_CRC
  70030. bs->crc16Cache = bs_cache;
  70031. #endif
  70032. } else {
  70033. if (!drflac__reload_cache(bs)) {
  70034. return DRFLAC_FALSE;
  70035. }
  70036. bs_cache = bs->cache;
  70037. bs_consumedBits = bs->consumedBits;
  70038. }
  70039. lzcount = drflac__clz(bs_cache);
  70040. zeroCounter += lzcount;
  70041. if (lzcount < sizeof(bs_cache)*8) {
  70042. break;
  70043. }
  70044. }
  70045. pZeroCounterOut[0] = zeroCounter;
  70046. goto extract_rice_param_part;
  70047. }
  70048. bs->cache = bs_cache;
  70049. bs->consumedBits = bs_consumedBits;
  70050. return DRFLAC_TRUE;
  70051. }
  70052. static DRFLAC_INLINE drflac_bool32 drflac__seek_rice_parts(drflac_bs* bs, drflac_uint8 riceParam)
  70053. {
  70054. drflac_uint32 riceParamPlus1 = riceParam + 1;
  70055. drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
  70056. drflac_cache_t bs_cache = bs->cache;
  70057. drflac_uint32 bs_consumedBits = bs->consumedBits;
  70058. drflac_uint32 lzcount = drflac__clz(bs_cache);
  70059. if (lzcount < sizeof(bs_cache)*8) {
  70060. extract_rice_param_part:
  70061. bs_cache <<= lzcount;
  70062. bs_consumedBits += lzcount;
  70063. if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
  70064. bs_cache <<= riceParamPlus1;
  70065. bs_consumedBits += riceParamPlus1;
  70066. } else {
  70067. drflac_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
  70068. DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
  70069. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  70070. #ifndef DR_FLAC_NO_CRC
  70071. drflac__update_crc16(bs);
  70072. #endif
  70073. bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  70074. bs_consumedBits = riceParamPartLoBitCount;
  70075. #ifndef DR_FLAC_NO_CRC
  70076. bs->crc16Cache = bs_cache;
  70077. #endif
  70078. } else {
  70079. if (!drflac__reload_cache(bs)) {
  70080. return DRFLAC_FALSE;
  70081. }
  70082. if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  70083. return DRFLAC_FALSE;
  70084. }
  70085. bs_cache = bs->cache;
  70086. bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
  70087. }
  70088. bs_cache <<= riceParamPartLoBitCount;
  70089. }
  70090. } else {
  70091. for (;;) {
  70092. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  70093. #ifndef DR_FLAC_NO_CRC
  70094. drflac__update_crc16(bs);
  70095. #endif
  70096. bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  70097. bs_consumedBits = 0;
  70098. #ifndef DR_FLAC_NO_CRC
  70099. bs->crc16Cache = bs_cache;
  70100. #endif
  70101. } else {
  70102. if (!drflac__reload_cache(bs)) {
  70103. return DRFLAC_FALSE;
  70104. }
  70105. bs_cache = bs->cache;
  70106. bs_consumedBits = bs->consumedBits;
  70107. }
  70108. lzcount = drflac__clz(bs_cache);
  70109. if (lzcount < sizeof(bs_cache)*8) {
  70110. break;
  70111. }
  70112. }
  70113. goto extract_rice_param_part;
  70114. }
  70115. bs->cache = bs_cache;
  70116. bs->consumedBits = bs_consumedBits;
  70117. return DRFLAC_TRUE;
  70118. }
  70119. static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar_zeroorder(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70120. {
  70121. drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70122. drflac_uint32 zeroCountPart0;
  70123. drflac_uint32 riceParamPart0;
  70124. drflac_uint32 riceParamMask;
  70125. drflac_uint32 i;
  70126. DRFLAC_ASSERT(bs != NULL);
  70127. DRFLAC_ASSERT(pSamplesOut != NULL);
  70128. (void)bitsPerSample;
  70129. (void)order;
  70130. (void)shift;
  70131. (void)coefficients;
  70132. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  70133. i = 0;
  70134. while (i < count) {
  70135. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
  70136. return DRFLAC_FALSE;
  70137. }
  70138. riceParamPart0 &= riceParamMask;
  70139. riceParamPart0 |= (zeroCountPart0 << riceParam);
  70140. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  70141. pSamplesOut[i] = riceParamPart0;
  70142. i += 1;
  70143. }
  70144. return DRFLAC_TRUE;
  70145. }
  70146. static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70147. {
  70148. drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70149. drflac_uint32 zeroCountPart0 = 0;
  70150. drflac_uint32 zeroCountPart1 = 0;
  70151. drflac_uint32 zeroCountPart2 = 0;
  70152. drflac_uint32 zeroCountPart3 = 0;
  70153. drflac_uint32 riceParamPart0 = 0;
  70154. drflac_uint32 riceParamPart1 = 0;
  70155. drflac_uint32 riceParamPart2 = 0;
  70156. drflac_uint32 riceParamPart3 = 0;
  70157. drflac_uint32 riceParamMask;
  70158. const drflac_int32* pSamplesOutEnd;
  70159. drflac_uint32 i;
  70160. DRFLAC_ASSERT(bs != NULL);
  70161. DRFLAC_ASSERT(pSamplesOut != NULL);
  70162. if (lpcOrder == 0) {
  70163. return drflac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  70164. }
  70165. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  70166. pSamplesOutEnd = pSamplesOut + (count & ~3);
  70167. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  70168. while (pSamplesOut < pSamplesOutEnd) {
  70169. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
  70170. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
  70171. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
  70172. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
  70173. return DRFLAC_FALSE;
  70174. }
  70175. riceParamPart0 &= riceParamMask;
  70176. riceParamPart1 &= riceParamMask;
  70177. riceParamPart2 &= riceParamMask;
  70178. riceParamPart3 &= riceParamMask;
  70179. riceParamPart0 |= (zeroCountPart0 << riceParam);
  70180. riceParamPart1 |= (zeroCountPart1 << riceParam);
  70181. riceParamPart2 |= (zeroCountPart2 << riceParam);
  70182. riceParamPart3 |= (zeroCountPart3 << riceParam);
  70183. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  70184. riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
  70185. riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
  70186. riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
  70187. pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  70188. pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
  70189. pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
  70190. pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
  70191. pSamplesOut += 4;
  70192. }
  70193. } else {
  70194. while (pSamplesOut < pSamplesOutEnd) {
  70195. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
  70196. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
  70197. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
  70198. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
  70199. return DRFLAC_FALSE;
  70200. }
  70201. riceParamPart0 &= riceParamMask;
  70202. riceParamPart1 &= riceParamMask;
  70203. riceParamPart2 &= riceParamMask;
  70204. riceParamPart3 &= riceParamMask;
  70205. riceParamPart0 |= (zeroCountPart0 << riceParam);
  70206. riceParamPart1 |= (zeroCountPart1 << riceParam);
  70207. riceParamPart2 |= (zeroCountPart2 << riceParam);
  70208. riceParamPart3 |= (zeroCountPart3 << riceParam);
  70209. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  70210. riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
  70211. riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
  70212. riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
  70213. pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  70214. pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
  70215. pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
  70216. pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
  70217. pSamplesOut += 4;
  70218. }
  70219. }
  70220. i = (count & ~3);
  70221. while (i < count) {
  70222. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
  70223. return DRFLAC_FALSE;
  70224. }
  70225. riceParamPart0 &= riceParamMask;
  70226. riceParamPart0 |= (zeroCountPart0 << riceParam);
  70227. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  70228. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  70229. pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  70230. } else {
  70231. pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  70232. }
  70233. i += 1;
  70234. pSamplesOut += 1;
  70235. }
  70236. return DRFLAC_TRUE;
  70237. }
  70238. #if defined(DRFLAC_SUPPORT_SSE2)
  70239. static DRFLAC_INLINE __m128i drflac__mm_packs_interleaved_epi32(__m128i a, __m128i b)
  70240. {
  70241. __m128i r;
  70242. r = _mm_packs_epi32(a, b);
  70243. r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0));
  70244. r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
  70245. r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
  70246. return r;
  70247. }
  70248. #endif
  70249. #if defined(DRFLAC_SUPPORT_SSE41)
  70250. static DRFLAC_INLINE __m128i drflac__mm_not_si128(__m128i a)
  70251. {
  70252. return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128()));
  70253. }
  70254. static DRFLAC_INLINE __m128i drflac__mm_hadd_epi32(__m128i x)
  70255. {
  70256. __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
  70257. __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2));
  70258. return _mm_add_epi32(x64, x32);
  70259. }
  70260. static DRFLAC_INLINE __m128i drflac__mm_hadd_epi64(__m128i x)
  70261. {
  70262. return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
  70263. }
  70264. static DRFLAC_INLINE __m128i drflac__mm_srai_epi64(__m128i x, int count)
  70265. {
  70266. __m128i lo = _mm_srli_epi64(x, count);
  70267. __m128i hi = _mm_srai_epi32(x, count);
  70268. hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0));
  70269. return _mm_or_si128(lo, hi);
  70270. }
  70271. static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_32(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70272. {
  70273. int i;
  70274. drflac_uint32 riceParamMask;
  70275. drflac_int32* pDecodedSamples = pSamplesOut;
  70276. drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  70277. drflac_uint32 zeroCountParts0 = 0;
  70278. drflac_uint32 zeroCountParts1 = 0;
  70279. drflac_uint32 zeroCountParts2 = 0;
  70280. drflac_uint32 zeroCountParts3 = 0;
  70281. drflac_uint32 riceParamParts0 = 0;
  70282. drflac_uint32 riceParamParts1 = 0;
  70283. drflac_uint32 riceParamParts2 = 0;
  70284. drflac_uint32 riceParamParts3 = 0;
  70285. __m128i coefficients128_0;
  70286. __m128i coefficients128_4;
  70287. __m128i coefficients128_8;
  70288. __m128i samples128_0;
  70289. __m128i samples128_4;
  70290. __m128i samples128_8;
  70291. __m128i riceParamMask128;
  70292. const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70293. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  70294. riceParamMask128 = _mm_set1_epi32(riceParamMask);
  70295. coefficients128_0 = _mm_setzero_si128();
  70296. coefficients128_4 = _mm_setzero_si128();
  70297. coefficients128_8 = _mm_setzero_si128();
  70298. samples128_0 = _mm_setzero_si128();
  70299. samples128_4 = _mm_setzero_si128();
  70300. samples128_8 = _mm_setzero_si128();
  70301. #if 1
  70302. {
  70303. int runningOrder = order;
  70304. if (runningOrder >= 4) {
  70305. coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
  70306. samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
  70307. runningOrder -= 4;
  70308. } else {
  70309. switch (runningOrder) {
  70310. case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break;
  70311. case 2: coefficients128_0 = _mm_set_epi32(0, 0, coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0, 0); break;
  70312. case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
  70313. }
  70314. runningOrder = 0;
  70315. }
  70316. if (runningOrder >= 4) {
  70317. coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
  70318. samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
  70319. runningOrder -= 4;
  70320. } else {
  70321. switch (runningOrder) {
  70322. case 3: coefficients128_4 = _mm_set_epi32(0, coefficients[6], coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], pSamplesOut[-7], 0); break;
  70323. case 2: coefficients128_4 = _mm_set_epi32(0, 0, coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], 0, 0); break;
  70324. case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
  70325. }
  70326. runningOrder = 0;
  70327. }
  70328. if (runningOrder == 4) {
  70329. coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
  70330. samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
  70331. runningOrder -= 4;
  70332. } else {
  70333. switch (runningOrder) {
  70334. case 3: coefficients128_8 = _mm_set_epi32(0, coefficients[10], coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], pSamplesOut[-11], 0); break;
  70335. case 2: coefficients128_8 = _mm_set_epi32(0, 0, coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], 0, 0); break;
  70336. case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
  70337. }
  70338. runningOrder = 0;
  70339. }
  70340. coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
  70341. coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
  70342. coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
  70343. }
  70344. #else
  70345. switch (order)
  70346. {
  70347. case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
  70348. case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
  70349. case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
  70350. case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
  70351. case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
  70352. case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
  70353. case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
  70354. case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
  70355. case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
  70356. case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
  70357. case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
  70358. case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
  70359. }
  70360. #endif
  70361. while (pDecodedSamples < pDecodedSamplesEnd) {
  70362. __m128i prediction128;
  70363. __m128i zeroCountPart128;
  70364. __m128i riceParamPart128;
  70365. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
  70366. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
  70367. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
  70368. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
  70369. return DRFLAC_FALSE;
  70370. }
  70371. zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
  70372. riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
  70373. riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
  70374. riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
  70375. riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01))), _mm_set1_epi32(0x01)));
  70376. if (order <= 4) {
  70377. for (i = 0; i < 4; i += 1) {
  70378. prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0);
  70379. prediction128 = drflac__mm_hadd_epi32(prediction128);
  70380. prediction128 = _mm_srai_epi32(prediction128, shift);
  70381. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  70382. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  70383. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  70384. }
  70385. } else if (order <= 8) {
  70386. for (i = 0; i < 4; i += 1) {
  70387. prediction128 = _mm_mullo_epi32(coefficients128_4, samples128_4);
  70388. prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
  70389. prediction128 = drflac__mm_hadd_epi32(prediction128);
  70390. prediction128 = _mm_srai_epi32(prediction128, shift);
  70391. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  70392. samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
  70393. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  70394. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  70395. }
  70396. } else {
  70397. for (i = 0; i < 4; i += 1) {
  70398. prediction128 = _mm_mullo_epi32(coefficients128_8, samples128_8);
  70399. prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4));
  70400. prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
  70401. prediction128 = drflac__mm_hadd_epi32(prediction128);
  70402. prediction128 = _mm_srai_epi32(prediction128, shift);
  70403. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  70404. samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
  70405. samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
  70406. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  70407. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  70408. }
  70409. }
  70410. _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
  70411. pDecodedSamples += 4;
  70412. }
  70413. i = (count & ~3);
  70414. while (i < (int)count) {
  70415. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
  70416. return DRFLAC_FALSE;
  70417. }
  70418. riceParamParts0 &= riceParamMask;
  70419. riceParamParts0 |= (zeroCountParts0 << riceParam);
  70420. riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
  70421. pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
  70422. i += 1;
  70423. pDecodedSamples += 1;
  70424. }
  70425. return DRFLAC_TRUE;
  70426. }
  70427. static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_64(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70428. {
  70429. int i;
  70430. drflac_uint32 riceParamMask;
  70431. drflac_int32* pDecodedSamples = pSamplesOut;
  70432. drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  70433. drflac_uint32 zeroCountParts0 = 0;
  70434. drflac_uint32 zeroCountParts1 = 0;
  70435. drflac_uint32 zeroCountParts2 = 0;
  70436. drflac_uint32 zeroCountParts3 = 0;
  70437. drflac_uint32 riceParamParts0 = 0;
  70438. drflac_uint32 riceParamParts1 = 0;
  70439. drflac_uint32 riceParamParts2 = 0;
  70440. drflac_uint32 riceParamParts3 = 0;
  70441. __m128i coefficients128_0;
  70442. __m128i coefficients128_4;
  70443. __m128i coefficients128_8;
  70444. __m128i samples128_0;
  70445. __m128i samples128_4;
  70446. __m128i samples128_8;
  70447. __m128i prediction128;
  70448. __m128i riceParamMask128;
  70449. const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70450. DRFLAC_ASSERT(order <= 12);
  70451. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  70452. riceParamMask128 = _mm_set1_epi32(riceParamMask);
  70453. prediction128 = _mm_setzero_si128();
  70454. coefficients128_0 = _mm_setzero_si128();
  70455. coefficients128_4 = _mm_setzero_si128();
  70456. coefficients128_8 = _mm_setzero_si128();
  70457. samples128_0 = _mm_setzero_si128();
  70458. samples128_4 = _mm_setzero_si128();
  70459. samples128_8 = _mm_setzero_si128();
  70460. #if 1
  70461. {
  70462. int runningOrder = order;
  70463. if (runningOrder >= 4) {
  70464. coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
  70465. samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
  70466. runningOrder -= 4;
  70467. } else {
  70468. switch (runningOrder) {
  70469. case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break;
  70470. case 2: coefficients128_0 = _mm_set_epi32(0, 0, coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0, 0); break;
  70471. case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
  70472. }
  70473. runningOrder = 0;
  70474. }
  70475. if (runningOrder >= 4) {
  70476. coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
  70477. samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
  70478. runningOrder -= 4;
  70479. } else {
  70480. switch (runningOrder) {
  70481. case 3: coefficients128_4 = _mm_set_epi32(0, coefficients[6], coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], pSamplesOut[-7], 0); break;
  70482. case 2: coefficients128_4 = _mm_set_epi32(0, 0, coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], 0, 0); break;
  70483. case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
  70484. }
  70485. runningOrder = 0;
  70486. }
  70487. if (runningOrder == 4) {
  70488. coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
  70489. samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
  70490. runningOrder -= 4;
  70491. } else {
  70492. switch (runningOrder) {
  70493. case 3: coefficients128_8 = _mm_set_epi32(0, coefficients[10], coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], pSamplesOut[-11], 0); break;
  70494. case 2: coefficients128_8 = _mm_set_epi32(0, 0, coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], 0, 0); break;
  70495. case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
  70496. }
  70497. runningOrder = 0;
  70498. }
  70499. coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
  70500. coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
  70501. coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
  70502. }
  70503. #else
  70504. switch (order)
  70505. {
  70506. case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
  70507. case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
  70508. case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
  70509. case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
  70510. case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
  70511. case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
  70512. case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
  70513. case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
  70514. case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
  70515. case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
  70516. case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
  70517. case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
  70518. }
  70519. #endif
  70520. while (pDecodedSamples < pDecodedSamplesEnd) {
  70521. __m128i zeroCountPart128;
  70522. __m128i riceParamPart128;
  70523. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
  70524. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
  70525. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
  70526. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
  70527. return DRFLAC_FALSE;
  70528. }
  70529. zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
  70530. riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
  70531. riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
  70532. riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
  70533. riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(1))), _mm_set1_epi32(1)));
  70534. for (i = 0; i < 4; i += 1) {
  70535. prediction128 = _mm_xor_si128(prediction128, prediction128);
  70536. switch (order)
  70537. {
  70538. case 12:
  70539. case 11: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_8, _MM_SHUFFLE(1, 1, 0, 0))));
  70540. case 10:
  70541. case 9: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_8, _MM_SHUFFLE(3, 3, 2, 2))));
  70542. case 8:
  70543. case 7: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_4, _MM_SHUFFLE(1, 1, 0, 0))));
  70544. case 6:
  70545. case 5: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_4, _MM_SHUFFLE(3, 3, 2, 2))));
  70546. case 4:
  70547. case 3: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_0, _MM_SHUFFLE(1, 1, 0, 0))));
  70548. case 2:
  70549. case 1: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_0, _MM_SHUFFLE(3, 3, 2, 2))));
  70550. }
  70551. prediction128 = drflac__mm_hadd_epi64(prediction128);
  70552. prediction128 = drflac__mm_srai_epi64(prediction128, shift);
  70553. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  70554. samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
  70555. samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
  70556. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  70557. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  70558. }
  70559. _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
  70560. pDecodedSamples += 4;
  70561. }
  70562. i = (count & ~3);
  70563. while (i < (int)count) {
  70564. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
  70565. return DRFLAC_FALSE;
  70566. }
  70567. riceParamParts0 &= riceParamMask;
  70568. riceParamParts0 |= (zeroCountParts0 << riceParam);
  70569. riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
  70570. pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
  70571. i += 1;
  70572. pDecodedSamples += 1;
  70573. }
  70574. return DRFLAC_TRUE;
  70575. }
  70576. static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70577. {
  70578. DRFLAC_ASSERT(bs != NULL);
  70579. DRFLAC_ASSERT(pSamplesOut != NULL);
  70580. if (lpcOrder > 0 && lpcOrder <= 12) {
  70581. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  70582. return drflac__decode_samples_with_residual__rice__sse41_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  70583. } else {
  70584. return drflac__decode_samples_with_residual__rice__sse41_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  70585. }
  70586. } else {
  70587. return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  70588. }
  70589. }
  70590. #endif
  70591. #if defined(DRFLAC_SUPPORT_NEON)
  70592. static DRFLAC_INLINE void drflac__vst2q_s32(drflac_int32* p, int32x4x2_t x)
  70593. {
  70594. vst1q_s32(p+0, x.val[0]);
  70595. vst1q_s32(p+4, x.val[1]);
  70596. }
  70597. static DRFLAC_INLINE void drflac__vst2q_u32(drflac_uint32* p, uint32x4x2_t x)
  70598. {
  70599. vst1q_u32(p+0, x.val[0]);
  70600. vst1q_u32(p+4, x.val[1]);
  70601. }
  70602. static DRFLAC_INLINE void drflac__vst2q_f32(float* p, float32x4x2_t x)
  70603. {
  70604. vst1q_f32(p+0, x.val[0]);
  70605. vst1q_f32(p+4, x.val[1]);
  70606. }
  70607. static DRFLAC_INLINE void drflac__vst2q_s16(drflac_int16* p, int16x4x2_t x)
  70608. {
  70609. vst1q_s16(p, vcombine_s16(x.val[0], x.val[1]));
  70610. }
  70611. static DRFLAC_INLINE void drflac__vst2q_u16(drflac_uint16* p, uint16x4x2_t x)
  70612. {
  70613. vst1q_u16(p, vcombine_u16(x.val[0], x.val[1]));
  70614. }
  70615. static DRFLAC_INLINE int32x4_t drflac__vdupq_n_s32x4(drflac_int32 x3, drflac_int32 x2, drflac_int32 x1, drflac_int32 x0)
  70616. {
  70617. drflac_int32 x[4];
  70618. x[3] = x3;
  70619. x[2] = x2;
  70620. x[1] = x1;
  70621. x[0] = x0;
  70622. return vld1q_s32(x);
  70623. }
  70624. static DRFLAC_INLINE int32x4_t drflac__valignrq_s32_1(int32x4_t a, int32x4_t b)
  70625. {
  70626. return vextq_s32(b, a, 1);
  70627. }
  70628. static DRFLAC_INLINE uint32x4_t drflac__valignrq_u32_1(uint32x4_t a, uint32x4_t b)
  70629. {
  70630. return vextq_u32(b, a, 1);
  70631. }
  70632. static DRFLAC_INLINE int32x2_t drflac__vhaddq_s32(int32x4_t x)
  70633. {
  70634. int32x2_t r = vadd_s32(vget_high_s32(x), vget_low_s32(x));
  70635. return vpadd_s32(r, r);
  70636. }
  70637. static DRFLAC_INLINE int64x1_t drflac__vhaddq_s64(int64x2_t x)
  70638. {
  70639. return vadd_s64(vget_high_s64(x), vget_low_s64(x));
  70640. }
  70641. static DRFLAC_INLINE int32x4_t drflac__vrevq_s32(int32x4_t x)
  70642. {
  70643. return vrev64q_s32(vcombine_s32(vget_high_s32(x), vget_low_s32(x)));
  70644. }
  70645. static DRFLAC_INLINE int32x4_t drflac__vnotq_s32(int32x4_t x)
  70646. {
  70647. return veorq_s32(x, vdupq_n_s32(0xFFFFFFFF));
  70648. }
  70649. static DRFLAC_INLINE uint32x4_t drflac__vnotq_u32(uint32x4_t x)
  70650. {
  70651. return veorq_u32(x, vdupq_n_u32(0xFFFFFFFF));
  70652. }
  70653. static drflac_bool32 drflac__decode_samples_with_residual__rice__neon_32(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70654. {
  70655. int i;
  70656. drflac_uint32 riceParamMask;
  70657. drflac_int32* pDecodedSamples = pSamplesOut;
  70658. drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  70659. drflac_uint32 zeroCountParts[4];
  70660. drflac_uint32 riceParamParts[4];
  70661. int32x4_t coefficients128_0;
  70662. int32x4_t coefficients128_4;
  70663. int32x4_t coefficients128_8;
  70664. int32x4_t samples128_0;
  70665. int32x4_t samples128_4;
  70666. int32x4_t samples128_8;
  70667. uint32x4_t riceParamMask128;
  70668. int32x4_t riceParam128;
  70669. int32x2_t shift64;
  70670. uint32x4_t one128;
  70671. const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70672. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  70673. riceParamMask128 = vdupq_n_u32(riceParamMask);
  70674. riceParam128 = vdupq_n_s32(riceParam);
  70675. shift64 = vdup_n_s32(-shift);
  70676. one128 = vdupq_n_u32(1);
  70677. {
  70678. int runningOrder = order;
  70679. drflac_int32 tempC[4] = {0, 0, 0, 0};
  70680. drflac_int32 tempS[4] = {0, 0, 0, 0};
  70681. if (runningOrder >= 4) {
  70682. coefficients128_0 = vld1q_s32(coefficients + 0);
  70683. samples128_0 = vld1q_s32(pSamplesOut - 4);
  70684. runningOrder -= 4;
  70685. } else {
  70686. switch (runningOrder) {
  70687. case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3];
  70688. case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2];
  70689. case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1];
  70690. }
  70691. coefficients128_0 = vld1q_s32(tempC);
  70692. samples128_0 = vld1q_s32(tempS);
  70693. runningOrder = 0;
  70694. }
  70695. if (runningOrder >= 4) {
  70696. coefficients128_4 = vld1q_s32(coefficients + 4);
  70697. samples128_4 = vld1q_s32(pSamplesOut - 8);
  70698. runningOrder -= 4;
  70699. } else {
  70700. switch (runningOrder) {
  70701. case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7];
  70702. case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6];
  70703. case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5];
  70704. }
  70705. coefficients128_4 = vld1q_s32(tempC);
  70706. samples128_4 = vld1q_s32(tempS);
  70707. runningOrder = 0;
  70708. }
  70709. if (runningOrder == 4) {
  70710. coefficients128_8 = vld1q_s32(coefficients + 8);
  70711. samples128_8 = vld1q_s32(pSamplesOut - 12);
  70712. runningOrder -= 4;
  70713. } else {
  70714. switch (runningOrder) {
  70715. case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11];
  70716. case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10];
  70717. case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9];
  70718. }
  70719. coefficients128_8 = vld1q_s32(tempC);
  70720. samples128_8 = vld1q_s32(tempS);
  70721. runningOrder = 0;
  70722. }
  70723. coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
  70724. coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
  70725. coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
  70726. }
  70727. while (pDecodedSamples < pDecodedSamplesEnd) {
  70728. int32x4_t prediction128;
  70729. int32x2_t prediction64;
  70730. uint32x4_t zeroCountPart128;
  70731. uint32x4_t riceParamPart128;
  70732. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
  70733. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
  70734. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
  70735. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
  70736. return DRFLAC_FALSE;
  70737. }
  70738. zeroCountPart128 = vld1q_u32(zeroCountParts);
  70739. riceParamPart128 = vld1q_u32(riceParamParts);
  70740. riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
  70741. riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
  70742. riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
  70743. if (order <= 4) {
  70744. for (i = 0; i < 4; i += 1) {
  70745. prediction128 = vmulq_s32(coefficients128_0, samples128_0);
  70746. prediction64 = drflac__vhaddq_s32(prediction128);
  70747. prediction64 = vshl_s32(prediction64, shift64);
  70748. prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  70749. samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  70750. riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  70751. }
  70752. } else if (order <= 8) {
  70753. for (i = 0; i < 4; i += 1) {
  70754. prediction128 = vmulq_s32(coefficients128_4, samples128_4);
  70755. prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
  70756. prediction64 = drflac__vhaddq_s32(prediction128);
  70757. prediction64 = vshl_s32(prediction64, shift64);
  70758. prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  70759. samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
  70760. samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  70761. riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  70762. }
  70763. } else {
  70764. for (i = 0; i < 4; i += 1) {
  70765. prediction128 = vmulq_s32(coefficients128_8, samples128_8);
  70766. prediction128 = vmlaq_s32(prediction128, coefficients128_4, samples128_4);
  70767. prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
  70768. prediction64 = drflac__vhaddq_s32(prediction128);
  70769. prediction64 = vshl_s32(prediction64, shift64);
  70770. prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  70771. samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
  70772. samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
  70773. samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  70774. riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  70775. }
  70776. }
  70777. vst1q_s32(pDecodedSamples, samples128_0);
  70778. pDecodedSamples += 4;
  70779. }
  70780. i = (count & ~3);
  70781. while (i < (int)count) {
  70782. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
  70783. return DRFLAC_FALSE;
  70784. }
  70785. riceParamParts[0] &= riceParamMask;
  70786. riceParamParts[0] |= (zeroCountParts[0] << riceParam);
  70787. riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
  70788. pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
  70789. i += 1;
  70790. pDecodedSamples += 1;
  70791. }
  70792. return DRFLAC_TRUE;
  70793. }
  70794. static drflac_bool32 drflac__decode_samples_with_residual__rice__neon_64(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70795. {
  70796. int i;
  70797. drflac_uint32 riceParamMask;
  70798. drflac_int32* pDecodedSamples = pSamplesOut;
  70799. drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  70800. drflac_uint32 zeroCountParts[4];
  70801. drflac_uint32 riceParamParts[4];
  70802. int32x4_t coefficients128_0;
  70803. int32x4_t coefficients128_4;
  70804. int32x4_t coefficients128_8;
  70805. int32x4_t samples128_0;
  70806. int32x4_t samples128_4;
  70807. int32x4_t samples128_8;
  70808. uint32x4_t riceParamMask128;
  70809. int32x4_t riceParam128;
  70810. int64x1_t shift64;
  70811. uint32x4_t one128;
  70812. int64x2_t prediction128 = { 0 };
  70813. uint32x4_t zeroCountPart128;
  70814. uint32x4_t riceParamPart128;
  70815. const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70816. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  70817. riceParamMask128 = vdupq_n_u32(riceParamMask);
  70818. riceParam128 = vdupq_n_s32(riceParam);
  70819. shift64 = vdup_n_s64(-shift);
  70820. one128 = vdupq_n_u32(1);
  70821. {
  70822. int runningOrder = order;
  70823. drflac_int32 tempC[4] = {0, 0, 0, 0};
  70824. drflac_int32 tempS[4] = {0, 0, 0, 0};
  70825. if (runningOrder >= 4) {
  70826. coefficients128_0 = vld1q_s32(coefficients + 0);
  70827. samples128_0 = vld1q_s32(pSamplesOut - 4);
  70828. runningOrder -= 4;
  70829. } else {
  70830. switch (runningOrder) {
  70831. case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3];
  70832. case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2];
  70833. case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1];
  70834. }
  70835. coefficients128_0 = vld1q_s32(tempC);
  70836. samples128_0 = vld1q_s32(tempS);
  70837. runningOrder = 0;
  70838. }
  70839. if (runningOrder >= 4) {
  70840. coefficients128_4 = vld1q_s32(coefficients + 4);
  70841. samples128_4 = vld1q_s32(pSamplesOut - 8);
  70842. runningOrder -= 4;
  70843. } else {
  70844. switch (runningOrder) {
  70845. case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7];
  70846. case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6];
  70847. case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5];
  70848. }
  70849. coefficients128_4 = vld1q_s32(tempC);
  70850. samples128_4 = vld1q_s32(tempS);
  70851. runningOrder = 0;
  70852. }
  70853. if (runningOrder == 4) {
  70854. coefficients128_8 = vld1q_s32(coefficients + 8);
  70855. samples128_8 = vld1q_s32(pSamplesOut - 12);
  70856. runningOrder -= 4;
  70857. } else {
  70858. switch (runningOrder) {
  70859. case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11];
  70860. case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10];
  70861. case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9];
  70862. }
  70863. coefficients128_8 = vld1q_s32(tempC);
  70864. samples128_8 = vld1q_s32(tempS);
  70865. runningOrder = 0;
  70866. }
  70867. coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
  70868. coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
  70869. coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
  70870. }
  70871. while (pDecodedSamples < pDecodedSamplesEnd) {
  70872. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
  70873. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
  70874. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
  70875. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
  70876. return DRFLAC_FALSE;
  70877. }
  70878. zeroCountPart128 = vld1q_u32(zeroCountParts);
  70879. riceParamPart128 = vld1q_u32(riceParamParts);
  70880. riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
  70881. riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
  70882. riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
  70883. for (i = 0; i < 4; i += 1) {
  70884. int64x1_t prediction64;
  70885. prediction128 = veorq_s64(prediction128, prediction128);
  70886. switch (order)
  70887. {
  70888. case 12:
  70889. case 11: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_8), vget_low_s32(samples128_8)));
  70890. case 10:
  70891. case 9: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_8), vget_high_s32(samples128_8)));
  70892. case 8:
  70893. case 7: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_4), vget_low_s32(samples128_4)));
  70894. case 6:
  70895. case 5: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_4), vget_high_s32(samples128_4)));
  70896. case 4:
  70897. case 3: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_0), vget_low_s32(samples128_0)));
  70898. case 2:
  70899. case 1: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_0), vget_high_s32(samples128_0)));
  70900. }
  70901. prediction64 = drflac__vhaddq_s64(prediction128);
  70902. prediction64 = vshl_s64(prediction64, shift64);
  70903. prediction64 = vadd_s64(prediction64, vdup_n_s64(vgetq_lane_u32(riceParamPart128, 0)));
  70904. samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
  70905. samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
  70906. samples128_0 = drflac__valignrq_s32_1(vcombine_s32(vreinterpret_s32_s64(prediction64), vdup_n_s32(0)), samples128_0);
  70907. riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  70908. }
  70909. vst1q_s32(pDecodedSamples, samples128_0);
  70910. pDecodedSamples += 4;
  70911. }
  70912. i = (count & ~3);
  70913. while (i < (int)count) {
  70914. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
  70915. return DRFLAC_FALSE;
  70916. }
  70917. riceParamParts[0] &= riceParamMask;
  70918. riceParamParts[0] |= (zeroCountParts[0] << riceParam);
  70919. riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
  70920. pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
  70921. i += 1;
  70922. pDecodedSamples += 1;
  70923. }
  70924. return DRFLAC_TRUE;
  70925. }
  70926. static drflac_bool32 drflac__decode_samples_with_residual__rice__neon(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70927. {
  70928. DRFLAC_ASSERT(bs != NULL);
  70929. DRFLAC_ASSERT(pSamplesOut != NULL);
  70930. if (lpcOrder > 0 && lpcOrder <= 12) {
  70931. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  70932. return drflac__decode_samples_with_residual__rice__neon_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  70933. } else {
  70934. return drflac__decode_samples_with_residual__rice__neon_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  70935. }
  70936. } else {
  70937. return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  70938. }
  70939. }
  70940. #endif
  70941. static drflac_bool32 drflac__decode_samples_with_residual__rice(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70942. {
  70943. #if defined(DRFLAC_SUPPORT_SSE41)
  70944. if (drflac__gIsSSE41Supported) {
  70945. return drflac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  70946. } else
  70947. #elif defined(DRFLAC_SUPPORT_NEON)
  70948. if (drflac__gIsNEONSupported) {
  70949. return drflac__decode_samples_with_residual__rice__neon(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  70950. } else
  70951. #endif
  70952. {
  70953. #if 0
  70954. return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  70955. #else
  70956. return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  70957. #endif
  70958. }
  70959. }
  70960. static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam)
  70961. {
  70962. drflac_uint32 i;
  70963. DRFLAC_ASSERT(bs != NULL);
  70964. for (i = 0; i < count; ++i) {
  70965. if (!drflac__seek_rice_parts(bs, riceParam)) {
  70966. return DRFLAC_FALSE;
  70967. }
  70968. }
  70969. return DRFLAC_TRUE;
  70970. }
  70971. #if defined(__clang__)
  70972. __attribute__((no_sanitize("signed-integer-overflow")))
  70973. #endif
  70974. static drflac_bool32 drflac__decode_samples_with_residual__unencoded(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 unencodedBitsPerSample, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  70975. {
  70976. drflac_uint32 i;
  70977. DRFLAC_ASSERT(bs != NULL);
  70978. DRFLAC_ASSERT(unencodedBitsPerSample <= 31);
  70979. DRFLAC_ASSERT(pSamplesOut != NULL);
  70980. for (i = 0; i < count; ++i) {
  70981. if (unencodedBitsPerSample > 0) {
  70982. if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) {
  70983. return DRFLAC_FALSE;
  70984. }
  70985. } else {
  70986. pSamplesOut[i] = 0;
  70987. }
  70988. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  70989. pSamplesOut[i] += drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  70990. } else {
  70991. pSamplesOut[i] += drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  70992. }
  70993. }
  70994. return DRFLAC_TRUE;
  70995. }
  70996. static drflac_bool32 drflac__decode_samples_with_residual(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 blockSize, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
  70997. {
  70998. drflac_uint8 residualMethod;
  70999. drflac_uint8 partitionOrder;
  71000. drflac_uint32 samplesInPartition;
  71001. drflac_uint32 partitionsRemaining;
  71002. DRFLAC_ASSERT(bs != NULL);
  71003. DRFLAC_ASSERT(blockSize != 0);
  71004. DRFLAC_ASSERT(pDecodedSamples != NULL);
  71005. if (!drflac__read_uint8(bs, 2, &residualMethod)) {
  71006. return DRFLAC_FALSE;
  71007. }
  71008. if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  71009. return DRFLAC_FALSE;
  71010. }
  71011. pDecodedSamples += lpcOrder;
  71012. if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
  71013. return DRFLAC_FALSE;
  71014. }
  71015. if (partitionOrder > 8) {
  71016. return DRFLAC_FALSE;
  71017. }
  71018. if ((blockSize / (1 << partitionOrder)) < lpcOrder) {
  71019. return DRFLAC_FALSE;
  71020. }
  71021. samplesInPartition = (blockSize / (1 << partitionOrder)) - lpcOrder;
  71022. partitionsRemaining = (1 << partitionOrder);
  71023. for (;;) {
  71024. drflac_uint8 riceParam = 0;
  71025. if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
  71026. if (!drflac__read_uint8(bs, 4, &riceParam)) {
  71027. return DRFLAC_FALSE;
  71028. }
  71029. if (riceParam == 15) {
  71030. riceParam = 0xFF;
  71031. }
  71032. } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  71033. if (!drflac__read_uint8(bs, 5, &riceParam)) {
  71034. return DRFLAC_FALSE;
  71035. }
  71036. if (riceParam == 31) {
  71037. riceParam = 0xFF;
  71038. }
  71039. }
  71040. if (riceParam != 0xFF) {
  71041. if (!drflac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
  71042. return DRFLAC_FALSE;
  71043. }
  71044. } else {
  71045. drflac_uint8 unencodedBitsPerSample = 0;
  71046. if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
  71047. return DRFLAC_FALSE;
  71048. }
  71049. if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
  71050. return DRFLAC_FALSE;
  71051. }
  71052. }
  71053. pDecodedSamples += samplesInPartition;
  71054. if (partitionsRemaining == 1) {
  71055. break;
  71056. }
  71057. partitionsRemaining -= 1;
  71058. if (partitionOrder != 0) {
  71059. samplesInPartition = blockSize / (1 << partitionOrder);
  71060. }
  71061. }
  71062. return DRFLAC_TRUE;
  71063. }
  71064. static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order)
  71065. {
  71066. drflac_uint8 residualMethod;
  71067. drflac_uint8 partitionOrder;
  71068. drflac_uint32 samplesInPartition;
  71069. drflac_uint32 partitionsRemaining;
  71070. DRFLAC_ASSERT(bs != NULL);
  71071. DRFLAC_ASSERT(blockSize != 0);
  71072. if (!drflac__read_uint8(bs, 2, &residualMethod)) {
  71073. return DRFLAC_FALSE;
  71074. }
  71075. if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  71076. return DRFLAC_FALSE;
  71077. }
  71078. if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
  71079. return DRFLAC_FALSE;
  71080. }
  71081. if (partitionOrder > 8) {
  71082. return DRFLAC_FALSE;
  71083. }
  71084. if ((blockSize / (1 << partitionOrder)) <= order) {
  71085. return DRFLAC_FALSE;
  71086. }
  71087. samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
  71088. partitionsRemaining = (1 << partitionOrder);
  71089. for (;;)
  71090. {
  71091. drflac_uint8 riceParam = 0;
  71092. if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
  71093. if (!drflac__read_uint8(bs, 4, &riceParam)) {
  71094. return DRFLAC_FALSE;
  71095. }
  71096. if (riceParam == 15) {
  71097. riceParam = 0xFF;
  71098. }
  71099. } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  71100. if (!drflac__read_uint8(bs, 5, &riceParam)) {
  71101. return DRFLAC_FALSE;
  71102. }
  71103. if (riceParam == 31) {
  71104. riceParam = 0xFF;
  71105. }
  71106. }
  71107. if (riceParam != 0xFF) {
  71108. if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) {
  71109. return DRFLAC_FALSE;
  71110. }
  71111. } else {
  71112. drflac_uint8 unencodedBitsPerSample = 0;
  71113. if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
  71114. return DRFLAC_FALSE;
  71115. }
  71116. if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) {
  71117. return DRFLAC_FALSE;
  71118. }
  71119. }
  71120. if (partitionsRemaining == 1) {
  71121. break;
  71122. }
  71123. partitionsRemaining -= 1;
  71124. samplesInPartition = blockSize / (1 << partitionOrder);
  71125. }
  71126. return DRFLAC_TRUE;
  71127. }
  71128. static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
  71129. {
  71130. drflac_uint32 i;
  71131. drflac_int32 sample;
  71132. if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
  71133. return DRFLAC_FALSE;
  71134. }
  71135. for (i = 0; i < blockSize; ++i) {
  71136. pDecodedSamples[i] = sample;
  71137. }
  71138. return DRFLAC_TRUE;
  71139. }
  71140. static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
  71141. {
  71142. drflac_uint32 i;
  71143. for (i = 0; i < blockSize; ++i) {
  71144. drflac_int32 sample;
  71145. if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
  71146. return DRFLAC_FALSE;
  71147. }
  71148. pDecodedSamples[i] = sample;
  71149. }
  71150. return DRFLAC_TRUE;
  71151. }
  71152. static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
  71153. {
  71154. drflac_uint32 i;
  71155. static drflac_int32 lpcCoefficientsTable[5][4] = {
  71156. {0, 0, 0, 0},
  71157. {1, 0, 0, 0},
  71158. {2, -1, 0, 0},
  71159. {3, -3, 1, 0},
  71160. {4, -6, 4, -1}
  71161. };
  71162. for (i = 0; i < lpcOrder; ++i) {
  71163. drflac_int32 sample;
  71164. if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
  71165. return DRFLAC_FALSE;
  71166. }
  71167. pDecodedSamples[i] = sample;
  71168. }
  71169. if (!drflac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, 4, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) {
  71170. return DRFLAC_FALSE;
  71171. }
  71172. return DRFLAC_TRUE;
  71173. }
  71174. static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
  71175. {
  71176. drflac_uint8 i;
  71177. drflac_uint8 lpcPrecision;
  71178. drflac_int8 lpcShift;
  71179. drflac_int32 coefficients[32];
  71180. for (i = 0; i < lpcOrder; ++i) {
  71181. drflac_int32 sample;
  71182. if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
  71183. return DRFLAC_FALSE;
  71184. }
  71185. pDecodedSamples[i] = sample;
  71186. }
  71187. if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
  71188. return DRFLAC_FALSE;
  71189. }
  71190. if (lpcPrecision == 15) {
  71191. return DRFLAC_FALSE;
  71192. }
  71193. lpcPrecision += 1;
  71194. if (!drflac__read_int8(bs, 5, &lpcShift)) {
  71195. return DRFLAC_FALSE;
  71196. }
  71197. if (lpcShift < 0) {
  71198. return DRFLAC_FALSE;
  71199. }
  71200. DRFLAC_ZERO_MEMORY(coefficients, sizeof(coefficients));
  71201. for (i = 0; i < lpcOrder; ++i) {
  71202. if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) {
  71203. return DRFLAC_FALSE;
  71204. }
  71205. }
  71206. if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
  71207. return DRFLAC_FALSE;
  71208. }
  71209. return DRFLAC_TRUE;
  71210. }
  71211. static drflac_bool32 drflac__read_next_flac_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header)
  71212. {
  71213. const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
  71214. const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1};
  71215. DRFLAC_ASSERT(bs != NULL);
  71216. DRFLAC_ASSERT(header != NULL);
  71217. for (;;) {
  71218. drflac_uint8 crc8 = 0xCE;
  71219. drflac_uint8 reserved = 0;
  71220. drflac_uint8 blockingStrategy = 0;
  71221. drflac_uint8 blockSize = 0;
  71222. drflac_uint8 sampleRate = 0;
  71223. drflac_uint8 channelAssignment = 0;
  71224. drflac_uint8 bitsPerSample = 0;
  71225. drflac_bool32 isVariableBlockSize;
  71226. if (!drflac__find_and_seek_to_next_sync_code(bs)) {
  71227. return DRFLAC_FALSE;
  71228. }
  71229. if (!drflac__read_uint8(bs, 1, &reserved)) {
  71230. return DRFLAC_FALSE;
  71231. }
  71232. if (reserved == 1) {
  71233. continue;
  71234. }
  71235. crc8 = drflac_crc8(crc8, reserved, 1);
  71236. if (!drflac__read_uint8(bs, 1, &blockingStrategy)) {
  71237. return DRFLAC_FALSE;
  71238. }
  71239. crc8 = drflac_crc8(crc8, blockingStrategy, 1);
  71240. if (!drflac__read_uint8(bs, 4, &blockSize)) {
  71241. return DRFLAC_FALSE;
  71242. }
  71243. if (blockSize == 0) {
  71244. continue;
  71245. }
  71246. crc8 = drflac_crc8(crc8, blockSize, 4);
  71247. if (!drflac__read_uint8(bs, 4, &sampleRate)) {
  71248. return DRFLAC_FALSE;
  71249. }
  71250. crc8 = drflac_crc8(crc8, sampleRate, 4);
  71251. if (!drflac__read_uint8(bs, 4, &channelAssignment)) {
  71252. return DRFLAC_FALSE;
  71253. }
  71254. if (channelAssignment > 10) {
  71255. continue;
  71256. }
  71257. crc8 = drflac_crc8(crc8, channelAssignment, 4);
  71258. if (!drflac__read_uint8(bs, 3, &bitsPerSample)) {
  71259. return DRFLAC_FALSE;
  71260. }
  71261. if (bitsPerSample == 3 || bitsPerSample == 7) {
  71262. continue;
  71263. }
  71264. crc8 = drflac_crc8(crc8, bitsPerSample, 3);
  71265. if (!drflac__read_uint8(bs, 1, &reserved)) {
  71266. return DRFLAC_FALSE;
  71267. }
  71268. if (reserved == 1) {
  71269. continue;
  71270. }
  71271. crc8 = drflac_crc8(crc8, reserved, 1);
  71272. isVariableBlockSize = blockingStrategy == 1;
  71273. if (isVariableBlockSize) {
  71274. drflac_uint64 pcmFrameNumber;
  71275. drflac_result result = drflac__read_utf8_coded_number(bs, &pcmFrameNumber, &crc8);
  71276. if (result != DRFLAC_SUCCESS) {
  71277. if (result == DRFLAC_AT_END) {
  71278. return DRFLAC_FALSE;
  71279. } else {
  71280. continue;
  71281. }
  71282. }
  71283. header->flacFrameNumber = 0;
  71284. header->pcmFrameNumber = pcmFrameNumber;
  71285. } else {
  71286. drflac_uint64 flacFrameNumber = 0;
  71287. drflac_result result = drflac__read_utf8_coded_number(bs, &flacFrameNumber, &crc8);
  71288. if (result != DRFLAC_SUCCESS) {
  71289. if (result == DRFLAC_AT_END) {
  71290. return DRFLAC_FALSE;
  71291. } else {
  71292. continue;
  71293. }
  71294. }
  71295. header->flacFrameNumber = (drflac_uint32)flacFrameNumber;
  71296. header->pcmFrameNumber = 0;
  71297. }
  71298. DRFLAC_ASSERT(blockSize > 0);
  71299. if (blockSize == 1) {
  71300. header->blockSizeInPCMFrames = 192;
  71301. } else if (blockSize <= 5) {
  71302. DRFLAC_ASSERT(blockSize >= 2);
  71303. header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2));
  71304. } else if (blockSize == 6) {
  71305. if (!drflac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) {
  71306. return DRFLAC_FALSE;
  71307. }
  71308. crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 8);
  71309. header->blockSizeInPCMFrames += 1;
  71310. } else if (blockSize == 7) {
  71311. if (!drflac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) {
  71312. return DRFLAC_FALSE;
  71313. }
  71314. crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 16);
  71315. if (header->blockSizeInPCMFrames == 0xFFFF) {
  71316. return DRFLAC_FALSE;
  71317. }
  71318. header->blockSizeInPCMFrames += 1;
  71319. } else {
  71320. DRFLAC_ASSERT(blockSize >= 8);
  71321. header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8));
  71322. }
  71323. if (sampleRate <= 11) {
  71324. header->sampleRate = sampleRateTable[sampleRate];
  71325. } else if (sampleRate == 12) {
  71326. if (!drflac__read_uint32(bs, 8, &header->sampleRate)) {
  71327. return DRFLAC_FALSE;
  71328. }
  71329. crc8 = drflac_crc8(crc8, header->sampleRate, 8);
  71330. header->sampleRate *= 1000;
  71331. } else if (sampleRate == 13) {
  71332. if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
  71333. return DRFLAC_FALSE;
  71334. }
  71335. crc8 = drflac_crc8(crc8, header->sampleRate, 16);
  71336. } else if (sampleRate == 14) {
  71337. if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
  71338. return DRFLAC_FALSE;
  71339. }
  71340. crc8 = drflac_crc8(crc8, header->sampleRate, 16);
  71341. header->sampleRate *= 10;
  71342. } else {
  71343. continue;
  71344. }
  71345. header->channelAssignment = channelAssignment;
  71346. header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
  71347. if (header->bitsPerSample == 0) {
  71348. header->bitsPerSample = streaminfoBitsPerSample;
  71349. }
  71350. if (header->bitsPerSample != streaminfoBitsPerSample) {
  71351. return DRFLAC_FALSE;
  71352. }
  71353. if (!drflac__read_uint8(bs, 8, &header->crc8)) {
  71354. return DRFLAC_FALSE;
  71355. }
  71356. #ifndef DR_FLAC_NO_CRC
  71357. if (header->crc8 != crc8) {
  71358. continue;
  71359. }
  71360. #endif
  71361. return DRFLAC_TRUE;
  71362. }
  71363. }
  71364. static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe)
  71365. {
  71366. drflac_uint8 header;
  71367. int type;
  71368. if (!drflac__read_uint8(bs, 8, &header)) {
  71369. return DRFLAC_FALSE;
  71370. }
  71371. if ((header & 0x80) != 0) {
  71372. return DRFLAC_FALSE;
  71373. }
  71374. type = (header & 0x7E) >> 1;
  71375. if (type == 0) {
  71376. pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT;
  71377. } else if (type == 1) {
  71378. pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM;
  71379. } else {
  71380. if ((type & 0x20) != 0) {
  71381. pSubframe->subframeType = DRFLAC_SUBFRAME_LPC;
  71382. pSubframe->lpcOrder = (drflac_uint8)(type & 0x1F) + 1;
  71383. } else if ((type & 0x08) != 0) {
  71384. pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED;
  71385. pSubframe->lpcOrder = (drflac_uint8)(type & 0x07);
  71386. if (pSubframe->lpcOrder > 4) {
  71387. pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
  71388. pSubframe->lpcOrder = 0;
  71389. }
  71390. } else {
  71391. pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
  71392. }
  71393. }
  71394. if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED) {
  71395. return DRFLAC_FALSE;
  71396. }
  71397. pSubframe->wastedBitsPerSample = 0;
  71398. if ((header & 0x01) == 1) {
  71399. unsigned int wastedBitsPerSample;
  71400. if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) {
  71401. return DRFLAC_FALSE;
  71402. }
  71403. pSubframe->wastedBitsPerSample = (drflac_uint8)wastedBitsPerSample + 1;
  71404. }
  71405. return DRFLAC_TRUE;
  71406. }
  71407. static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut)
  71408. {
  71409. drflac_subframe* pSubframe;
  71410. drflac_uint32 subframeBitsPerSample;
  71411. DRFLAC_ASSERT(bs != NULL);
  71412. DRFLAC_ASSERT(frame != NULL);
  71413. pSubframe = frame->subframes + subframeIndex;
  71414. if (!drflac__read_subframe_header(bs, pSubframe)) {
  71415. return DRFLAC_FALSE;
  71416. }
  71417. subframeBitsPerSample = frame->header.bitsPerSample;
  71418. if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
  71419. subframeBitsPerSample += 1;
  71420. } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
  71421. subframeBitsPerSample += 1;
  71422. }
  71423. if (subframeBitsPerSample > 32) {
  71424. return DRFLAC_FALSE;
  71425. }
  71426. if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
  71427. return DRFLAC_FALSE;
  71428. }
  71429. subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
  71430. pSubframe->pSamplesS32 = pDecodedSamplesOut;
  71431. switch (pSubframe->subframeType)
  71432. {
  71433. case DRFLAC_SUBFRAME_CONSTANT:
  71434. {
  71435. drflac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
  71436. } break;
  71437. case DRFLAC_SUBFRAME_VERBATIM:
  71438. {
  71439. drflac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
  71440. } break;
  71441. case DRFLAC_SUBFRAME_FIXED:
  71442. {
  71443. drflac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
  71444. } break;
  71445. case DRFLAC_SUBFRAME_LPC:
  71446. {
  71447. drflac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
  71448. } break;
  71449. default: return DRFLAC_FALSE;
  71450. }
  71451. return DRFLAC_TRUE;
  71452. }
  71453. static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex)
  71454. {
  71455. drflac_subframe* pSubframe;
  71456. drflac_uint32 subframeBitsPerSample;
  71457. DRFLAC_ASSERT(bs != NULL);
  71458. DRFLAC_ASSERT(frame != NULL);
  71459. pSubframe = frame->subframes + subframeIndex;
  71460. if (!drflac__read_subframe_header(bs, pSubframe)) {
  71461. return DRFLAC_FALSE;
  71462. }
  71463. subframeBitsPerSample = frame->header.bitsPerSample;
  71464. if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
  71465. subframeBitsPerSample += 1;
  71466. } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
  71467. subframeBitsPerSample += 1;
  71468. }
  71469. if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
  71470. return DRFLAC_FALSE;
  71471. }
  71472. subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
  71473. pSubframe->pSamplesS32 = NULL;
  71474. switch (pSubframe->subframeType)
  71475. {
  71476. case DRFLAC_SUBFRAME_CONSTANT:
  71477. {
  71478. if (!drflac__seek_bits(bs, subframeBitsPerSample)) {
  71479. return DRFLAC_FALSE;
  71480. }
  71481. } break;
  71482. case DRFLAC_SUBFRAME_VERBATIM:
  71483. {
  71484. unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample;
  71485. if (!drflac__seek_bits(bs, bitsToSeek)) {
  71486. return DRFLAC_FALSE;
  71487. }
  71488. } break;
  71489. case DRFLAC_SUBFRAME_FIXED:
  71490. {
  71491. unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
  71492. if (!drflac__seek_bits(bs, bitsToSeek)) {
  71493. return DRFLAC_FALSE;
  71494. }
  71495. if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
  71496. return DRFLAC_FALSE;
  71497. }
  71498. } break;
  71499. case DRFLAC_SUBFRAME_LPC:
  71500. {
  71501. drflac_uint8 lpcPrecision;
  71502. unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
  71503. if (!drflac__seek_bits(bs, bitsToSeek)) {
  71504. return DRFLAC_FALSE;
  71505. }
  71506. if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
  71507. return DRFLAC_FALSE;
  71508. }
  71509. if (lpcPrecision == 15) {
  71510. return DRFLAC_FALSE;
  71511. }
  71512. lpcPrecision += 1;
  71513. bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5;
  71514. if (!drflac__seek_bits(bs, bitsToSeek)) {
  71515. return DRFLAC_FALSE;
  71516. }
  71517. if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
  71518. return DRFLAC_FALSE;
  71519. }
  71520. } break;
  71521. default: return DRFLAC_FALSE;
  71522. }
  71523. return DRFLAC_TRUE;
  71524. }
  71525. static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment)
  71526. {
  71527. drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
  71528. DRFLAC_ASSERT(channelAssignment <= 10);
  71529. return lookup[channelAssignment];
  71530. }
  71531. static drflac_result drflac__decode_flac_frame(drflac* pFlac)
  71532. {
  71533. int channelCount;
  71534. int i;
  71535. drflac_uint8 paddingSizeInBits;
  71536. drflac_uint16 desiredCRC16;
  71537. #ifndef DR_FLAC_NO_CRC
  71538. drflac_uint16 actualCRC16;
  71539. #endif
  71540. DRFLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes));
  71541. if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) {
  71542. return DRFLAC_ERROR;
  71543. }
  71544. channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  71545. if (channelCount != (int)pFlac->channels) {
  71546. return DRFLAC_ERROR;
  71547. }
  71548. for (i = 0; i < channelCount; ++i) {
  71549. if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) {
  71550. return DRFLAC_ERROR;
  71551. }
  71552. }
  71553. paddingSizeInBits = (drflac_uint8)(DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7);
  71554. if (paddingSizeInBits > 0) {
  71555. drflac_uint8 padding = 0;
  71556. if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) {
  71557. return DRFLAC_AT_END;
  71558. }
  71559. }
  71560. #ifndef DR_FLAC_NO_CRC
  71561. actualCRC16 = drflac__flush_crc16(&pFlac->bs);
  71562. #endif
  71563. if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
  71564. return DRFLAC_AT_END;
  71565. }
  71566. #ifndef DR_FLAC_NO_CRC
  71567. if (actualCRC16 != desiredCRC16) {
  71568. return DRFLAC_CRC_MISMATCH;
  71569. }
  71570. #endif
  71571. pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  71572. return DRFLAC_SUCCESS;
  71573. }
  71574. static drflac_result drflac__seek_flac_frame(drflac* pFlac)
  71575. {
  71576. int channelCount;
  71577. int i;
  71578. drflac_uint16 desiredCRC16;
  71579. #ifndef DR_FLAC_NO_CRC
  71580. drflac_uint16 actualCRC16;
  71581. #endif
  71582. channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  71583. for (i = 0; i < channelCount; ++i) {
  71584. if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) {
  71585. return DRFLAC_ERROR;
  71586. }
  71587. }
  71588. if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) {
  71589. return DRFLAC_ERROR;
  71590. }
  71591. #ifndef DR_FLAC_NO_CRC
  71592. actualCRC16 = drflac__flush_crc16(&pFlac->bs);
  71593. #endif
  71594. if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
  71595. return DRFLAC_AT_END;
  71596. }
  71597. #ifndef DR_FLAC_NO_CRC
  71598. if (actualCRC16 != desiredCRC16) {
  71599. return DRFLAC_CRC_MISMATCH;
  71600. }
  71601. #endif
  71602. return DRFLAC_SUCCESS;
  71603. }
  71604. static drflac_bool32 drflac__read_and_decode_next_flac_frame(drflac* pFlac)
  71605. {
  71606. DRFLAC_ASSERT(pFlac != NULL);
  71607. for (;;) {
  71608. drflac_result result;
  71609. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71610. return DRFLAC_FALSE;
  71611. }
  71612. result = drflac__decode_flac_frame(pFlac);
  71613. if (result != DRFLAC_SUCCESS) {
  71614. if (result == DRFLAC_CRC_MISMATCH) {
  71615. continue;
  71616. } else {
  71617. return DRFLAC_FALSE;
  71618. }
  71619. }
  71620. return DRFLAC_TRUE;
  71621. }
  71622. }
  71623. static void drflac__get_pcm_frame_range_of_current_flac_frame(drflac* pFlac, drflac_uint64* pFirstPCMFrame, drflac_uint64* pLastPCMFrame)
  71624. {
  71625. drflac_uint64 firstPCMFrame;
  71626. drflac_uint64 lastPCMFrame;
  71627. DRFLAC_ASSERT(pFlac != NULL);
  71628. firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber;
  71629. if (firstPCMFrame == 0) {
  71630. firstPCMFrame = ((drflac_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames;
  71631. }
  71632. lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  71633. if (lastPCMFrame > 0) {
  71634. lastPCMFrame -= 1;
  71635. }
  71636. if (pFirstPCMFrame) {
  71637. *pFirstPCMFrame = firstPCMFrame;
  71638. }
  71639. if (pLastPCMFrame) {
  71640. *pLastPCMFrame = lastPCMFrame;
  71641. }
  71642. }
  71643. static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac)
  71644. {
  71645. drflac_bool32 result;
  71646. DRFLAC_ASSERT(pFlac != NULL);
  71647. result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes);
  71648. DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
  71649. pFlac->currentPCMFrame = 0;
  71650. return result;
  71651. }
  71652. static DRFLAC_INLINE drflac_result drflac__seek_to_next_flac_frame(drflac* pFlac)
  71653. {
  71654. DRFLAC_ASSERT(pFlac != NULL);
  71655. return drflac__seek_flac_frame(pFlac);
  71656. }
  71657. static drflac_uint64 drflac__seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 pcmFramesToSeek)
  71658. {
  71659. drflac_uint64 pcmFramesRead = 0;
  71660. while (pcmFramesToSeek > 0) {
  71661. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  71662. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  71663. break;
  71664. }
  71665. } else {
  71666. if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) {
  71667. pcmFramesRead += pcmFramesToSeek;
  71668. pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)pcmFramesToSeek;
  71669. pcmFramesToSeek = 0;
  71670. } else {
  71671. pcmFramesRead += pFlac->currentFLACFrame.pcmFramesRemaining;
  71672. pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining;
  71673. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  71674. }
  71675. }
  71676. }
  71677. pFlac->currentPCMFrame += pcmFramesRead;
  71678. return pcmFramesRead;
  71679. }
  71680. static drflac_bool32 drflac__seek_to_pcm_frame__brute_force(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  71681. {
  71682. drflac_bool32 isMidFrame = DRFLAC_FALSE;
  71683. drflac_uint64 runningPCMFrameCount;
  71684. DRFLAC_ASSERT(pFlac != NULL);
  71685. if (pcmFrameIndex >= pFlac->currentPCMFrame) {
  71686. runningPCMFrameCount = pFlac->currentPCMFrame;
  71687. if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  71688. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71689. return DRFLAC_FALSE;
  71690. }
  71691. } else {
  71692. isMidFrame = DRFLAC_TRUE;
  71693. }
  71694. } else {
  71695. runningPCMFrameCount = 0;
  71696. if (!drflac__seek_to_first_frame(pFlac)) {
  71697. return DRFLAC_FALSE;
  71698. }
  71699. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71700. return DRFLAC_FALSE;
  71701. }
  71702. }
  71703. for (;;) {
  71704. drflac_uint64 pcmFrameCountInThisFLACFrame;
  71705. drflac_uint64 firstPCMFrameInFLACFrame = 0;
  71706. drflac_uint64 lastPCMFrameInFLACFrame = 0;
  71707. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  71708. pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  71709. if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
  71710. drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
  71711. if (!isMidFrame) {
  71712. drflac_result result = drflac__decode_flac_frame(pFlac);
  71713. if (result == DRFLAC_SUCCESS) {
  71714. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  71715. } else {
  71716. if (result == DRFLAC_CRC_MISMATCH) {
  71717. goto next_iteration;
  71718. } else {
  71719. return DRFLAC_FALSE;
  71720. }
  71721. }
  71722. } else {
  71723. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  71724. }
  71725. } else {
  71726. if (!isMidFrame) {
  71727. drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
  71728. if (result == DRFLAC_SUCCESS) {
  71729. runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
  71730. } else {
  71731. if (result == DRFLAC_CRC_MISMATCH) {
  71732. goto next_iteration;
  71733. } else {
  71734. return DRFLAC_FALSE;
  71735. }
  71736. }
  71737. } else {
  71738. runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
  71739. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  71740. isMidFrame = DRFLAC_FALSE;
  71741. }
  71742. if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
  71743. return DRFLAC_TRUE;
  71744. }
  71745. }
  71746. next_iteration:
  71747. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71748. return DRFLAC_FALSE;
  71749. }
  71750. }
  71751. }
  71752. #if !defined(DR_FLAC_NO_CRC)
  71753. #define DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f
  71754. static drflac_bool32 drflac__seek_to_approximate_flac_frame_to_byte(drflac* pFlac, drflac_uint64 targetByte, drflac_uint64 rangeLo, drflac_uint64 rangeHi, drflac_uint64* pLastSuccessfulSeekOffset)
  71755. {
  71756. DRFLAC_ASSERT(pFlac != NULL);
  71757. DRFLAC_ASSERT(pLastSuccessfulSeekOffset != NULL);
  71758. DRFLAC_ASSERT(targetByte >= rangeLo);
  71759. DRFLAC_ASSERT(targetByte <= rangeHi);
  71760. *pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes;
  71761. for (;;) {
  71762. drflac_uint64 lastTargetByte = targetByte;
  71763. if (!drflac__seek_to_byte(&pFlac->bs, targetByte)) {
  71764. if (targetByte == 0) {
  71765. drflac__seek_to_first_frame(pFlac);
  71766. return DRFLAC_FALSE;
  71767. }
  71768. targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  71769. rangeHi = targetByte;
  71770. } else {
  71771. DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
  71772. #if 1
  71773. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  71774. targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  71775. rangeHi = targetByte;
  71776. } else {
  71777. break;
  71778. }
  71779. #else
  71780. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71781. targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  71782. rangeHi = targetByte;
  71783. } else {
  71784. break;
  71785. }
  71786. #endif
  71787. }
  71788. if(targetByte == lastTargetByte) {
  71789. return DRFLAC_FALSE;
  71790. }
  71791. }
  71792. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
  71793. DRFLAC_ASSERT(targetByte <= rangeHi);
  71794. *pLastSuccessfulSeekOffset = targetByte;
  71795. return DRFLAC_TRUE;
  71796. }
  71797. static drflac_bool32 drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 offset)
  71798. {
  71799. #if 0
  71800. if (drflac__decode_flac_frame(pFlac) != DRFLAC_SUCCESS) {
  71801. if (drflac__read_and_decode_next_flac_frame(pFlac) == DRFLAC_FALSE) {
  71802. return DRFLAC_FALSE;
  71803. }
  71804. }
  71805. #endif
  71806. return drflac__seek_forward_by_pcm_frames(pFlac, offset) == offset;
  71807. }
  71808. static drflac_bool32 drflac__seek_to_pcm_frame__binary_search_internal(drflac* pFlac, drflac_uint64 pcmFrameIndex, drflac_uint64 byteRangeLo, drflac_uint64 byteRangeHi)
  71809. {
  71810. drflac_uint64 targetByte;
  71811. drflac_uint64 pcmRangeLo = pFlac->totalPCMFrameCount;
  71812. drflac_uint64 pcmRangeHi = 0;
  71813. drflac_uint64 lastSuccessfulSeekOffset = (drflac_uint64)-1;
  71814. drflac_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo;
  71815. drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
  71816. targetByte = byteRangeLo + (drflac_uint64)(((drflac_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO);
  71817. if (targetByte > byteRangeHi) {
  71818. targetByte = byteRangeHi;
  71819. }
  71820. for (;;) {
  71821. if (drflac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) {
  71822. drflac_uint64 newPCMRangeLo;
  71823. drflac_uint64 newPCMRangeHi;
  71824. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi);
  71825. if (pcmRangeLo == newPCMRangeLo) {
  71826. if (!drflac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) {
  71827. break;
  71828. }
  71829. if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
  71830. return DRFLAC_TRUE;
  71831. } else {
  71832. break;
  71833. }
  71834. }
  71835. pcmRangeLo = newPCMRangeLo;
  71836. pcmRangeHi = newPCMRangeHi;
  71837. if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) {
  71838. if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) {
  71839. return DRFLAC_TRUE;
  71840. } else {
  71841. break;
  71842. }
  71843. } else {
  71844. const float approxCompressionRatio = (drflac_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((drflac_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  71845. if (pcmRangeLo > pcmFrameIndex) {
  71846. byteRangeHi = lastSuccessfulSeekOffset;
  71847. if (byteRangeLo > byteRangeHi) {
  71848. byteRangeLo = byteRangeHi;
  71849. }
  71850. targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2);
  71851. if (targetByte < byteRangeLo) {
  71852. targetByte = byteRangeLo;
  71853. }
  71854. } else {
  71855. if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) {
  71856. if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
  71857. return DRFLAC_TRUE;
  71858. } else {
  71859. break;
  71860. }
  71861. } else {
  71862. byteRangeLo = lastSuccessfulSeekOffset;
  71863. if (byteRangeHi < byteRangeLo) {
  71864. byteRangeHi = byteRangeLo;
  71865. }
  71866. targetByte = lastSuccessfulSeekOffset + (drflac_uint64)(((drflac_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio);
  71867. if (targetByte > byteRangeHi) {
  71868. targetByte = byteRangeHi;
  71869. }
  71870. if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) {
  71871. closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset;
  71872. }
  71873. }
  71874. }
  71875. }
  71876. } else {
  71877. break;
  71878. }
  71879. }
  71880. drflac__seek_to_first_frame(pFlac);
  71881. return DRFLAC_FALSE;
  71882. }
  71883. static drflac_bool32 drflac__seek_to_pcm_frame__binary_search(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  71884. {
  71885. drflac_uint64 byteRangeLo;
  71886. drflac_uint64 byteRangeHi;
  71887. drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
  71888. if (drflac__seek_to_first_frame(pFlac) == DRFLAC_FALSE) {
  71889. return DRFLAC_FALSE;
  71890. }
  71891. if (pcmFrameIndex < seekForwardThreshold) {
  71892. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex;
  71893. }
  71894. byteRangeLo = pFlac->firstFLACFramePosInBytes;
  71895. byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  71896. return drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi);
  71897. }
  71898. #endif
  71899. static drflac_bool32 drflac__seek_to_pcm_frame__seek_table(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  71900. {
  71901. drflac_uint32 iClosestSeekpoint = 0;
  71902. drflac_bool32 isMidFrame = DRFLAC_FALSE;
  71903. drflac_uint64 runningPCMFrameCount;
  71904. drflac_uint32 iSeekpoint;
  71905. DRFLAC_ASSERT(pFlac != NULL);
  71906. if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) {
  71907. return DRFLAC_FALSE;
  71908. }
  71909. if (pFlac->pSeekpoints[0].firstPCMFrame > pcmFrameIndex) {
  71910. return DRFLAC_FALSE;
  71911. }
  71912. for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
  71913. if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) {
  71914. break;
  71915. }
  71916. iClosestSeekpoint = iSeekpoint;
  71917. }
  71918. if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) {
  71919. return DRFLAC_FALSE;
  71920. }
  71921. if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) {
  71922. return DRFLAC_FALSE;
  71923. }
  71924. #if !defined(DR_FLAC_NO_CRC)
  71925. if (pFlac->totalPCMFrameCount > 0) {
  71926. drflac_uint64 byteRangeLo;
  71927. drflac_uint64 byteRangeHi;
  71928. byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  71929. byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset;
  71930. if (iClosestSeekpoint < pFlac->seekpointCount-1) {
  71931. drflac_uint32 iNextSeekpoint = iClosestSeekpoint + 1;
  71932. if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) {
  71933. return DRFLAC_FALSE;
  71934. }
  71935. if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((drflac_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) {
  71936. byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1;
  71937. }
  71938. }
  71939. if (drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
  71940. if (drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71941. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
  71942. if (drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) {
  71943. return DRFLAC_TRUE;
  71944. }
  71945. }
  71946. }
  71947. }
  71948. #endif
  71949. if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) {
  71950. runningPCMFrameCount = pFlac->currentPCMFrame;
  71951. if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  71952. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71953. return DRFLAC_FALSE;
  71954. }
  71955. } else {
  71956. isMidFrame = DRFLAC_TRUE;
  71957. }
  71958. } else {
  71959. runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame;
  71960. if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
  71961. return DRFLAC_FALSE;
  71962. }
  71963. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71964. return DRFLAC_FALSE;
  71965. }
  71966. }
  71967. for (;;) {
  71968. drflac_uint64 pcmFrameCountInThisFLACFrame;
  71969. drflac_uint64 firstPCMFrameInFLACFrame = 0;
  71970. drflac_uint64 lastPCMFrameInFLACFrame = 0;
  71971. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  71972. pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  71973. if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
  71974. drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
  71975. if (!isMidFrame) {
  71976. drflac_result result = drflac__decode_flac_frame(pFlac);
  71977. if (result == DRFLAC_SUCCESS) {
  71978. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  71979. } else {
  71980. if (result == DRFLAC_CRC_MISMATCH) {
  71981. goto next_iteration;
  71982. } else {
  71983. return DRFLAC_FALSE;
  71984. }
  71985. }
  71986. } else {
  71987. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  71988. }
  71989. } else {
  71990. if (!isMidFrame) {
  71991. drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
  71992. if (result == DRFLAC_SUCCESS) {
  71993. runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
  71994. } else {
  71995. if (result == DRFLAC_CRC_MISMATCH) {
  71996. goto next_iteration;
  71997. } else {
  71998. return DRFLAC_FALSE;
  71999. }
  72000. }
  72001. } else {
  72002. runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
  72003. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  72004. isMidFrame = DRFLAC_FALSE;
  72005. }
  72006. if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
  72007. return DRFLAC_TRUE;
  72008. }
  72009. }
  72010. next_iteration:
  72011. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  72012. return DRFLAC_FALSE;
  72013. }
  72014. }
  72015. }
  72016. #ifndef DR_FLAC_NO_OGG
  72017. typedef struct
  72018. {
  72019. drflac_uint8 capturePattern[4];
  72020. drflac_uint8 structureVersion;
  72021. drflac_uint8 headerType;
  72022. drflac_uint64 granulePosition;
  72023. drflac_uint32 serialNumber;
  72024. drflac_uint32 sequenceNumber;
  72025. drflac_uint32 checksum;
  72026. drflac_uint8 segmentCount;
  72027. drflac_uint8 segmentTable[255];
  72028. } drflac_ogg_page_header;
  72029. #endif
  72030. typedef struct
  72031. {
  72032. drflac_read_proc onRead;
  72033. drflac_seek_proc onSeek;
  72034. drflac_meta_proc onMeta;
  72035. drflac_container container;
  72036. void* pUserData;
  72037. void* pUserDataMD;
  72038. drflac_uint32 sampleRate;
  72039. drflac_uint8 channels;
  72040. drflac_uint8 bitsPerSample;
  72041. drflac_uint64 totalPCMFrameCount;
  72042. drflac_uint16 maxBlockSizeInPCMFrames;
  72043. drflac_uint64 runningFilePos;
  72044. drflac_bool32 hasStreamInfoBlock;
  72045. drflac_bool32 hasMetadataBlocks;
  72046. drflac_bs bs;
  72047. drflac_frame_header firstFrameHeader;
  72048. #ifndef DR_FLAC_NO_OGG
  72049. drflac_uint32 oggSerial;
  72050. drflac_uint64 oggFirstBytePos;
  72051. drflac_ogg_page_header oggBosHeader;
  72052. #endif
  72053. } drflac_init_info;
  72054. static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
  72055. {
  72056. blockHeader = drflac__be2host_32(blockHeader);
  72057. *isLastBlock = (drflac_uint8)((blockHeader & 0x80000000UL) >> 31);
  72058. *blockType = (drflac_uint8)((blockHeader & 0x7F000000UL) >> 24);
  72059. *blockSize = (blockHeader & 0x00FFFFFFUL);
  72060. }
  72061. static DRFLAC_INLINE drflac_bool32 drflac__read_and_decode_block_header(drflac_read_proc onRead, void* pUserData, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
  72062. {
  72063. drflac_uint32 blockHeader;
  72064. *blockSize = 0;
  72065. if (onRead(pUserData, &blockHeader, 4) != 4) {
  72066. return DRFLAC_FALSE;
  72067. }
  72068. drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
  72069. return DRFLAC_TRUE;
  72070. }
  72071. static drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo)
  72072. {
  72073. drflac_uint32 blockSizes;
  72074. drflac_uint64 frameSizes = 0;
  72075. drflac_uint64 importantProps;
  72076. drflac_uint8 md5[16];
  72077. if (onRead(pUserData, &blockSizes, 4) != 4) {
  72078. return DRFLAC_FALSE;
  72079. }
  72080. if (onRead(pUserData, &frameSizes, 6) != 6) {
  72081. return DRFLAC_FALSE;
  72082. }
  72083. if (onRead(pUserData, &importantProps, 8) != 8) {
  72084. return DRFLAC_FALSE;
  72085. }
  72086. if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) {
  72087. return DRFLAC_FALSE;
  72088. }
  72089. blockSizes = drflac__be2host_32(blockSizes);
  72090. frameSizes = drflac__be2host_64(frameSizes);
  72091. importantProps = drflac__be2host_64(importantProps);
  72092. pStreamInfo->minBlockSizeInPCMFrames = (drflac_uint16)((blockSizes & 0xFFFF0000) >> 16);
  72093. pStreamInfo->maxBlockSizeInPCMFrames = (drflac_uint16) (blockSizes & 0x0000FFFF);
  72094. pStreamInfo->minFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 24)) >> 40);
  72095. pStreamInfo->maxFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 0)) >> 16);
  72096. pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (((drflac_uint64)0x000FFFFF << 16) << 28)) >> 44);
  72097. pStreamInfo->channels = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000000E << 16) << 24)) >> 41) + 1;
  72098. pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000001F << 16) << 20)) >> 36) + 1;
  72099. pStreamInfo->totalPCMFrameCount = ((importantProps & ((((drflac_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF)));
  72100. DRFLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5));
  72101. return DRFLAC_TRUE;
  72102. }
  72103. static void* drflac__malloc_default(size_t sz, void* pUserData)
  72104. {
  72105. (void)pUserData;
  72106. return DRFLAC_MALLOC(sz);
  72107. }
  72108. static void* drflac__realloc_default(void* p, size_t sz, void* pUserData)
  72109. {
  72110. (void)pUserData;
  72111. return DRFLAC_REALLOC(p, sz);
  72112. }
  72113. static void drflac__free_default(void* p, void* pUserData)
  72114. {
  72115. (void)pUserData;
  72116. DRFLAC_FREE(p);
  72117. }
  72118. static void* drflac__malloc_from_callbacks(size_t sz, const drflac_allocation_callbacks* pAllocationCallbacks)
  72119. {
  72120. if (pAllocationCallbacks == NULL) {
  72121. return NULL;
  72122. }
  72123. if (pAllocationCallbacks->onMalloc != NULL) {
  72124. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  72125. }
  72126. if (pAllocationCallbacks->onRealloc != NULL) {
  72127. return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  72128. }
  72129. return NULL;
  72130. }
  72131. static void* drflac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drflac_allocation_callbacks* pAllocationCallbacks)
  72132. {
  72133. if (pAllocationCallbacks == NULL) {
  72134. return NULL;
  72135. }
  72136. if (pAllocationCallbacks->onRealloc != NULL) {
  72137. return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  72138. }
  72139. if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  72140. void* p2;
  72141. p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  72142. if (p2 == NULL) {
  72143. return NULL;
  72144. }
  72145. if (p != NULL) {
  72146. DRFLAC_COPY_MEMORY(p2, p, szOld);
  72147. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  72148. }
  72149. return p2;
  72150. }
  72151. return NULL;
  72152. }
  72153. static void drflac__free_from_callbacks(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
  72154. {
  72155. if (p == NULL || pAllocationCallbacks == NULL) {
  72156. return;
  72157. }
  72158. if (pAllocationCallbacks->onFree != NULL) {
  72159. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  72160. }
  72161. }
  72162. static drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_uint64* pFirstFramePos, drflac_uint64* pSeektablePos, drflac_uint32* pSeekpointCount, drflac_allocation_callbacks* pAllocationCallbacks)
  72163. {
  72164. drflac_uint64 runningFilePos = 42;
  72165. drflac_uint64 seektablePos = 0;
  72166. drflac_uint32 seektableSize = 0;
  72167. for (;;) {
  72168. drflac_metadata metadata;
  72169. drflac_uint8 isLastBlock = 0;
  72170. drflac_uint8 blockType;
  72171. drflac_uint32 blockSize;
  72172. if (drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize) == DRFLAC_FALSE) {
  72173. return DRFLAC_FALSE;
  72174. }
  72175. runningFilePos += 4;
  72176. metadata.type = blockType;
  72177. metadata.pRawData = NULL;
  72178. metadata.rawDataSize = 0;
  72179. switch (blockType)
  72180. {
  72181. case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION:
  72182. {
  72183. if (blockSize < 4) {
  72184. return DRFLAC_FALSE;
  72185. }
  72186. if (onMeta) {
  72187. void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72188. if (pRawData == NULL) {
  72189. return DRFLAC_FALSE;
  72190. }
  72191. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72192. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72193. return DRFLAC_FALSE;
  72194. }
  72195. metadata.pRawData = pRawData;
  72196. metadata.rawDataSize = blockSize;
  72197. metadata.data.application.id = drflac__be2host_32(*(drflac_uint32*)pRawData);
  72198. metadata.data.application.pData = (const void*)((drflac_uint8*)pRawData + sizeof(drflac_uint32));
  72199. metadata.data.application.dataSize = blockSize - sizeof(drflac_uint32);
  72200. onMeta(pUserDataMD, &metadata);
  72201. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72202. }
  72203. } break;
  72204. case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
  72205. {
  72206. seektablePos = runningFilePos;
  72207. seektableSize = blockSize;
  72208. if (onMeta) {
  72209. drflac_uint32 seekpointCount;
  72210. drflac_uint32 iSeekpoint;
  72211. void* pRawData;
  72212. seekpointCount = blockSize/DRFLAC_SEEKPOINT_SIZE_IN_BYTES;
  72213. pRawData = drflac__malloc_from_callbacks(seekpointCount * sizeof(drflac_seekpoint), pAllocationCallbacks);
  72214. if (pRawData == NULL) {
  72215. return DRFLAC_FALSE;
  72216. }
  72217. for (iSeekpoint = 0; iSeekpoint < seekpointCount; ++iSeekpoint) {
  72218. drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint;
  72219. if (onRead(pUserData, pSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) != DRFLAC_SEEKPOINT_SIZE_IN_BYTES) {
  72220. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72221. return DRFLAC_FALSE;
  72222. }
  72223. pSeekpoint->firstPCMFrame = drflac__be2host_64(pSeekpoint->firstPCMFrame);
  72224. pSeekpoint->flacFrameOffset = drflac__be2host_64(pSeekpoint->flacFrameOffset);
  72225. pSeekpoint->pcmFrameCount = drflac__be2host_16(pSeekpoint->pcmFrameCount);
  72226. }
  72227. metadata.pRawData = pRawData;
  72228. metadata.rawDataSize = blockSize;
  72229. metadata.data.seektable.seekpointCount = seekpointCount;
  72230. metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData;
  72231. onMeta(pUserDataMD, &metadata);
  72232. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72233. }
  72234. } break;
  72235. case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
  72236. {
  72237. if (blockSize < 8) {
  72238. return DRFLAC_FALSE;
  72239. }
  72240. if (onMeta) {
  72241. void* pRawData;
  72242. const char* pRunningData;
  72243. const char* pRunningDataEnd;
  72244. drflac_uint32 i;
  72245. pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72246. if (pRawData == NULL) {
  72247. return DRFLAC_FALSE;
  72248. }
  72249. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72250. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72251. return DRFLAC_FALSE;
  72252. }
  72253. metadata.pRawData = pRawData;
  72254. metadata.rawDataSize = blockSize;
  72255. pRunningData = (const char*)pRawData;
  72256. pRunningDataEnd = (const char*)pRawData + blockSize;
  72257. metadata.data.vorbis_comment.vendorLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72258. if ((pRunningDataEnd - pRunningData) - 4 < (drflac_int64)metadata.data.vorbis_comment.vendorLength) {
  72259. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72260. return DRFLAC_FALSE;
  72261. }
  72262. metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength;
  72263. metadata.data.vorbis_comment.commentCount = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72264. if ((pRunningDataEnd - pRunningData) / sizeof(drflac_uint32) < metadata.data.vorbis_comment.commentCount) {
  72265. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72266. return DRFLAC_FALSE;
  72267. }
  72268. metadata.data.vorbis_comment.pComments = pRunningData;
  72269. for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) {
  72270. drflac_uint32 commentLength;
  72271. if (pRunningDataEnd - pRunningData < 4) {
  72272. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72273. return DRFLAC_FALSE;
  72274. }
  72275. commentLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72276. if (pRunningDataEnd - pRunningData < (drflac_int64)commentLength) {
  72277. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72278. return DRFLAC_FALSE;
  72279. }
  72280. pRunningData += commentLength;
  72281. }
  72282. onMeta(pUserDataMD, &metadata);
  72283. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72284. }
  72285. } break;
  72286. case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET:
  72287. {
  72288. if (blockSize < 396) {
  72289. return DRFLAC_FALSE;
  72290. }
  72291. if (onMeta) {
  72292. void* pRawData;
  72293. const char* pRunningData;
  72294. const char* pRunningDataEnd;
  72295. size_t bufferSize;
  72296. drflac_uint8 iTrack;
  72297. drflac_uint8 iIndex;
  72298. void* pTrackData;
  72299. pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72300. if (pRawData == NULL) {
  72301. return DRFLAC_FALSE;
  72302. }
  72303. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72304. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72305. return DRFLAC_FALSE;
  72306. }
  72307. metadata.pRawData = pRawData;
  72308. metadata.rawDataSize = blockSize;
  72309. pRunningData = (const char*)pRawData;
  72310. pRunningDataEnd = (const char*)pRawData + blockSize;
  72311. DRFLAC_COPY_MEMORY(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128;
  72312. metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(const drflac_uint64*)pRunningData); pRunningData += 8;
  72313. metadata.data.cuesheet.isCD = (pRunningData[0] & 0x80) != 0; pRunningData += 259;
  72314. metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1;
  72315. metadata.data.cuesheet.pTrackData = NULL;
  72316. {
  72317. const char* pRunningDataSaved = pRunningData;
  72318. bufferSize = metadata.data.cuesheet.trackCount * DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES;
  72319. for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
  72320. drflac_uint8 indexCount;
  72321. drflac_uint32 indexPointSize;
  72322. if (pRunningDataEnd - pRunningData < DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES) {
  72323. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72324. return DRFLAC_FALSE;
  72325. }
  72326. pRunningData += 35;
  72327. indexCount = pRunningData[0];
  72328. pRunningData += 1;
  72329. bufferSize += indexCount * sizeof(drflac_cuesheet_track_index);
  72330. indexPointSize = indexCount * DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
  72331. if (pRunningDataEnd - pRunningData < (drflac_int64)indexPointSize) {
  72332. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72333. return DRFLAC_FALSE;
  72334. }
  72335. pRunningData += indexPointSize;
  72336. }
  72337. pRunningData = pRunningDataSaved;
  72338. }
  72339. {
  72340. char* pRunningTrackData;
  72341. pTrackData = drflac__malloc_from_callbacks(bufferSize, pAllocationCallbacks);
  72342. if (pTrackData == NULL) {
  72343. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72344. return DRFLAC_FALSE;
  72345. }
  72346. pRunningTrackData = (char*)pTrackData;
  72347. for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
  72348. drflac_uint8 indexCount;
  72349. DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES);
  72350. pRunningData += DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1;
  72351. pRunningTrackData += DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1;
  72352. indexCount = pRunningData[0];
  72353. pRunningData += 1;
  72354. pRunningTrackData += 1;
  72355. for (iIndex = 0; iIndex < indexCount; ++iIndex) {
  72356. drflac_cuesheet_track_index* pTrackIndex = (drflac_cuesheet_track_index*)pRunningTrackData;
  72357. DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES);
  72358. pRunningData += DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
  72359. pRunningTrackData += sizeof(drflac_cuesheet_track_index);
  72360. pTrackIndex->offset = drflac__be2host_64(pTrackIndex->offset);
  72361. }
  72362. }
  72363. metadata.data.cuesheet.pTrackData = pTrackData;
  72364. }
  72365. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72366. pRawData = NULL;
  72367. onMeta(pUserDataMD, &metadata);
  72368. drflac__free_from_callbacks(pTrackData, pAllocationCallbacks);
  72369. pTrackData = NULL;
  72370. }
  72371. } break;
  72372. case DRFLAC_METADATA_BLOCK_TYPE_PICTURE:
  72373. {
  72374. if (blockSize < 32) {
  72375. return DRFLAC_FALSE;
  72376. }
  72377. if (onMeta) {
  72378. void* pRawData;
  72379. const char* pRunningData;
  72380. const char* pRunningDataEnd;
  72381. pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72382. if (pRawData == NULL) {
  72383. return DRFLAC_FALSE;
  72384. }
  72385. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72386. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72387. return DRFLAC_FALSE;
  72388. }
  72389. metadata.pRawData = pRawData;
  72390. metadata.rawDataSize = blockSize;
  72391. pRunningData = (const char*)pRawData;
  72392. pRunningDataEnd = (const char*)pRawData + blockSize;
  72393. metadata.data.picture.type = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72394. metadata.data.picture.mimeLength = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72395. if ((pRunningDataEnd - pRunningData) - 24 < (drflac_int64)metadata.data.picture.mimeLength) {
  72396. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72397. return DRFLAC_FALSE;
  72398. }
  72399. metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength;
  72400. metadata.data.picture.descriptionLength = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72401. if ((pRunningDataEnd - pRunningData) - 20 < (drflac_int64)metadata.data.picture.descriptionLength) {
  72402. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72403. return DRFLAC_FALSE;
  72404. }
  72405. metadata.data.picture.description = pRunningData; pRunningData += metadata.data.picture.descriptionLength;
  72406. metadata.data.picture.width = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72407. metadata.data.picture.height = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72408. metadata.data.picture.colorDepth = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72409. metadata.data.picture.indexColorCount = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72410. metadata.data.picture.pictureDataSize = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72411. metadata.data.picture.pPictureData = (const drflac_uint8*)pRunningData;
  72412. if (pRunningDataEnd - pRunningData < (drflac_int64)metadata.data.picture.pictureDataSize) {
  72413. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72414. return DRFLAC_FALSE;
  72415. }
  72416. onMeta(pUserDataMD, &metadata);
  72417. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72418. }
  72419. } break;
  72420. case DRFLAC_METADATA_BLOCK_TYPE_PADDING:
  72421. {
  72422. if (onMeta) {
  72423. metadata.data.padding.unused = 0;
  72424. if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
  72425. isLastBlock = DRFLAC_TRUE;
  72426. } else {
  72427. onMeta(pUserDataMD, &metadata);
  72428. }
  72429. }
  72430. } break;
  72431. case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
  72432. {
  72433. if (onMeta) {
  72434. if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
  72435. isLastBlock = DRFLAC_TRUE;
  72436. }
  72437. }
  72438. } break;
  72439. default:
  72440. {
  72441. if (onMeta) {
  72442. void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72443. if (pRawData == NULL) {
  72444. return DRFLAC_FALSE;
  72445. }
  72446. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72447. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72448. return DRFLAC_FALSE;
  72449. }
  72450. metadata.pRawData = pRawData;
  72451. metadata.rawDataSize = blockSize;
  72452. onMeta(pUserDataMD, &metadata);
  72453. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72454. }
  72455. } break;
  72456. }
  72457. if (onMeta == NULL && blockSize > 0) {
  72458. if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
  72459. isLastBlock = DRFLAC_TRUE;
  72460. }
  72461. }
  72462. runningFilePos += blockSize;
  72463. if (isLastBlock) {
  72464. break;
  72465. }
  72466. }
  72467. *pSeektablePos = seektablePos;
  72468. *pSeekpointCount = seektableSize / DRFLAC_SEEKPOINT_SIZE_IN_BYTES;
  72469. *pFirstFramePos = runningFilePos;
  72470. return DRFLAC_TRUE;
  72471. }
  72472. static drflac_bool32 drflac__init_private__native(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
  72473. {
  72474. drflac_uint8 isLastBlock;
  72475. drflac_uint8 blockType;
  72476. drflac_uint32 blockSize;
  72477. (void)onSeek;
  72478. pInit->container = drflac_container_native;
  72479. if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
  72480. return DRFLAC_FALSE;
  72481. }
  72482. if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
  72483. if (!relaxed) {
  72484. return DRFLAC_FALSE;
  72485. } else {
  72486. pInit->hasStreamInfoBlock = DRFLAC_FALSE;
  72487. pInit->hasMetadataBlocks = DRFLAC_FALSE;
  72488. if (!drflac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) {
  72489. return DRFLAC_FALSE;
  72490. }
  72491. if (pInit->firstFrameHeader.bitsPerSample == 0) {
  72492. return DRFLAC_FALSE;
  72493. }
  72494. pInit->sampleRate = pInit->firstFrameHeader.sampleRate;
  72495. pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
  72496. pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample;
  72497. pInit->maxBlockSizeInPCMFrames = 65535;
  72498. return DRFLAC_TRUE;
  72499. }
  72500. } else {
  72501. drflac_streaminfo streaminfo;
  72502. if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
  72503. return DRFLAC_FALSE;
  72504. }
  72505. pInit->hasStreamInfoBlock = DRFLAC_TRUE;
  72506. pInit->sampleRate = streaminfo.sampleRate;
  72507. pInit->channels = streaminfo.channels;
  72508. pInit->bitsPerSample = streaminfo.bitsPerSample;
  72509. pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
  72510. pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
  72511. pInit->hasMetadataBlocks = !isLastBlock;
  72512. if (onMeta) {
  72513. drflac_metadata metadata;
  72514. metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
  72515. metadata.pRawData = NULL;
  72516. metadata.rawDataSize = 0;
  72517. metadata.data.streaminfo = streaminfo;
  72518. onMeta(pUserDataMD, &metadata);
  72519. }
  72520. return DRFLAC_TRUE;
  72521. }
  72522. }
  72523. #ifndef DR_FLAC_NO_OGG
  72524. #define DRFLAC_OGG_MAX_PAGE_SIZE 65307
  72525. #define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199
  72526. typedef enum
  72527. {
  72528. drflac_ogg_recover_on_crc_mismatch,
  72529. drflac_ogg_fail_on_crc_mismatch
  72530. } drflac_ogg_crc_mismatch_recovery;
  72531. #ifndef DR_FLAC_NO_CRC
  72532. static drflac_uint32 drflac__crc32_table[] = {
  72533. 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
  72534. 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
  72535. 0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
  72536. 0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
  72537. 0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
  72538. 0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
  72539. 0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
  72540. 0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
  72541. 0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
  72542. 0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
  72543. 0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
  72544. 0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
  72545. 0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
  72546. 0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
  72547. 0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
  72548. 0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
  72549. 0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL,
  72550. 0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L,
  72551. 0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L,
  72552. 0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL,
  72553. 0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL,
  72554. 0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L,
  72555. 0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L,
  72556. 0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL,
  72557. 0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL,
  72558. 0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L,
  72559. 0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L,
  72560. 0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL,
  72561. 0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL,
  72562. 0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L,
  72563. 0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L,
  72564. 0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL,
  72565. 0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L,
  72566. 0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL,
  72567. 0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL,
  72568. 0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L,
  72569. 0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L,
  72570. 0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL,
  72571. 0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL,
  72572. 0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L,
  72573. 0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L,
  72574. 0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL,
  72575. 0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL,
  72576. 0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L,
  72577. 0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L,
  72578. 0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL,
  72579. 0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL,
  72580. 0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L,
  72581. 0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L,
  72582. 0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL,
  72583. 0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L,
  72584. 0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L,
  72585. 0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L,
  72586. 0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL,
  72587. 0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L,
  72588. 0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L,
  72589. 0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L,
  72590. 0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL,
  72591. 0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L,
  72592. 0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L,
  72593. 0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L,
  72594. 0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL,
  72595. 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L,
  72596. 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L
  72597. };
  72598. #endif
  72599. static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data)
  72600. {
  72601. #ifndef DR_FLAC_NO_CRC
  72602. return (crc32 << 8) ^ drflac__crc32_table[(drflac_uint8)((crc32 >> 24) & 0xFF) ^ data];
  72603. #else
  72604. (void)data;
  72605. return crc32;
  72606. #endif
  72607. }
  72608. #if 0
  72609. static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint32(drflac_uint32 crc32, drflac_uint32 data)
  72610. {
  72611. crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 24) & 0xFF));
  72612. crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 16) & 0xFF));
  72613. crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 8) & 0xFF));
  72614. crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 0) & 0xFF));
  72615. return crc32;
  72616. }
  72617. static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drflac_uint64 data)
  72618. {
  72619. crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 32) & 0xFFFFFFFF));
  72620. crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 0) & 0xFFFFFFFF));
  72621. return crc32;
  72622. }
  72623. #endif
  72624. static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize)
  72625. {
  72626. drflac_uint32 i;
  72627. for (i = 0; i < dataSize; ++i) {
  72628. crc32 = drflac_crc32_byte(crc32, pData[i]);
  72629. }
  72630. return crc32;
  72631. }
  72632. static DRFLAC_INLINE drflac_bool32 drflac_ogg__is_capture_pattern(drflac_uint8 pattern[4])
  72633. {
  72634. return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
  72635. }
  72636. static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_page_header* pHeader)
  72637. {
  72638. return 27 + pHeader->segmentCount;
  72639. }
  72640. static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader)
  72641. {
  72642. drflac_uint32 pageBodySize = 0;
  72643. int i;
  72644. for (i = 0; i < pHeader->segmentCount; ++i) {
  72645. pageBodySize += pHeader->segmentTable[i];
  72646. }
  72647. return pageBodySize;
  72648. }
  72649. static drflac_result drflac_ogg__read_page_header_after_capture_pattern(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32)
  72650. {
  72651. drflac_uint8 data[23];
  72652. drflac_uint32 i;
  72653. DRFLAC_ASSERT(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32);
  72654. if (onRead(pUserData, data, 23) != 23) {
  72655. return DRFLAC_AT_END;
  72656. }
  72657. *pBytesRead += 23;
  72658. pHeader->capturePattern[0] = 'O';
  72659. pHeader->capturePattern[1] = 'g';
  72660. pHeader->capturePattern[2] = 'g';
  72661. pHeader->capturePattern[3] = 'S';
  72662. pHeader->structureVersion = data[0];
  72663. pHeader->headerType = data[1];
  72664. DRFLAC_COPY_MEMORY(&pHeader->granulePosition, &data[ 2], 8);
  72665. DRFLAC_COPY_MEMORY(&pHeader->serialNumber, &data[10], 4);
  72666. DRFLAC_COPY_MEMORY(&pHeader->sequenceNumber, &data[14], 4);
  72667. DRFLAC_COPY_MEMORY(&pHeader->checksum, &data[18], 4);
  72668. pHeader->segmentCount = data[22];
  72669. data[18] = 0;
  72670. data[19] = 0;
  72671. data[20] = 0;
  72672. data[21] = 0;
  72673. for (i = 0; i < 23; ++i) {
  72674. *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]);
  72675. }
  72676. if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) {
  72677. return DRFLAC_AT_END;
  72678. }
  72679. *pBytesRead += pHeader->segmentCount;
  72680. for (i = 0; i < pHeader->segmentCount; ++i) {
  72681. *pCRC32 = drflac_crc32_byte(*pCRC32, pHeader->segmentTable[i]);
  72682. }
  72683. return DRFLAC_SUCCESS;
  72684. }
  72685. static drflac_result drflac_ogg__read_page_header(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32)
  72686. {
  72687. drflac_uint8 id[4];
  72688. *pBytesRead = 0;
  72689. if (onRead(pUserData, id, 4) != 4) {
  72690. return DRFLAC_AT_END;
  72691. }
  72692. *pBytesRead += 4;
  72693. for (;;) {
  72694. if (drflac_ogg__is_capture_pattern(id)) {
  72695. drflac_result result;
  72696. *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
  72697. result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32);
  72698. if (result == DRFLAC_SUCCESS) {
  72699. return DRFLAC_SUCCESS;
  72700. } else {
  72701. if (result == DRFLAC_CRC_MISMATCH) {
  72702. continue;
  72703. } else {
  72704. return result;
  72705. }
  72706. }
  72707. } else {
  72708. id[0] = id[1];
  72709. id[1] = id[2];
  72710. id[2] = id[3];
  72711. if (onRead(pUserData, &id[3], 1) != 1) {
  72712. return DRFLAC_AT_END;
  72713. }
  72714. *pBytesRead += 1;
  72715. }
  72716. }
  72717. }
  72718. typedef struct
  72719. {
  72720. drflac_read_proc onRead;
  72721. drflac_seek_proc onSeek;
  72722. void* pUserData;
  72723. drflac_uint64 currentBytePos;
  72724. drflac_uint64 firstBytePos;
  72725. drflac_uint32 serialNumber;
  72726. drflac_ogg_page_header bosPageHeader;
  72727. drflac_ogg_page_header currentPageHeader;
  72728. drflac_uint32 bytesRemainingInPage;
  72729. drflac_uint32 pageDataSize;
  72730. drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE];
  72731. } drflac_oggbs;
  72732. static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead)
  72733. {
  72734. size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead);
  72735. oggbs->currentBytePos += bytesActuallyRead;
  72736. return bytesActuallyRead;
  72737. }
  72738. static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uint64 offset, drflac_seek_origin origin)
  72739. {
  72740. if (origin == drflac_seek_origin_start) {
  72741. if (offset <= 0x7FFFFFFF) {
  72742. if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_start)) {
  72743. return DRFLAC_FALSE;
  72744. }
  72745. oggbs->currentBytePos = offset;
  72746. return DRFLAC_TRUE;
  72747. } else {
  72748. if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
  72749. return DRFLAC_FALSE;
  72750. }
  72751. oggbs->currentBytePos = offset;
  72752. return drflac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, drflac_seek_origin_current);
  72753. }
  72754. } else {
  72755. while (offset > 0x7FFFFFFF) {
  72756. if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
  72757. return DRFLAC_FALSE;
  72758. }
  72759. oggbs->currentBytePos += 0x7FFFFFFF;
  72760. offset -= 0x7FFFFFFF;
  72761. }
  72762. if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_current)) {
  72763. return DRFLAC_FALSE;
  72764. }
  72765. oggbs->currentBytePos += offset;
  72766. return DRFLAC_TRUE;
  72767. }
  72768. }
  72769. static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_ogg_crc_mismatch_recovery recoveryMethod)
  72770. {
  72771. drflac_ogg_page_header header;
  72772. for (;;) {
  72773. drflac_uint32 crc32 = 0;
  72774. drflac_uint32 bytesRead;
  72775. drflac_uint32 pageBodySize;
  72776. #ifndef DR_FLAC_NO_CRC
  72777. drflac_uint32 actualCRC32;
  72778. #endif
  72779. if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
  72780. return DRFLAC_FALSE;
  72781. }
  72782. oggbs->currentBytePos += bytesRead;
  72783. pageBodySize = drflac_ogg__get_page_body_size(&header);
  72784. if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE) {
  72785. continue;
  72786. }
  72787. if (header.serialNumber != oggbs->serialNumber) {
  72788. if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, drflac_seek_origin_current)) {
  72789. return DRFLAC_FALSE;
  72790. }
  72791. continue;
  72792. }
  72793. if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) {
  72794. return DRFLAC_FALSE;
  72795. }
  72796. oggbs->pageDataSize = pageBodySize;
  72797. #ifndef DR_FLAC_NO_CRC
  72798. actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize);
  72799. if (actualCRC32 != header.checksum) {
  72800. if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch) {
  72801. continue;
  72802. } else {
  72803. drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch);
  72804. return DRFLAC_FALSE;
  72805. }
  72806. }
  72807. #else
  72808. (void)recoveryMethod;
  72809. #endif
  72810. oggbs->currentPageHeader = header;
  72811. oggbs->bytesRemainingInPage = pageBodySize;
  72812. return DRFLAC_TRUE;
  72813. }
  72814. }
  72815. #if 0
  72816. static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg)
  72817. {
  72818. drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
  72819. drflac_uint8 iSeg = 0;
  72820. drflac_uint32 iByte = 0;
  72821. while (iByte < bytesConsumedInPage) {
  72822. drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
  72823. if (iByte + segmentSize > bytesConsumedInPage) {
  72824. break;
  72825. } else {
  72826. iSeg += 1;
  72827. iByte += segmentSize;
  72828. }
  72829. }
  72830. *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte);
  72831. return iSeg;
  72832. }
  72833. static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs)
  72834. {
  72835. for (;;) {
  72836. drflac_bool32 atEndOfPage = DRFLAC_FALSE;
  72837. drflac_uint8 bytesRemainingInSeg;
  72838. drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
  72839. drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
  72840. for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
  72841. drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
  72842. if (segmentSize < 255) {
  72843. if (iSeg == oggbs->currentPageHeader.segmentCount-1) {
  72844. atEndOfPage = DRFLAC_TRUE;
  72845. }
  72846. break;
  72847. }
  72848. bytesToEndOfPacketOrPage += segmentSize;
  72849. }
  72850. drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, drflac_seek_origin_current);
  72851. oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
  72852. if (atEndOfPage) {
  72853. if (!drflac_oggbs__goto_next_page(oggbs)) {
  72854. return DRFLAC_FALSE;
  72855. }
  72856. if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
  72857. return DRFLAC_TRUE;
  72858. }
  72859. } else {
  72860. return DRFLAC_TRUE;
  72861. }
  72862. }
  72863. }
  72864. static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs)
  72865. {
  72866. return drflac_oggbs__seek_to_next_packet(oggbs);
  72867. }
  72868. #endif
  72869. static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
  72870. {
  72871. drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
  72872. drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut;
  72873. size_t bytesRead = 0;
  72874. DRFLAC_ASSERT(oggbs != NULL);
  72875. DRFLAC_ASSERT(pRunningBufferOut != NULL);
  72876. while (bytesRead < bytesToRead) {
  72877. size_t bytesRemainingToRead = bytesToRead - bytesRead;
  72878. if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
  72879. DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
  72880. bytesRead += bytesRemainingToRead;
  72881. oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead;
  72882. break;
  72883. }
  72884. if (oggbs->bytesRemainingInPage > 0) {
  72885. DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
  72886. bytesRead += oggbs->bytesRemainingInPage;
  72887. pRunningBufferOut += oggbs->bytesRemainingInPage;
  72888. oggbs->bytesRemainingInPage = 0;
  72889. }
  72890. DRFLAC_ASSERT(bytesRemainingToRead > 0);
  72891. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
  72892. break;
  72893. }
  72894. }
  72895. return bytesRead;
  72896. }
  72897. static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin)
  72898. {
  72899. drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
  72900. int bytesSeeked = 0;
  72901. DRFLAC_ASSERT(oggbs != NULL);
  72902. DRFLAC_ASSERT(offset >= 0);
  72903. if (origin == drflac_seek_origin_start) {
  72904. if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, drflac_seek_origin_start)) {
  72905. return DRFLAC_FALSE;
  72906. }
  72907. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
  72908. return DRFLAC_FALSE;
  72909. }
  72910. return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current);
  72911. }
  72912. DRFLAC_ASSERT(origin == drflac_seek_origin_current);
  72913. while (bytesSeeked < offset) {
  72914. int bytesRemainingToSeek = offset - bytesSeeked;
  72915. DRFLAC_ASSERT(bytesRemainingToSeek >= 0);
  72916. if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) {
  72917. bytesSeeked += bytesRemainingToSeek;
  72918. (void)bytesSeeked;
  72919. oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
  72920. break;
  72921. }
  72922. if (oggbs->bytesRemainingInPage > 0) {
  72923. bytesSeeked += (int)oggbs->bytesRemainingInPage;
  72924. oggbs->bytesRemainingInPage = 0;
  72925. }
  72926. DRFLAC_ASSERT(bytesRemainingToSeek > 0);
  72927. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
  72928. return DRFLAC_FALSE;
  72929. }
  72930. }
  72931. return DRFLAC_TRUE;
  72932. }
  72933. static drflac_bool32 drflac_ogg__seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  72934. {
  72935. drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  72936. drflac_uint64 originalBytePos;
  72937. drflac_uint64 runningGranulePosition;
  72938. drflac_uint64 runningFrameBytePos;
  72939. drflac_uint64 runningPCMFrameCount;
  72940. DRFLAC_ASSERT(oggbs != NULL);
  72941. originalBytePos = oggbs->currentBytePos;
  72942. if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) {
  72943. return DRFLAC_FALSE;
  72944. }
  72945. oggbs->bytesRemainingInPage = 0;
  72946. runningGranulePosition = 0;
  72947. for (;;) {
  72948. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
  72949. drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
  72950. return DRFLAC_FALSE;
  72951. }
  72952. runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
  72953. if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) {
  72954. break;
  72955. }
  72956. if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
  72957. if (oggbs->currentPageHeader.segmentTable[0] >= 2) {
  72958. drflac_uint8 firstBytesInPage[2];
  72959. firstBytesInPage[0] = oggbs->pageData[0];
  72960. firstBytesInPage[1] = oggbs->pageData[1];
  72961. if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) {
  72962. runningGranulePosition = oggbs->currentPageHeader.granulePosition;
  72963. }
  72964. continue;
  72965. }
  72966. }
  72967. }
  72968. if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) {
  72969. return DRFLAC_FALSE;
  72970. }
  72971. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
  72972. return DRFLAC_FALSE;
  72973. }
  72974. runningPCMFrameCount = runningGranulePosition;
  72975. for (;;) {
  72976. drflac_uint64 firstPCMFrameInFLACFrame = 0;
  72977. drflac_uint64 lastPCMFrameInFLACFrame = 0;
  72978. drflac_uint64 pcmFrameCountInThisFrame;
  72979. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  72980. return DRFLAC_FALSE;
  72981. }
  72982. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  72983. pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  72984. if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) {
  72985. drflac_result result = drflac__decode_flac_frame(pFlac);
  72986. if (result == DRFLAC_SUCCESS) {
  72987. pFlac->currentPCMFrame = pcmFrameIndex;
  72988. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  72989. return DRFLAC_TRUE;
  72990. } else {
  72991. return DRFLAC_FALSE;
  72992. }
  72993. }
  72994. if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) {
  72995. drflac_result result = drflac__decode_flac_frame(pFlac);
  72996. if (result == DRFLAC_SUCCESS) {
  72997. drflac_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount);
  72998. if (pcmFramesToDecode == 0) {
  72999. return DRFLAC_TRUE;
  73000. }
  73001. pFlac->currentPCMFrame = runningPCMFrameCount;
  73002. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  73003. } else {
  73004. if (result == DRFLAC_CRC_MISMATCH) {
  73005. continue;
  73006. } else {
  73007. return DRFLAC_FALSE;
  73008. }
  73009. }
  73010. } else {
  73011. drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
  73012. if (result == DRFLAC_SUCCESS) {
  73013. runningPCMFrameCount += pcmFrameCountInThisFrame;
  73014. } else {
  73015. if (result == DRFLAC_CRC_MISMATCH) {
  73016. continue;
  73017. } else {
  73018. return DRFLAC_FALSE;
  73019. }
  73020. }
  73021. }
  73022. }
  73023. }
  73024. static drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
  73025. {
  73026. drflac_ogg_page_header header;
  73027. drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
  73028. drflac_uint32 bytesRead = 0;
  73029. (void)relaxed;
  73030. pInit->container = drflac_container_ogg;
  73031. pInit->oggFirstBytePos = 0;
  73032. if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
  73033. return DRFLAC_FALSE;
  73034. }
  73035. pInit->runningFilePos += bytesRead;
  73036. for (;;) {
  73037. int pageBodySize;
  73038. if ((header.headerType & 0x02) == 0) {
  73039. return DRFLAC_FALSE;
  73040. }
  73041. pageBodySize = drflac_ogg__get_page_body_size(&header);
  73042. if (pageBodySize == 51) {
  73043. drflac_uint32 bytesRemainingInPage = pageBodySize;
  73044. drflac_uint8 packetType;
  73045. if (onRead(pUserData, &packetType, 1) != 1) {
  73046. return DRFLAC_FALSE;
  73047. }
  73048. bytesRemainingInPage -= 1;
  73049. if (packetType == 0x7F) {
  73050. drflac_uint8 sig[4];
  73051. if (onRead(pUserData, sig, 4) != 4) {
  73052. return DRFLAC_FALSE;
  73053. }
  73054. bytesRemainingInPage -= 4;
  73055. if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
  73056. drflac_uint8 mappingVersion[2];
  73057. if (onRead(pUserData, mappingVersion, 2) != 2) {
  73058. return DRFLAC_FALSE;
  73059. }
  73060. if (mappingVersion[0] != 1) {
  73061. return DRFLAC_FALSE;
  73062. }
  73063. if (!onSeek(pUserData, 2, drflac_seek_origin_current)) {
  73064. return DRFLAC_FALSE;
  73065. }
  73066. if (onRead(pUserData, sig, 4) != 4) {
  73067. return DRFLAC_FALSE;
  73068. }
  73069. if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') {
  73070. drflac_streaminfo streaminfo;
  73071. drflac_uint8 isLastBlock;
  73072. drflac_uint8 blockType;
  73073. drflac_uint32 blockSize;
  73074. if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
  73075. return DRFLAC_FALSE;
  73076. }
  73077. if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
  73078. return DRFLAC_FALSE;
  73079. }
  73080. if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
  73081. pInit->hasStreamInfoBlock = DRFLAC_TRUE;
  73082. pInit->sampleRate = streaminfo.sampleRate;
  73083. pInit->channels = streaminfo.channels;
  73084. pInit->bitsPerSample = streaminfo.bitsPerSample;
  73085. pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
  73086. pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
  73087. pInit->hasMetadataBlocks = !isLastBlock;
  73088. if (onMeta) {
  73089. drflac_metadata metadata;
  73090. metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
  73091. metadata.pRawData = NULL;
  73092. metadata.rawDataSize = 0;
  73093. metadata.data.streaminfo = streaminfo;
  73094. onMeta(pUserDataMD, &metadata);
  73095. }
  73096. pInit->runningFilePos += pageBodySize;
  73097. pInit->oggFirstBytePos = pInit->runningFilePos - 79;
  73098. pInit->oggSerial = header.serialNumber;
  73099. pInit->oggBosHeader = header;
  73100. break;
  73101. } else {
  73102. return DRFLAC_FALSE;
  73103. }
  73104. } else {
  73105. return DRFLAC_FALSE;
  73106. }
  73107. } else {
  73108. if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
  73109. return DRFLAC_FALSE;
  73110. }
  73111. }
  73112. } else {
  73113. if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
  73114. return DRFLAC_FALSE;
  73115. }
  73116. }
  73117. } else {
  73118. if (!onSeek(pUserData, pageBodySize, drflac_seek_origin_current)) {
  73119. return DRFLAC_FALSE;
  73120. }
  73121. }
  73122. pInit->runningFilePos += pageBodySize;
  73123. if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
  73124. return DRFLAC_FALSE;
  73125. }
  73126. pInit->runningFilePos += bytesRead;
  73127. }
  73128. pInit->hasMetadataBlocks = DRFLAC_TRUE;
  73129. return DRFLAC_TRUE;
  73130. }
  73131. #endif
  73132. static drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD)
  73133. {
  73134. drflac_bool32 relaxed;
  73135. drflac_uint8 id[4];
  73136. if (pInit == NULL || onRead == NULL || onSeek == NULL) {
  73137. return DRFLAC_FALSE;
  73138. }
  73139. DRFLAC_ZERO_MEMORY(pInit, sizeof(*pInit));
  73140. pInit->onRead = onRead;
  73141. pInit->onSeek = onSeek;
  73142. pInit->onMeta = onMeta;
  73143. pInit->container = container;
  73144. pInit->pUserData = pUserData;
  73145. pInit->pUserDataMD = pUserDataMD;
  73146. pInit->bs.onRead = onRead;
  73147. pInit->bs.onSeek = onSeek;
  73148. pInit->bs.pUserData = pUserData;
  73149. drflac__reset_cache(&pInit->bs);
  73150. relaxed = container != drflac_container_unknown;
  73151. for (;;) {
  73152. if (onRead(pUserData, id, 4) != 4) {
  73153. return DRFLAC_FALSE;
  73154. }
  73155. pInit->runningFilePos += 4;
  73156. if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') {
  73157. drflac_uint8 header[6];
  73158. drflac_uint8 flags;
  73159. drflac_uint32 headerSize;
  73160. if (onRead(pUserData, header, 6) != 6) {
  73161. return DRFLAC_FALSE;
  73162. }
  73163. pInit->runningFilePos += 6;
  73164. flags = header[1];
  73165. DRFLAC_COPY_MEMORY(&headerSize, header+2, 4);
  73166. headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize));
  73167. if (flags & 0x10) {
  73168. headerSize += 10;
  73169. }
  73170. if (!onSeek(pUserData, headerSize, drflac_seek_origin_current)) {
  73171. return DRFLAC_FALSE;
  73172. }
  73173. pInit->runningFilePos += headerSize;
  73174. } else {
  73175. break;
  73176. }
  73177. }
  73178. if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') {
  73179. return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  73180. }
  73181. #ifndef DR_FLAC_NO_OGG
  73182. if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') {
  73183. return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  73184. }
  73185. #endif
  73186. if (relaxed) {
  73187. if (container == drflac_container_native) {
  73188. return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  73189. }
  73190. #ifndef DR_FLAC_NO_OGG
  73191. if (container == drflac_container_ogg) {
  73192. return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  73193. }
  73194. #endif
  73195. }
  73196. return DRFLAC_FALSE;
  73197. }
  73198. static void drflac__init_from_info(drflac* pFlac, const drflac_init_info* pInit)
  73199. {
  73200. DRFLAC_ASSERT(pFlac != NULL);
  73201. DRFLAC_ASSERT(pInit != NULL);
  73202. DRFLAC_ZERO_MEMORY(pFlac, sizeof(*pFlac));
  73203. pFlac->bs = pInit->bs;
  73204. pFlac->onMeta = pInit->onMeta;
  73205. pFlac->pUserDataMD = pInit->pUserDataMD;
  73206. pFlac->maxBlockSizeInPCMFrames = pInit->maxBlockSizeInPCMFrames;
  73207. pFlac->sampleRate = pInit->sampleRate;
  73208. pFlac->channels = (drflac_uint8)pInit->channels;
  73209. pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample;
  73210. pFlac->totalPCMFrameCount = pInit->totalPCMFrameCount;
  73211. pFlac->container = pInit->container;
  73212. }
  73213. static drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD, const drflac_allocation_callbacks* pAllocationCallbacks)
  73214. {
  73215. drflac_init_info init;
  73216. drflac_uint32 allocationSize;
  73217. drflac_uint32 wholeSIMDVectorCountPerChannel;
  73218. drflac_uint32 decodedSamplesAllocationSize;
  73219. #ifndef DR_FLAC_NO_OGG
  73220. drflac_oggbs* pOggbs = NULL;
  73221. #endif
  73222. drflac_uint64 firstFramePos;
  73223. drflac_uint64 seektablePos;
  73224. drflac_uint32 seekpointCount;
  73225. drflac_allocation_callbacks allocationCallbacks;
  73226. drflac* pFlac;
  73227. drflac__init_cpu_caps();
  73228. if (!drflac__init_private(&init, onRead, onSeek, onMeta, container, pUserData, pUserDataMD)) {
  73229. return NULL;
  73230. }
  73231. if (pAllocationCallbacks != NULL) {
  73232. allocationCallbacks = *pAllocationCallbacks;
  73233. if (allocationCallbacks.onFree == NULL || (allocationCallbacks.onMalloc == NULL && allocationCallbacks.onRealloc == NULL)) {
  73234. return NULL;
  73235. }
  73236. } else {
  73237. allocationCallbacks.pUserData = NULL;
  73238. allocationCallbacks.onMalloc = drflac__malloc_default;
  73239. allocationCallbacks.onRealloc = drflac__realloc_default;
  73240. allocationCallbacks.onFree = drflac__free_default;
  73241. }
  73242. allocationSize = sizeof(drflac);
  73243. if ((init.maxBlockSizeInPCMFrames % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) {
  73244. wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32)));
  73245. } else {
  73246. wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1;
  73247. }
  73248. decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels;
  73249. allocationSize += decodedSamplesAllocationSize;
  73250. allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE;
  73251. #ifndef DR_FLAC_NO_OGG
  73252. if (init.container == drflac_container_ogg) {
  73253. allocationSize += sizeof(drflac_oggbs);
  73254. pOggbs = (drflac_oggbs*)drflac__malloc_from_callbacks(sizeof(*pOggbs), &allocationCallbacks);
  73255. if (pOggbs == NULL) {
  73256. return NULL;
  73257. }
  73258. DRFLAC_ZERO_MEMORY(pOggbs, sizeof(*pOggbs));
  73259. pOggbs->onRead = onRead;
  73260. pOggbs->onSeek = onSeek;
  73261. pOggbs->pUserData = pUserData;
  73262. pOggbs->currentBytePos = init.oggFirstBytePos;
  73263. pOggbs->firstBytePos = init.oggFirstBytePos;
  73264. pOggbs->serialNumber = init.oggSerial;
  73265. pOggbs->bosPageHeader = init.oggBosHeader;
  73266. pOggbs->bytesRemainingInPage = 0;
  73267. }
  73268. #endif
  73269. firstFramePos = 42;
  73270. seektablePos = 0;
  73271. seekpointCount = 0;
  73272. if (init.hasMetadataBlocks) {
  73273. drflac_read_proc onReadOverride = onRead;
  73274. drflac_seek_proc onSeekOverride = onSeek;
  73275. void* pUserDataOverride = pUserData;
  73276. #ifndef DR_FLAC_NO_OGG
  73277. if (init.container == drflac_container_ogg) {
  73278. onReadOverride = drflac__on_read_ogg;
  73279. onSeekOverride = drflac__on_seek_ogg;
  73280. pUserDataOverride = (void*)pOggbs;
  73281. }
  73282. #endif
  73283. if (!drflac__read_and_decode_metadata(onReadOverride, onSeekOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seekpointCount, &allocationCallbacks)) {
  73284. #ifndef DR_FLAC_NO_OGG
  73285. drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
  73286. #endif
  73287. return NULL;
  73288. }
  73289. allocationSize += seekpointCount * sizeof(drflac_seekpoint);
  73290. }
  73291. pFlac = (drflac*)drflac__malloc_from_callbacks(allocationSize, &allocationCallbacks);
  73292. if (pFlac == NULL) {
  73293. #ifndef DR_FLAC_NO_OGG
  73294. drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
  73295. #endif
  73296. return NULL;
  73297. }
  73298. drflac__init_from_info(pFlac, &init);
  73299. pFlac->allocationCallbacks = allocationCallbacks;
  73300. pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE);
  73301. #ifndef DR_FLAC_NO_OGG
  73302. if (init.container == drflac_container_ogg) {
  73303. drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + (seekpointCount * sizeof(drflac_seekpoint)));
  73304. DRFLAC_COPY_MEMORY(pInternalOggbs, pOggbs, sizeof(*pOggbs));
  73305. drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
  73306. pOggbs = NULL;
  73307. pFlac->bs.onRead = drflac__on_read_ogg;
  73308. pFlac->bs.onSeek = drflac__on_seek_ogg;
  73309. pFlac->bs.pUserData = (void*)pInternalOggbs;
  73310. pFlac->_oggbs = (void*)pInternalOggbs;
  73311. }
  73312. #endif
  73313. pFlac->firstFLACFramePosInBytes = firstFramePos;
  73314. #ifndef DR_FLAC_NO_OGG
  73315. if (init.container == drflac_container_ogg)
  73316. {
  73317. pFlac->pSeekpoints = NULL;
  73318. pFlac->seekpointCount = 0;
  73319. }
  73320. else
  73321. #endif
  73322. {
  73323. if (seektablePos != 0) {
  73324. pFlac->seekpointCount = seekpointCount;
  73325. pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
  73326. DRFLAC_ASSERT(pFlac->bs.onSeek != NULL);
  73327. DRFLAC_ASSERT(pFlac->bs.onRead != NULL);
  73328. if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, drflac_seek_origin_start)) {
  73329. drflac_uint32 iSeekpoint;
  73330. for (iSeekpoint = 0; iSeekpoint < seekpointCount; iSeekpoint += 1) {
  73331. if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints + iSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) == DRFLAC_SEEKPOINT_SIZE_IN_BYTES) {
  73332. pFlac->pSeekpoints[iSeekpoint].firstPCMFrame = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame);
  73333. pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset);
  73334. pFlac->pSeekpoints[iSeekpoint].pcmFrameCount = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount);
  73335. } else {
  73336. pFlac->pSeekpoints = NULL;
  73337. pFlac->seekpointCount = 0;
  73338. break;
  73339. }
  73340. }
  73341. if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, drflac_seek_origin_start)) {
  73342. drflac__free_from_callbacks(pFlac, &allocationCallbacks);
  73343. return NULL;
  73344. }
  73345. } else {
  73346. pFlac->pSeekpoints = NULL;
  73347. pFlac->seekpointCount = 0;
  73348. }
  73349. }
  73350. }
  73351. if (!init.hasStreamInfoBlock) {
  73352. pFlac->currentFLACFrame.header = init.firstFrameHeader;
  73353. for (;;) {
  73354. drflac_result result = drflac__decode_flac_frame(pFlac);
  73355. if (result == DRFLAC_SUCCESS) {
  73356. break;
  73357. } else {
  73358. if (result == DRFLAC_CRC_MISMATCH) {
  73359. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  73360. drflac__free_from_callbacks(pFlac, &allocationCallbacks);
  73361. return NULL;
  73362. }
  73363. continue;
  73364. } else {
  73365. drflac__free_from_callbacks(pFlac, &allocationCallbacks);
  73366. return NULL;
  73367. }
  73368. }
  73369. }
  73370. }
  73371. return pFlac;
  73372. }
  73373. #ifndef DR_FLAC_NO_STDIO
  73374. #include <stdio.h>
  73375. #ifndef DR_FLAC_NO_WCHAR
  73376. #include <wchar.h>
  73377. #endif
  73378. #include <errno.h>
  73379. static drflac_result drflac_result_from_errno(int e)
  73380. {
  73381. switch (e)
  73382. {
  73383. case 0: return DRFLAC_SUCCESS;
  73384. #ifdef EPERM
  73385. case EPERM: return DRFLAC_INVALID_OPERATION;
  73386. #endif
  73387. #ifdef ENOENT
  73388. case ENOENT: return DRFLAC_DOES_NOT_EXIST;
  73389. #endif
  73390. #ifdef ESRCH
  73391. case ESRCH: return DRFLAC_DOES_NOT_EXIST;
  73392. #endif
  73393. #ifdef EINTR
  73394. case EINTR: return DRFLAC_INTERRUPT;
  73395. #endif
  73396. #ifdef EIO
  73397. case EIO: return DRFLAC_IO_ERROR;
  73398. #endif
  73399. #ifdef ENXIO
  73400. case ENXIO: return DRFLAC_DOES_NOT_EXIST;
  73401. #endif
  73402. #ifdef E2BIG
  73403. case E2BIG: return DRFLAC_INVALID_ARGS;
  73404. #endif
  73405. #ifdef ENOEXEC
  73406. case ENOEXEC: return DRFLAC_INVALID_FILE;
  73407. #endif
  73408. #ifdef EBADF
  73409. case EBADF: return DRFLAC_INVALID_FILE;
  73410. #endif
  73411. #ifdef ECHILD
  73412. case ECHILD: return DRFLAC_ERROR;
  73413. #endif
  73414. #ifdef EAGAIN
  73415. case EAGAIN: return DRFLAC_UNAVAILABLE;
  73416. #endif
  73417. #ifdef ENOMEM
  73418. case ENOMEM: return DRFLAC_OUT_OF_MEMORY;
  73419. #endif
  73420. #ifdef EACCES
  73421. case EACCES: return DRFLAC_ACCESS_DENIED;
  73422. #endif
  73423. #ifdef EFAULT
  73424. case EFAULT: return DRFLAC_BAD_ADDRESS;
  73425. #endif
  73426. #ifdef ENOTBLK
  73427. case ENOTBLK: return DRFLAC_ERROR;
  73428. #endif
  73429. #ifdef EBUSY
  73430. case EBUSY: return DRFLAC_BUSY;
  73431. #endif
  73432. #ifdef EEXIST
  73433. case EEXIST: return DRFLAC_ALREADY_EXISTS;
  73434. #endif
  73435. #ifdef EXDEV
  73436. case EXDEV: return DRFLAC_ERROR;
  73437. #endif
  73438. #ifdef ENODEV
  73439. case ENODEV: return DRFLAC_DOES_NOT_EXIST;
  73440. #endif
  73441. #ifdef ENOTDIR
  73442. case ENOTDIR: return DRFLAC_NOT_DIRECTORY;
  73443. #endif
  73444. #ifdef EISDIR
  73445. case EISDIR: return DRFLAC_IS_DIRECTORY;
  73446. #endif
  73447. #ifdef EINVAL
  73448. case EINVAL: return DRFLAC_INVALID_ARGS;
  73449. #endif
  73450. #ifdef ENFILE
  73451. case ENFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
  73452. #endif
  73453. #ifdef EMFILE
  73454. case EMFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
  73455. #endif
  73456. #ifdef ENOTTY
  73457. case ENOTTY: return DRFLAC_INVALID_OPERATION;
  73458. #endif
  73459. #ifdef ETXTBSY
  73460. case ETXTBSY: return DRFLAC_BUSY;
  73461. #endif
  73462. #ifdef EFBIG
  73463. case EFBIG: return DRFLAC_TOO_BIG;
  73464. #endif
  73465. #ifdef ENOSPC
  73466. case ENOSPC: return DRFLAC_NO_SPACE;
  73467. #endif
  73468. #ifdef ESPIPE
  73469. case ESPIPE: return DRFLAC_BAD_SEEK;
  73470. #endif
  73471. #ifdef EROFS
  73472. case EROFS: return DRFLAC_ACCESS_DENIED;
  73473. #endif
  73474. #ifdef EMLINK
  73475. case EMLINK: return DRFLAC_TOO_MANY_LINKS;
  73476. #endif
  73477. #ifdef EPIPE
  73478. case EPIPE: return DRFLAC_BAD_PIPE;
  73479. #endif
  73480. #ifdef EDOM
  73481. case EDOM: return DRFLAC_OUT_OF_RANGE;
  73482. #endif
  73483. #ifdef ERANGE
  73484. case ERANGE: return DRFLAC_OUT_OF_RANGE;
  73485. #endif
  73486. #ifdef EDEADLK
  73487. case EDEADLK: return DRFLAC_DEADLOCK;
  73488. #endif
  73489. #ifdef ENAMETOOLONG
  73490. case ENAMETOOLONG: return DRFLAC_PATH_TOO_LONG;
  73491. #endif
  73492. #ifdef ENOLCK
  73493. case ENOLCK: return DRFLAC_ERROR;
  73494. #endif
  73495. #ifdef ENOSYS
  73496. case ENOSYS: return DRFLAC_NOT_IMPLEMENTED;
  73497. #endif
  73498. #ifdef ENOTEMPTY
  73499. case ENOTEMPTY: return DRFLAC_DIRECTORY_NOT_EMPTY;
  73500. #endif
  73501. #ifdef ELOOP
  73502. case ELOOP: return DRFLAC_TOO_MANY_LINKS;
  73503. #endif
  73504. #ifdef ENOMSG
  73505. case ENOMSG: return DRFLAC_NO_MESSAGE;
  73506. #endif
  73507. #ifdef EIDRM
  73508. case EIDRM: return DRFLAC_ERROR;
  73509. #endif
  73510. #ifdef ECHRNG
  73511. case ECHRNG: return DRFLAC_ERROR;
  73512. #endif
  73513. #ifdef EL2NSYNC
  73514. case EL2NSYNC: return DRFLAC_ERROR;
  73515. #endif
  73516. #ifdef EL3HLT
  73517. case EL3HLT: return DRFLAC_ERROR;
  73518. #endif
  73519. #ifdef EL3RST
  73520. case EL3RST: return DRFLAC_ERROR;
  73521. #endif
  73522. #ifdef ELNRNG
  73523. case ELNRNG: return DRFLAC_OUT_OF_RANGE;
  73524. #endif
  73525. #ifdef EUNATCH
  73526. case EUNATCH: return DRFLAC_ERROR;
  73527. #endif
  73528. #ifdef ENOCSI
  73529. case ENOCSI: return DRFLAC_ERROR;
  73530. #endif
  73531. #ifdef EL2HLT
  73532. case EL2HLT: return DRFLAC_ERROR;
  73533. #endif
  73534. #ifdef EBADE
  73535. case EBADE: return DRFLAC_ERROR;
  73536. #endif
  73537. #ifdef EBADR
  73538. case EBADR: return DRFLAC_ERROR;
  73539. #endif
  73540. #ifdef EXFULL
  73541. case EXFULL: return DRFLAC_ERROR;
  73542. #endif
  73543. #ifdef ENOANO
  73544. case ENOANO: return DRFLAC_ERROR;
  73545. #endif
  73546. #ifdef EBADRQC
  73547. case EBADRQC: return DRFLAC_ERROR;
  73548. #endif
  73549. #ifdef EBADSLT
  73550. case EBADSLT: return DRFLAC_ERROR;
  73551. #endif
  73552. #ifdef EBFONT
  73553. case EBFONT: return DRFLAC_INVALID_FILE;
  73554. #endif
  73555. #ifdef ENOSTR
  73556. case ENOSTR: return DRFLAC_ERROR;
  73557. #endif
  73558. #ifdef ENODATA
  73559. case ENODATA: return DRFLAC_NO_DATA_AVAILABLE;
  73560. #endif
  73561. #ifdef ETIME
  73562. case ETIME: return DRFLAC_TIMEOUT;
  73563. #endif
  73564. #ifdef ENOSR
  73565. case ENOSR: return DRFLAC_NO_DATA_AVAILABLE;
  73566. #endif
  73567. #ifdef ENONET
  73568. case ENONET: return DRFLAC_NO_NETWORK;
  73569. #endif
  73570. #ifdef ENOPKG
  73571. case ENOPKG: return DRFLAC_ERROR;
  73572. #endif
  73573. #ifdef EREMOTE
  73574. case EREMOTE: return DRFLAC_ERROR;
  73575. #endif
  73576. #ifdef ENOLINK
  73577. case ENOLINK: return DRFLAC_ERROR;
  73578. #endif
  73579. #ifdef EADV
  73580. case EADV: return DRFLAC_ERROR;
  73581. #endif
  73582. #ifdef ESRMNT
  73583. case ESRMNT: return DRFLAC_ERROR;
  73584. #endif
  73585. #ifdef ECOMM
  73586. case ECOMM: return DRFLAC_ERROR;
  73587. #endif
  73588. #ifdef EPROTO
  73589. case EPROTO: return DRFLAC_ERROR;
  73590. #endif
  73591. #ifdef EMULTIHOP
  73592. case EMULTIHOP: return DRFLAC_ERROR;
  73593. #endif
  73594. #ifdef EDOTDOT
  73595. case EDOTDOT: return DRFLAC_ERROR;
  73596. #endif
  73597. #ifdef EBADMSG
  73598. case EBADMSG: return DRFLAC_BAD_MESSAGE;
  73599. #endif
  73600. #ifdef EOVERFLOW
  73601. case EOVERFLOW: return DRFLAC_TOO_BIG;
  73602. #endif
  73603. #ifdef ENOTUNIQ
  73604. case ENOTUNIQ: return DRFLAC_NOT_UNIQUE;
  73605. #endif
  73606. #ifdef EBADFD
  73607. case EBADFD: return DRFLAC_ERROR;
  73608. #endif
  73609. #ifdef EREMCHG
  73610. case EREMCHG: return DRFLAC_ERROR;
  73611. #endif
  73612. #ifdef ELIBACC
  73613. case ELIBACC: return DRFLAC_ACCESS_DENIED;
  73614. #endif
  73615. #ifdef ELIBBAD
  73616. case ELIBBAD: return DRFLAC_INVALID_FILE;
  73617. #endif
  73618. #ifdef ELIBSCN
  73619. case ELIBSCN: return DRFLAC_INVALID_FILE;
  73620. #endif
  73621. #ifdef ELIBMAX
  73622. case ELIBMAX: return DRFLAC_ERROR;
  73623. #endif
  73624. #ifdef ELIBEXEC
  73625. case ELIBEXEC: return DRFLAC_ERROR;
  73626. #endif
  73627. #ifdef EILSEQ
  73628. case EILSEQ: return DRFLAC_INVALID_DATA;
  73629. #endif
  73630. #ifdef ERESTART
  73631. case ERESTART: return DRFLAC_ERROR;
  73632. #endif
  73633. #ifdef ESTRPIPE
  73634. case ESTRPIPE: return DRFLAC_ERROR;
  73635. #endif
  73636. #ifdef EUSERS
  73637. case EUSERS: return DRFLAC_ERROR;
  73638. #endif
  73639. #ifdef ENOTSOCK
  73640. case ENOTSOCK: return DRFLAC_NOT_SOCKET;
  73641. #endif
  73642. #ifdef EDESTADDRREQ
  73643. case EDESTADDRREQ: return DRFLAC_NO_ADDRESS;
  73644. #endif
  73645. #ifdef EMSGSIZE
  73646. case EMSGSIZE: return DRFLAC_TOO_BIG;
  73647. #endif
  73648. #ifdef EPROTOTYPE
  73649. case EPROTOTYPE: return DRFLAC_BAD_PROTOCOL;
  73650. #endif
  73651. #ifdef ENOPROTOOPT
  73652. case ENOPROTOOPT: return DRFLAC_PROTOCOL_UNAVAILABLE;
  73653. #endif
  73654. #ifdef EPROTONOSUPPORT
  73655. case EPROTONOSUPPORT: return DRFLAC_PROTOCOL_NOT_SUPPORTED;
  73656. #endif
  73657. #ifdef ESOCKTNOSUPPORT
  73658. case ESOCKTNOSUPPORT: return DRFLAC_SOCKET_NOT_SUPPORTED;
  73659. #endif
  73660. #ifdef EOPNOTSUPP
  73661. case EOPNOTSUPP: return DRFLAC_INVALID_OPERATION;
  73662. #endif
  73663. #ifdef EPFNOSUPPORT
  73664. case EPFNOSUPPORT: return DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED;
  73665. #endif
  73666. #ifdef EAFNOSUPPORT
  73667. case EAFNOSUPPORT: return DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED;
  73668. #endif
  73669. #ifdef EADDRINUSE
  73670. case EADDRINUSE: return DRFLAC_ALREADY_IN_USE;
  73671. #endif
  73672. #ifdef EADDRNOTAVAIL
  73673. case EADDRNOTAVAIL: return DRFLAC_ERROR;
  73674. #endif
  73675. #ifdef ENETDOWN
  73676. case ENETDOWN: return DRFLAC_NO_NETWORK;
  73677. #endif
  73678. #ifdef ENETUNREACH
  73679. case ENETUNREACH: return DRFLAC_NO_NETWORK;
  73680. #endif
  73681. #ifdef ENETRESET
  73682. case ENETRESET: return DRFLAC_NO_NETWORK;
  73683. #endif
  73684. #ifdef ECONNABORTED
  73685. case ECONNABORTED: return DRFLAC_NO_NETWORK;
  73686. #endif
  73687. #ifdef ECONNRESET
  73688. case ECONNRESET: return DRFLAC_CONNECTION_RESET;
  73689. #endif
  73690. #ifdef ENOBUFS
  73691. case ENOBUFS: return DRFLAC_NO_SPACE;
  73692. #endif
  73693. #ifdef EISCONN
  73694. case EISCONN: return DRFLAC_ALREADY_CONNECTED;
  73695. #endif
  73696. #ifdef ENOTCONN
  73697. case ENOTCONN: return DRFLAC_NOT_CONNECTED;
  73698. #endif
  73699. #ifdef ESHUTDOWN
  73700. case ESHUTDOWN: return DRFLAC_ERROR;
  73701. #endif
  73702. #ifdef ETOOMANYREFS
  73703. case ETOOMANYREFS: return DRFLAC_ERROR;
  73704. #endif
  73705. #ifdef ETIMEDOUT
  73706. case ETIMEDOUT: return DRFLAC_TIMEOUT;
  73707. #endif
  73708. #ifdef ECONNREFUSED
  73709. case ECONNREFUSED: return DRFLAC_CONNECTION_REFUSED;
  73710. #endif
  73711. #ifdef EHOSTDOWN
  73712. case EHOSTDOWN: return DRFLAC_NO_HOST;
  73713. #endif
  73714. #ifdef EHOSTUNREACH
  73715. case EHOSTUNREACH: return DRFLAC_NO_HOST;
  73716. #endif
  73717. #ifdef EALREADY
  73718. case EALREADY: return DRFLAC_IN_PROGRESS;
  73719. #endif
  73720. #ifdef EINPROGRESS
  73721. case EINPROGRESS: return DRFLAC_IN_PROGRESS;
  73722. #endif
  73723. #ifdef ESTALE
  73724. case ESTALE: return DRFLAC_INVALID_FILE;
  73725. #endif
  73726. #ifdef EUCLEAN
  73727. case EUCLEAN: return DRFLAC_ERROR;
  73728. #endif
  73729. #ifdef ENOTNAM
  73730. case ENOTNAM: return DRFLAC_ERROR;
  73731. #endif
  73732. #ifdef ENAVAIL
  73733. case ENAVAIL: return DRFLAC_ERROR;
  73734. #endif
  73735. #ifdef EISNAM
  73736. case EISNAM: return DRFLAC_ERROR;
  73737. #endif
  73738. #ifdef EREMOTEIO
  73739. case EREMOTEIO: return DRFLAC_IO_ERROR;
  73740. #endif
  73741. #ifdef EDQUOT
  73742. case EDQUOT: return DRFLAC_NO_SPACE;
  73743. #endif
  73744. #ifdef ENOMEDIUM
  73745. case ENOMEDIUM: return DRFLAC_DOES_NOT_EXIST;
  73746. #endif
  73747. #ifdef EMEDIUMTYPE
  73748. case EMEDIUMTYPE: return DRFLAC_ERROR;
  73749. #endif
  73750. #ifdef ECANCELED
  73751. case ECANCELED: return DRFLAC_CANCELLED;
  73752. #endif
  73753. #ifdef ENOKEY
  73754. case ENOKEY: return DRFLAC_ERROR;
  73755. #endif
  73756. #ifdef EKEYEXPIRED
  73757. case EKEYEXPIRED: return DRFLAC_ERROR;
  73758. #endif
  73759. #ifdef EKEYREVOKED
  73760. case EKEYREVOKED: return DRFLAC_ERROR;
  73761. #endif
  73762. #ifdef EKEYREJECTED
  73763. case EKEYREJECTED: return DRFLAC_ERROR;
  73764. #endif
  73765. #ifdef EOWNERDEAD
  73766. case EOWNERDEAD: return DRFLAC_ERROR;
  73767. #endif
  73768. #ifdef ENOTRECOVERABLE
  73769. case ENOTRECOVERABLE: return DRFLAC_ERROR;
  73770. #endif
  73771. #ifdef ERFKILL
  73772. case ERFKILL: return DRFLAC_ERROR;
  73773. #endif
  73774. #ifdef EHWPOISON
  73775. case EHWPOISON: return DRFLAC_ERROR;
  73776. #endif
  73777. default: return DRFLAC_ERROR;
  73778. }
  73779. }
  73780. static drflac_result drflac_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  73781. {
  73782. #if defined(_MSC_VER) && _MSC_VER >= 1400
  73783. errno_t err;
  73784. #endif
  73785. if (ppFile != NULL) {
  73786. *ppFile = NULL;
  73787. }
  73788. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  73789. return DRFLAC_INVALID_ARGS;
  73790. }
  73791. #if defined(_MSC_VER) && _MSC_VER >= 1400
  73792. err = fopen_s(ppFile, pFilePath, pOpenMode);
  73793. if (err != 0) {
  73794. return drflac_result_from_errno(err);
  73795. }
  73796. #else
  73797. #if defined(_WIN32) || defined(__APPLE__)
  73798. *ppFile = fopen(pFilePath, pOpenMode);
  73799. #else
  73800. #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  73801. *ppFile = fopen64(pFilePath, pOpenMode);
  73802. #else
  73803. *ppFile = fopen(pFilePath, pOpenMode);
  73804. #endif
  73805. #endif
  73806. if (*ppFile == NULL) {
  73807. drflac_result result = drflac_result_from_errno(errno);
  73808. if (result == DRFLAC_SUCCESS) {
  73809. result = DRFLAC_ERROR;
  73810. }
  73811. return result;
  73812. }
  73813. #endif
  73814. return DRFLAC_SUCCESS;
  73815. }
  73816. #if defined(_WIN32)
  73817. #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
  73818. #define DRFLAC_HAS_WFOPEN
  73819. #endif
  73820. #endif
  73821. #ifndef DR_FLAC_NO_WCHAR
  73822. static drflac_result drflac_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drflac_allocation_callbacks* pAllocationCallbacks)
  73823. {
  73824. if (ppFile != NULL) {
  73825. *ppFile = NULL;
  73826. }
  73827. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  73828. return DRFLAC_INVALID_ARGS;
  73829. }
  73830. #if defined(DRFLAC_HAS_WFOPEN)
  73831. {
  73832. #if defined(_MSC_VER) && _MSC_VER >= 1400
  73833. errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  73834. if (err != 0) {
  73835. return drflac_result_from_errno(err);
  73836. }
  73837. #else
  73838. *ppFile = _wfopen(pFilePath, pOpenMode);
  73839. if (*ppFile == NULL) {
  73840. return drflac_result_from_errno(errno);
  73841. }
  73842. #endif
  73843. (void)pAllocationCallbacks;
  73844. }
  73845. #else
  73846. #if defined(__DJGPP__)
  73847. {
  73848. }
  73849. #else
  73850. {
  73851. mbstate_t mbs;
  73852. size_t lenMB;
  73853. const wchar_t* pFilePathTemp = pFilePath;
  73854. char* pFilePathMB = NULL;
  73855. char pOpenModeMB[32] = {0};
  73856. DRFLAC_ZERO_OBJECT(&mbs);
  73857. lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  73858. if (lenMB == (size_t)-1) {
  73859. return drflac_result_from_errno(errno);
  73860. }
  73861. pFilePathMB = (char*)drflac__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
  73862. if (pFilePathMB == NULL) {
  73863. return DRFLAC_OUT_OF_MEMORY;
  73864. }
  73865. pFilePathTemp = pFilePath;
  73866. DRFLAC_ZERO_OBJECT(&mbs);
  73867. wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  73868. {
  73869. size_t i = 0;
  73870. for (;;) {
  73871. if (pOpenMode[i] == 0) {
  73872. pOpenModeMB[i] = '\0';
  73873. break;
  73874. }
  73875. pOpenModeMB[i] = (char)pOpenMode[i];
  73876. i += 1;
  73877. }
  73878. }
  73879. *ppFile = fopen(pFilePathMB, pOpenModeMB);
  73880. drflac__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
  73881. }
  73882. #endif
  73883. if (*ppFile == NULL) {
  73884. return DRFLAC_ERROR;
  73885. }
  73886. #endif
  73887. return DRFLAC_SUCCESS;
  73888. }
  73889. #endif
  73890. static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
  73891. {
  73892. return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData);
  73893. }
  73894. static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin)
  73895. {
  73896. DRFLAC_ASSERT(offset >= 0);
  73897. return fseek((FILE*)pUserData, offset, (origin == drflac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  73898. }
  73899. DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
  73900. {
  73901. drflac* pFlac;
  73902. FILE* pFile;
  73903. if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
  73904. return NULL;
  73905. }
  73906. pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  73907. if (pFlac == NULL) {
  73908. fclose(pFile);
  73909. return NULL;
  73910. }
  73911. return pFlac;
  73912. }
  73913. #ifndef DR_FLAC_NO_WCHAR
  73914. DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
  73915. {
  73916. drflac* pFlac;
  73917. FILE* pFile;
  73918. if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
  73919. return NULL;
  73920. }
  73921. pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  73922. if (pFlac == NULL) {
  73923. fclose(pFile);
  73924. return NULL;
  73925. }
  73926. return pFlac;
  73927. }
  73928. #endif
  73929. DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  73930. {
  73931. drflac* pFlac;
  73932. FILE* pFile;
  73933. if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
  73934. return NULL;
  73935. }
  73936. pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
  73937. if (pFlac == NULL) {
  73938. fclose(pFile);
  73939. return pFlac;
  73940. }
  73941. return pFlac;
  73942. }
  73943. #ifndef DR_FLAC_NO_WCHAR
  73944. DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  73945. {
  73946. drflac* pFlac;
  73947. FILE* pFile;
  73948. if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
  73949. return NULL;
  73950. }
  73951. pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
  73952. if (pFlac == NULL) {
  73953. fclose(pFile);
  73954. return pFlac;
  73955. }
  73956. return pFlac;
  73957. }
  73958. #endif
  73959. #endif
  73960. static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead)
  73961. {
  73962. drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
  73963. size_t bytesRemaining;
  73964. DRFLAC_ASSERT(memoryStream != NULL);
  73965. DRFLAC_ASSERT(memoryStream->dataSize >= memoryStream->currentReadPos);
  73966. bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos;
  73967. if (bytesToRead > bytesRemaining) {
  73968. bytesToRead = bytesRemaining;
  73969. }
  73970. if (bytesToRead > 0) {
  73971. DRFLAC_COPY_MEMORY(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead);
  73972. memoryStream->currentReadPos += bytesToRead;
  73973. }
  73974. return bytesToRead;
  73975. }
  73976. static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin)
  73977. {
  73978. drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
  73979. DRFLAC_ASSERT(memoryStream != NULL);
  73980. DRFLAC_ASSERT(offset >= 0);
  73981. if (offset > (drflac_int64)memoryStream->dataSize) {
  73982. return DRFLAC_FALSE;
  73983. }
  73984. if (origin == drflac_seek_origin_current) {
  73985. if (memoryStream->currentReadPos + offset <= memoryStream->dataSize) {
  73986. memoryStream->currentReadPos += offset;
  73987. } else {
  73988. return DRFLAC_FALSE;
  73989. }
  73990. } else {
  73991. if ((drflac_uint32)offset <= memoryStream->dataSize) {
  73992. memoryStream->currentReadPos = offset;
  73993. } else {
  73994. return DRFLAC_FALSE;
  73995. }
  73996. }
  73997. return DRFLAC_TRUE;
  73998. }
  73999. DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks)
  74000. {
  74001. drflac__memory_stream memoryStream;
  74002. drflac* pFlac;
  74003. memoryStream.data = (const drflac_uint8*)pData;
  74004. memoryStream.dataSize = dataSize;
  74005. memoryStream.currentReadPos = 0;
  74006. pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, &memoryStream, pAllocationCallbacks);
  74007. if (pFlac == NULL) {
  74008. return NULL;
  74009. }
  74010. pFlac->memoryStream = memoryStream;
  74011. #ifndef DR_FLAC_NO_OGG
  74012. if (pFlac->container == drflac_container_ogg)
  74013. {
  74014. drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  74015. oggbs->pUserData = &pFlac->memoryStream;
  74016. }
  74017. else
  74018. #endif
  74019. {
  74020. pFlac->bs.pUserData = &pFlac->memoryStream;
  74021. }
  74022. return pFlac;
  74023. }
  74024. DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  74025. {
  74026. drflac__memory_stream memoryStream;
  74027. drflac* pFlac;
  74028. memoryStream.data = (const drflac_uint8*)pData;
  74029. memoryStream.dataSize = dataSize;
  74030. memoryStream.currentReadPos = 0;
  74031. pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData, pAllocationCallbacks);
  74032. if (pFlac == NULL) {
  74033. return NULL;
  74034. }
  74035. pFlac->memoryStream = memoryStream;
  74036. #ifndef DR_FLAC_NO_OGG
  74037. if (pFlac->container == drflac_container_ogg)
  74038. {
  74039. drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  74040. oggbs->pUserData = &pFlac->memoryStream;
  74041. }
  74042. else
  74043. #endif
  74044. {
  74045. pFlac->bs.pUserData = &pFlac->memoryStream;
  74046. }
  74047. return pFlac;
  74048. }
  74049. DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  74050. {
  74051. return drflac_open_with_metadata_private(onRead, onSeek, NULL, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
  74052. }
  74053. DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  74054. {
  74055. return drflac_open_with_metadata_private(onRead, onSeek, NULL, container, pUserData, pUserData, pAllocationCallbacks);
  74056. }
  74057. DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  74058. {
  74059. return drflac_open_with_metadata_private(onRead, onSeek, onMeta, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
  74060. }
  74061. DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  74062. {
  74063. return drflac_open_with_metadata_private(onRead, onSeek, onMeta, container, pUserData, pUserData, pAllocationCallbacks);
  74064. }
  74065. DRFLAC_API void drflac_close(drflac* pFlac)
  74066. {
  74067. if (pFlac == NULL) {
  74068. return;
  74069. }
  74070. #ifndef DR_FLAC_NO_STDIO
  74071. if (pFlac->bs.onRead == drflac__on_read_stdio) {
  74072. fclose((FILE*)pFlac->bs.pUserData);
  74073. }
  74074. #ifndef DR_FLAC_NO_OGG
  74075. if (pFlac->container == drflac_container_ogg) {
  74076. drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  74077. DRFLAC_ASSERT(pFlac->bs.onRead == drflac__on_read_ogg);
  74078. if (oggbs->onRead == drflac__on_read_stdio) {
  74079. fclose((FILE*)oggbs->pUserData);
  74080. }
  74081. }
  74082. #endif
  74083. #endif
  74084. drflac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks);
  74085. }
  74086. #if 0
  74087. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74088. {
  74089. drflac_uint64 i;
  74090. for (i = 0; i < frameCount; ++i) {
  74091. drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74092. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74093. drflac_uint32 right = left - side;
  74094. pOutputSamples[i*2+0] = (drflac_int32)left;
  74095. pOutputSamples[i*2+1] = (drflac_int32)right;
  74096. }
  74097. }
  74098. #endif
  74099. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74100. {
  74101. drflac_uint64 i;
  74102. drflac_uint64 frameCount4 = frameCount >> 2;
  74103. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74104. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74105. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74106. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74107. for (i = 0; i < frameCount4; ++i) {
  74108. drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  74109. drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  74110. drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  74111. drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  74112. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  74113. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  74114. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  74115. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  74116. drflac_uint32 right0 = left0 - side0;
  74117. drflac_uint32 right1 = left1 - side1;
  74118. drflac_uint32 right2 = left2 - side2;
  74119. drflac_uint32 right3 = left3 - side3;
  74120. pOutputSamples[i*8+0] = (drflac_int32)left0;
  74121. pOutputSamples[i*8+1] = (drflac_int32)right0;
  74122. pOutputSamples[i*8+2] = (drflac_int32)left1;
  74123. pOutputSamples[i*8+3] = (drflac_int32)right1;
  74124. pOutputSamples[i*8+4] = (drflac_int32)left2;
  74125. pOutputSamples[i*8+5] = (drflac_int32)right2;
  74126. pOutputSamples[i*8+6] = (drflac_int32)left3;
  74127. pOutputSamples[i*8+7] = (drflac_int32)right3;
  74128. }
  74129. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74130. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  74131. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  74132. drflac_uint32 right = left - side;
  74133. pOutputSamples[i*2+0] = (drflac_int32)left;
  74134. pOutputSamples[i*2+1] = (drflac_int32)right;
  74135. }
  74136. }
  74137. #if defined(DRFLAC_SUPPORT_SSE2)
  74138. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74139. {
  74140. drflac_uint64 i;
  74141. drflac_uint64 frameCount4 = frameCount >> 2;
  74142. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74143. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74144. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74145. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74146. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74147. for (i = 0; i < frameCount4; ++i) {
  74148. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74149. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74150. __m128i right = _mm_sub_epi32(left, side);
  74151. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  74152. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  74153. }
  74154. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74155. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  74156. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  74157. drflac_uint32 right = left - side;
  74158. pOutputSamples[i*2+0] = (drflac_int32)left;
  74159. pOutputSamples[i*2+1] = (drflac_int32)right;
  74160. }
  74161. }
  74162. #endif
  74163. #if defined(DRFLAC_SUPPORT_NEON)
  74164. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74165. {
  74166. drflac_uint64 i;
  74167. drflac_uint64 frameCount4 = frameCount >> 2;
  74168. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74169. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74170. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74171. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74172. int32x4_t shift0_4;
  74173. int32x4_t shift1_4;
  74174. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74175. shift0_4 = vdupq_n_s32(shift0);
  74176. shift1_4 = vdupq_n_s32(shift1);
  74177. for (i = 0; i < frameCount4; ++i) {
  74178. uint32x4_t left;
  74179. uint32x4_t side;
  74180. uint32x4_t right;
  74181. left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  74182. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  74183. right = vsubq_u32(left, side);
  74184. drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
  74185. }
  74186. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74187. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  74188. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  74189. drflac_uint32 right = left - side;
  74190. pOutputSamples[i*2+0] = (drflac_int32)left;
  74191. pOutputSamples[i*2+1] = (drflac_int32)right;
  74192. }
  74193. }
  74194. #endif
  74195. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74196. {
  74197. #if defined(DRFLAC_SUPPORT_SSE2)
  74198. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74199. drflac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74200. } else
  74201. #elif defined(DRFLAC_SUPPORT_NEON)
  74202. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74203. drflac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74204. } else
  74205. #endif
  74206. {
  74207. #if 0
  74208. drflac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74209. #else
  74210. drflac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74211. #endif
  74212. }
  74213. }
  74214. #if 0
  74215. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74216. {
  74217. drflac_uint64 i;
  74218. for (i = 0; i < frameCount; ++i) {
  74219. drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74220. drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74221. drflac_uint32 left = right + side;
  74222. pOutputSamples[i*2+0] = (drflac_int32)left;
  74223. pOutputSamples[i*2+1] = (drflac_int32)right;
  74224. }
  74225. }
  74226. #endif
  74227. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74228. {
  74229. drflac_uint64 i;
  74230. drflac_uint64 frameCount4 = frameCount >> 2;
  74231. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74232. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74233. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74234. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74235. for (i = 0; i < frameCount4; ++i) {
  74236. drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
  74237. drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
  74238. drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
  74239. drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
  74240. drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  74241. drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  74242. drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  74243. drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  74244. drflac_uint32 left0 = right0 + side0;
  74245. drflac_uint32 left1 = right1 + side1;
  74246. drflac_uint32 left2 = right2 + side2;
  74247. drflac_uint32 left3 = right3 + side3;
  74248. pOutputSamples[i*8+0] = (drflac_int32)left0;
  74249. pOutputSamples[i*8+1] = (drflac_int32)right0;
  74250. pOutputSamples[i*8+2] = (drflac_int32)left1;
  74251. pOutputSamples[i*8+3] = (drflac_int32)right1;
  74252. pOutputSamples[i*8+4] = (drflac_int32)left2;
  74253. pOutputSamples[i*8+5] = (drflac_int32)right2;
  74254. pOutputSamples[i*8+6] = (drflac_int32)left3;
  74255. pOutputSamples[i*8+7] = (drflac_int32)right3;
  74256. }
  74257. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74258. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  74259. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  74260. drflac_uint32 left = right + side;
  74261. pOutputSamples[i*2+0] = (drflac_int32)left;
  74262. pOutputSamples[i*2+1] = (drflac_int32)right;
  74263. }
  74264. }
  74265. #if defined(DRFLAC_SUPPORT_SSE2)
  74266. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74267. {
  74268. drflac_uint64 i;
  74269. drflac_uint64 frameCount4 = frameCount >> 2;
  74270. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74271. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74272. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74273. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74274. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74275. for (i = 0; i < frameCount4; ++i) {
  74276. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74277. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74278. __m128i left = _mm_add_epi32(right, side);
  74279. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  74280. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  74281. }
  74282. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74283. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  74284. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  74285. drflac_uint32 left = right + side;
  74286. pOutputSamples[i*2+0] = (drflac_int32)left;
  74287. pOutputSamples[i*2+1] = (drflac_int32)right;
  74288. }
  74289. }
  74290. #endif
  74291. #if defined(DRFLAC_SUPPORT_NEON)
  74292. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74293. {
  74294. drflac_uint64 i;
  74295. drflac_uint64 frameCount4 = frameCount >> 2;
  74296. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74297. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74298. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74299. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74300. int32x4_t shift0_4;
  74301. int32x4_t shift1_4;
  74302. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74303. shift0_4 = vdupq_n_s32(shift0);
  74304. shift1_4 = vdupq_n_s32(shift1);
  74305. for (i = 0; i < frameCount4; ++i) {
  74306. uint32x4_t side;
  74307. uint32x4_t right;
  74308. uint32x4_t left;
  74309. side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  74310. right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  74311. left = vaddq_u32(right, side);
  74312. drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
  74313. }
  74314. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74315. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  74316. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  74317. drflac_uint32 left = right + side;
  74318. pOutputSamples[i*2+0] = (drflac_int32)left;
  74319. pOutputSamples[i*2+1] = (drflac_int32)right;
  74320. }
  74321. }
  74322. #endif
  74323. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74324. {
  74325. #if defined(DRFLAC_SUPPORT_SSE2)
  74326. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74327. drflac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74328. } else
  74329. #elif defined(DRFLAC_SUPPORT_NEON)
  74330. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74331. drflac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74332. } else
  74333. #endif
  74334. {
  74335. #if 0
  74336. drflac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74337. #else
  74338. drflac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74339. #endif
  74340. }
  74341. }
  74342. #if 0
  74343. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74344. {
  74345. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  74346. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74347. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74348. mid = (mid << 1) | (side & 0x01);
  74349. pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
  74350. pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
  74351. }
  74352. }
  74353. #endif
  74354. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74355. {
  74356. drflac_uint64 i;
  74357. drflac_uint64 frameCount4 = frameCount >> 2;
  74358. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74359. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74360. drflac_int32 shift = unusedBitsPerSample;
  74361. if (shift > 0) {
  74362. shift -= 1;
  74363. for (i = 0; i < frameCount4; ++i) {
  74364. drflac_uint32 temp0L;
  74365. drflac_uint32 temp1L;
  74366. drflac_uint32 temp2L;
  74367. drflac_uint32 temp3L;
  74368. drflac_uint32 temp0R;
  74369. drflac_uint32 temp1R;
  74370. drflac_uint32 temp2R;
  74371. drflac_uint32 temp3R;
  74372. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74373. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74374. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74375. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74376. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74377. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74378. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74379. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74380. mid0 = (mid0 << 1) | (side0 & 0x01);
  74381. mid1 = (mid1 << 1) | (side1 & 0x01);
  74382. mid2 = (mid2 << 1) | (side2 & 0x01);
  74383. mid3 = (mid3 << 1) | (side3 & 0x01);
  74384. temp0L = (mid0 + side0) << shift;
  74385. temp1L = (mid1 + side1) << shift;
  74386. temp2L = (mid2 + side2) << shift;
  74387. temp3L = (mid3 + side3) << shift;
  74388. temp0R = (mid0 - side0) << shift;
  74389. temp1R = (mid1 - side1) << shift;
  74390. temp2R = (mid2 - side2) << shift;
  74391. temp3R = (mid3 - side3) << shift;
  74392. pOutputSamples[i*8+0] = (drflac_int32)temp0L;
  74393. pOutputSamples[i*8+1] = (drflac_int32)temp0R;
  74394. pOutputSamples[i*8+2] = (drflac_int32)temp1L;
  74395. pOutputSamples[i*8+3] = (drflac_int32)temp1R;
  74396. pOutputSamples[i*8+4] = (drflac_int32)temp2L;
  74397. pOutputSamples[i*8+5] = (drflac_int32)temp2R;
  74398. pOutputSamples[i*8+6] = (drflac_int32)temp3L;
  74399. pOutputSamples[i*8+7] = (drflac_int32)temp3R;
  74400. }
  74401. } else {
  74402. for (i = 0; i < frameCount4; ++i) {
  74403. drflac_uint32 temp0L;
  74404. drflac_uint32 temp1L;
  74405. drflac_uint32 temp2L;
  74406. drflac_uint32 temp3L;
  74407. drflac_uint32 temp0R;
  74408. drflac_uint32 temp1R;
  74409. drflac_uint32 temp2R;
  74410. drflac_uint32 temp3R;
  74411. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74412. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74413. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74414. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74415. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74416. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74417. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74418. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74419. mid0 = (mid0 << 1) | (side0 & 0x01);
  74420. mid1 = (mid1 << 1) | (side1 & 0x01);
  74421. mid2 = (mid2 << 1) | (side2 & 0x01);
  74422. mid3 = (mid3 << 1) | (side3 & 0x01);
  74423. temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
  74424. temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
  74425. temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
  74426. temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
  74427. temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
  74428. temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
  74429. temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
  74430. temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
  74431. pOutputSamples[i*8+0] = (drflac_int32)temp0L;
  74432. pOutputSamples[i*8+1] = (drflac_int32)temp0R;
  74433. pOutputSamples[i*8+2] = (drflac_int32)temp1L;
  74434. pOutputSamples[i*8+3] = (drflac_int32)temp1R;
  74435. pOutputSamples[i*8+4] = (drflac_int32)temp2L;
  74436. pOutputSamples[i*8+5] = (drflac_int32)temp2R;
  74437. pOutputSamples[i*8+6] = (drflac_int32)temp3L;
  74438. pOutputSamples[i*8+7] = (drflac_int32)temp3R;
  74439. }
  74440. }
  74441. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74442. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74443. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74444. mid = (mid << 1) | (side & 0x01);
  74445. pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
  74446. pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
  74447. }
  74448. }
  74449. #if defined(DRFLAC_SUPPORT_SSE2)
  74450. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74451. {
  74452. drflac_uint64 i;
  74453. drflac_uint64 frameCount4 = frameCount >> 2;
  74454. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74455. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74456. drflac_int32 shift = unusedBitsPerSample;
  74457. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74458. if (shift == 0) {
  74459. for (i = 0; i < frameCount4; ++i) {
  74460. __m128i mid;
  74461. __m128i side;
  74462. __m128i left;
  74463. __m128i right;
  74464. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74465. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74466. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  74467. left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  74468. right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  74469. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  74470. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  74471. }
  74472. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74473. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74474. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74475. mid = (mid << 1) | (side & 0x01);
  74476. pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
  74477. pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
  74478. }
  74479. } else {
  74480. shift -= 1;
  74481. for (i = 0; i < frameCount4; ++i) {
  74482. __m128i mid;
  74483. __m128i side;
  74484. __m128i left;
  74485. __m128i right;
  74486. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74487. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74488. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  74489. left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  74490. right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  74491. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  74492. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  74493. }
  74494. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74495. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74496. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74497. mid = (mid << 1) | (side & 0x01);
  74498. pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
  74499. pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
  74500. }
  74501. }
  74502. }
  74503. #endif
  74504. #if defined(DRFLAC_SUPPORT_NEON)
  74505. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74506. {
  74507. drflac_uint64 i;
  74508. drflac_uint64 frameCount4 = frameCount >> 2;
  74509. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74510. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74511. drflac_int32 shift = unusedBitsPerSample;
  74512. int32x4_t wbpsShift0_4;
  74513. int32x4_t wbpsShift1_4;
  74514. uint32x4_t one4;
  74515. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74516. wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74517. wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74518. one4 = vdupq_n_u32(1);
  74519. if (shift == 0) {
  74520. for (i = 0; i < frameCount4; ++i) {
  74521. uint32x4_t mid;
  74522. uint32x4_t side;
  74523. int32x4_t left;
  74524. int32x4_t right;
  74525. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  74526. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  74527. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
  74528. left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  74529. right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  74530. drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  74531. }
  74532. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74533. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74534. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74535. mid = (mid << 1) | (side & 0x01);
  74536. pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
  74537. pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
  74538. }
  74539. } else {
  74540. int32x4_t shift4;
  74541. shift -= 1;
  74542. shift4 = vdupq_n_s32(shift);
  74543. for (i = 0; i < frameCount4; ++i) {
  74544. uint32x4_t mid;
  74545. uint32x4_t side;
  74546. int32x4_t left;
  74547. int32x4_t right;
  74548. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  74549. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  74550. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
  74551. left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  74552. right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  74553. drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  74554. }
  74555. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74556. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74557. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74558. mid = (mid << 1) | (side & 0x01);
  74559. pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
  74560. pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
  74561. }
  74562. }
  74563. }
  74564. #endif
  74565. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74566. {
  74567. #if defined(DRFLAC_SUPPORT_SSE2)
  74568. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74569. drflac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74570. } else
  74571. #elif defined(DRFLAC_SUPPORT_NEON)
  74572. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74573. drflac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74574. } else
  74575. #endif
  74576. {
  74577. #if 0
  74578. drflac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74579. #else
  74580. drflac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74581. #endif
  74582. }
  74583. }
  74584. #if 0
  74585. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74586. {
  74587. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  74588. pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample));
  74589. pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample));
  74590. }
  74591. }
  74592. #endif
  74593. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74594. {
  74595. drflac_uint64 i;
  74596. drflac_uint64 frameCount4 = frameCount >> 2;
  74597. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74598. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74599. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74600. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74601. for (i = 0; i < frameCount4; ++i) {
  74602. drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  74603. drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  74604. drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  74605. drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  74606. drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  74607. drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  74608. drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  74609. drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  74610. pOutputSamples[i*8+0] = (drflac_int32)tempL0;
  74611. pOutputSamples[i*8+1] = (drflac_int32)tempR0;
  74612. pOutputSamples[i*8+2] = (drflac_int32)tempL1;
  74613. pOutputSamples[i*8+3] = (drflac_int32)tempR1;
  74614. pOutputSamples[i*8+4] = (drflac_int32)tempL2;
  74615. pOutputSamples[i*8+5] = (drflac_int32)tempR2;
  74616. pOutputSamples[i*8+6] = (drflac_int32)tempL3;
  74617. pOutputSamples[i*8+7] = (drflac_int32)tempR3;
  74618. }
  74619. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74620. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
  74621. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
  74622. }
  74623. }
  74624. #if defined(DRFLAC_SUPPORT_SSE2)
  74625. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74626. {
  74627. drflac_uint64 i;
  74628. drflac_uint64 frameCount4 = frameCount >> 2;
  74629. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74630. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74631. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74632. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74633. for (i = 0; i < frameCount4; ++i) {
  74634. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74635. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74636. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  74637. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  74638. }
  74639. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74640. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
  74641. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
  74642. }
  74643. }
  74644. #endif
  74645. #if defined(DRFLAC_SUPPORT_NEON)
  74646. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74647. {
  74648. drflac_uint64 i;
  74649. drflac_uint64 frameCount4 = frameCount >> 2;
  74650. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74651. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74652. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74653. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74654. int32x4_t shift4_0 = vdupq_n_s32(shift0);
  74655. int32x4_t shift4_1 = vdupq_n_s32(shift1);
  74656. for (i = 0; i < frameCount4; ++i) {
  74657. int32x4_t left;
  74658. int32x4_t right;
  74659. left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0));
  74660. right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1));
  74661. drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  74662. }
  74663. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74664. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
  74665. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
  74666. }
  74667. }
  74668. #endif
  74669. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  74670. {
  74671. #if defined(DRFLAC_SUPPORT_SSE2)
  74672. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74673. drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74674. } else
  74675. #elif defined(DRFLAC_SUPPORT_NEON)
  74676. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74677. drflac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74678. } else
  74679. #endif
  74680. {
  74681. #if 0
  74682. drflac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74683. #else
  74684. drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74685. #endif
  74686. }
  74687. }
  74688. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut)
  74689. {
  74690. drflac_uint64 framesRead;
  74691. drflac_uint32 unusedBitsPerSample;
  74692. if (pFlac == NULL || framesToRead == 0) {
  74693. return 0;
  74694. }
  74695. if (pBufferOut == NULL) {
  74696. return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  74697. }
  74698. DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
  74699. unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  74700. framesRead = 0;
  74701. while (framesToRead > 0) {
  74702. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  74703. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  74704. break;
  74705. }
  74706. } else {
  74707. unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  74708. drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  74709. drflac_uint64 frameCountThisIteration = framesToRead;
  74710. if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  74711. frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  74712. }
  74713. if (channelCount == 2) {
  74714. const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  74715. const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  74716. switch (pFlac->currentFLACFrame.header.channelAssignment)
  74717. {
  74718. case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  74719. {
  74720. drflac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74721. } break;
  74722. case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  74723. {
  74724. drflac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74725. } break;
  74726. case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  74727. {
  74728. drflac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74729. } break;
  74730. case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  74731. default:
  74732. {
  74733. drflac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74734. } break;
  74735. }
  74736. } else {
  74737. drflac_uint64 i;
  74738. for (i = 0; i < frameCountThisIteration; ++i) {
  74739. unsigned int j;
  74740. for (j = 0; j < channelCount; ++j) {
  74741. pBufferOut[(i*channelCount)+j] = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  74742. }
  74743. }
  74744. }
  74745. framesRead += frameCountThisIteration;
  74746. pBufferOut += frameCountThisIteration * channelCount;
  74747. framesToRead -= frameCountThisIteration;
  74748. pFlac->currentPCMFrame += frameCountThisIteration;
  74749. pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
  74750. }
  74751. }
  74752. return framesRead;
  74753. }
  74754. #if 0
  74755. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  74756. {
  74757. drflac_uint64 i;
  74758. for (i = 0; i < frameCount; ++i) {
  74759. drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74760. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74761. drflac_uint32 right = left - side;
  74762. left >>= 16;
  74763. right >>= 16;
  74764. pOutputSamples[i*2+0] = (drflac_int16)left;
  74765. pOutputSamples[i*2+1] = (drflac_int16)right;
  74766. }
  74767. }
  74768. #endif
  74769. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  74770. {
  74771. drflac_uint64 i;
  74772. drflac_uint64 frameCount4 = frameCount >> 2;
  74773. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74774. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74775. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74776. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74777. for (i = 0; i < frameCount4; ++i) {
  74778. drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  74779. drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  74780. drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  74781. drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  74782. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  74783. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  74784. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  74785. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  74786. drflac_uint32 right0 = left0 - side0;
  74787. drflac_uint32 right1 = left1 - side1;
  74788. drflac_uint32 right2 = left2 - side2;
  74789. drflac_uint32 right3 = left3 - side3;
  74790. left0 >>= 16;
  74791. left1 >>= 16;
  74792. left2 >>= 16;
  74793. left3 >>= 16;
  74794. right0 >>= 16;
  74795. right1 >>= 16;
  74796. right2 >>= 16;
  74797. right3 >>= 16;
  74798. pOutputSamples[i*8+0] = (drflac_int16)left0;
  74799. pOutputSamples[i*8+1] = (drflac_int16)right0;
  74800. pOutputSamples[i*8+2] = (drflac_int16)left1;
  74801. pOutputSamples[i*8+3] = (drflac_int16)right1;
  74802. pOutputSamples[i*8+4] = (drflac_int16)left2;
  74803. pOutputSamples[i*8+5] = (drflac_int16)right2;
  74804. pOutputSamples[i*8+6] = (drflac_int16)left3;
  74805. pOutputSamples[i*8+7] = (drflac_int16)right3;
  74806. }
  74807. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74808. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  74809. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  74810. drflac_uint32 right = left - side;
  74811. left >>= 16;
  74812. right >>= 16;
  74813. pOutputSamples[i*2+0] = (drflac_int16)left;
  74814. pOutputSamples[i*2+1] = (drflac_int16)right;
  74815. }
  74816. }
  74817. #if defined(DRFLAC_SUPPORT_SSE2)
  74818. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  74819. {
  74820. drflac_uint64 i;
  74821. drflac_uint64 frameCount4 = frameCount >> 2;
  74822. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74823. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74824. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74825. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74826. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74827. for (i = 0; i < frameCount4; ++i) {
  74828. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74829. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74830. __m128i right = _mm_sub_epi32(left, side);
  74831. left = _mm_srai_epi32(left, 16);
  74832. right = _mm_srai_epi32(right, 16);
  74833. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  74834. }
  74835. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74836. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  74837. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  74838. drflac_uint32 right = left - side;
  74839. left >>= 16;
  74840. right >>= 16;
  74841. pOutputSamples[i*2+0] = (drflac_int16)left;
  74842. pOutputSamples[i*2+1] = (drflac_int16)right;
  74843. }
  74844. }
  74845. #endif
  74846. #if defined(DRFLAC_SUPPORT_NEON)
  74847. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  74848. {
  74849. drflac_uint64 i;
  74850. drflac_uint64 frameCount4 = frameCount >> 2;
  74851. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74852. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74853. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74854. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74855. int32x4_t shift0_4;
  74856. int32x4_t shift1_4;
  74857. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74858. shift0_4 = vdupq_n_s32(shift0);
  74859. shift1_4 = vdupq_n_s32(shift1);
  74860. for (i = 0; i < frameCount4; ++i) {
  74861. uint32x4_t left;
  74862. uint32x4_t side;
  74863. uint32x4_t right;
  74864. left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  74865. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  74866. right = vsubq_u32(left, side);
  74867. left = vshrq_n_u32(left, 16);
  74868. right = vshrq_n_u32(right, 16);
  74869. drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
  74870. }
  74871. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74872. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  74873. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  74874. drflac_uint32 right = left - side;
  74875. left >>= 16;
  74876. right >>= 16;
  74877. pOutputSamples[i*2+0] = (drflac_int16)left;
  74878. pOutputSamples[i*2+1] = (drflac_int16)right;
  74879. }
  74880. }
  74881. #endif
  74882. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  74883. {
  74884. #if defined(DRFLAC_SUPPORT_SSE2)
  74885. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74886. drflac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74887. } else
  74888. #elif defined(DRFLAC_SUPPORT_NEON)
  74889. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74890. drflac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74891. } else
  74892. #endif
  74893. {
  74894. #if 0
  74895. drflac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74896. #else
  74897. drflac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74898. #endif
  74899. }
  74900. }
  74901. #if 0
  74902. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  74903. {
  74904. drflac_uint64 i;
  74905. for (i = 0; i < frameCount; ++i) {
  74906. drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74907. drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74908. drflac_uint32 left = right + side;
  74909. left >>= 16;
  74910. right >>= 16;
  74911. pOutputSamples[i*2+0] = (drflac_int16)left;
  74912. pOutputSamples[i*2+1] = (drflac_int16)right;
  74913. }
  74914. }
  74915. #endif
  74916. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  74917. {
  74918. drflac_uint64 i;
  74919. drflac_uint64 frameCount4 = frameCount >> 2;
  74920. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74921. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74922. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74923. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74924. for (i = 0; i < frameCount4; ++i) {
  74925. drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
  74926. drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
  74927. drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
  74928. drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
  74929. drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  74930. drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  74931. drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  74932. drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  74933. drflac_uint32 left0 = right0 + side0;
  74934. drflac_uint32 left1 = right1 + side1;
  74935. drflac_uint32 left2 = right2 + side2;
  74936. drflac_uint32 left3 = right3 + side3;
  74937. left0 >>= 16;
  74938. left1 >>= 16;
  74939. left2 >>= 16;
  74940. left3 >>= 16;
  74941. right0 >>= 16;
  74942. right1 >>= 16;
  74943. right2 >>= 16;
  74944. right3 >>= 16;
  74945. pOutputSamples[i*8+0] = (drflac_int16)left0;
  74946. pOutputSamples[i*8+1] = (drflac_int16)right0;
  74947. pOutputSamples[i*8+2] = (drflac_int16)left1;
  74948. pOutputSamples[i*8+3] = (drflac_int16)right1;
  74949. pOutputSamples[i*8+4] = (drflac_int16)left2;
  74950. pOutputSamples[i*8+5] = (drflac_int16)right2;
  74951. pOutputSamples[i*8+6] = (drflac_int16)left3;
  74952. pOutputSamples[i*8+7] = (drflac_int16)right3;
  74953. }
  74954. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74955. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  74956. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  74957. drflac_uint32 left = right + side;
  74958. left >>= 16;
  74959. right >>= 16;
  74960. pOutputSamples[i*2+0] = (drflac_int16)left;
  74961. pOutputSamples[i*2+1] = (drflac_int16)right;
  74962. }
  74963. }
  74964. #if defined(DRFLAC_SUPPORT_SSE2)
  74965. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  74966. {
  74967. drflac_uint64 i;
  74968. drflac_uint64 frameCount4 = frameCount >> 2;
  74969. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74970. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74971. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74972. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74973. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74974. for (i = 0; i < frameCount4; ++i) {
  74975. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74976. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74977. __m128i left = _mm_add_epi32(right, side);
  74978. left = _mm_srai_epi32(left, 16);
  74979. right = _mm_srai_epi32(right, 16);
  74980. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  74981. }
  74982. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74983. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  74984. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  74985. drflac_uint32 left = right + side;
  74986. left >>= 16;
  74987. right >>= 16;
  74988. pOutputSamples[i*2+0] = (drflac_int16)left;
  74989. pOutputSamples[i*2+1] = (drflac_int16)right;
  74990. }
  74991. }
  74992. #endif
  74993. #if defined(DRFLAC_SUPPORT_NEON)
  74994. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  74995. {
  74996. drflac_uint64 i;
  74997. drflac_uint64 frameCount4 = frameCount >> 2;
  74998. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74999. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75000. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75001. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75002. int32x4_t shift0_4;
  75003. int32x4_t shift1_4;
  75004. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75005. shift0_4 = vdupq_n_s32(shift0);
  75006. shift1_4 = vdupq_n_s32(shift1);
  75007. for (i = 0; i < frameCount4; ++i) {
  75008. uint32x4_t side;
  75009. uint32x4_t right;
  75010. uint32x4_t left;
  75011. side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  75012. right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  75013. left = vaddq_u32(right, side);
  75014. left = vshrq_n_u32(left, 16);
  75015. right = vshrq_n_u32(right, 16);
  75016. drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
  75017. }
  75018. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75019. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  75020. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  75021. drflac_uint32 left = right + side;
  75022. left >>= 16;
  75023. right >>= 16;
  75024. pOutputSamples[i*2+0] = (drflac_int16)left;
  75025. pOutputSamples[i*2+1] = (drflac_int16)right;
  75026. }
  75027. }
  75028. #endif
  75029. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75030. {
  75031. #if defined(DRFLAC_SUPPORT_SSE2)
  75032. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  75033. drflac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75034. } else
  75035. #elif defined(DRFLAC_SUPPORT_NEON)
  75036. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  75037. drflac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75038. } else
  75039. #endif
  75040. {
  75041. #if 0
  75042. drflac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75043. #else
  75044. drflac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75045. #endif
  75046. }
  75047. }
  75048. #if 0
  75049. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75050. {
  75051. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  75052. drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75053. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75054. mid = (mid << 1) | (side & 0x01);
  75055. pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
  75056. pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
  75057. }
  75058. }
  75059. #endif
  75060. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75061. {
  75062. drflac_uint64 i;
  75063. drflac_uint64 frameCount4 = frameCount >> 2;
  75064. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75065. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75066. drflac_uint32 shift = unusedBitsPerSample;
  75067. if (shift > 0) {
  75068. shift -= 1;
  75069. for (i = 0; i < frameCount4; ++i) {
  75070. drflac_uint32 temp0L;
  75071. drflac_uint32 temp1L;
  75072. drflac_uint32 temp2L;
  75073. drflac_uint32 temp3L;
  75074. drflac_uint32 temp0R;
  75075. drflac_uint32 temp1R;
  75076. drflac_uint32 temp2R;
  75077. drflac_uint32 temp3R;
  75078. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75079. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75080. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75081. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75082. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75083. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75084. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75085. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75086. mid0 = (mid0 << 1) | (side0 & 0x01);
  75087. mid1 = (mid1 << 1) | (side1 & 0x01);
  75088. mid2 = (mid2 << 1) | (side2 & 0x01);
  75089. mid3 = (mid3 << 1) | (side3 & 0x01);
  75090. temp0L = (mid0 + side0) << shift;
  75091. temp1L = (mid1 + side1) << shift;
  75092. temp2L = (mid2 + side2) << shift;
  75093. temp3L = (mid3 + side3) << shift;
  75094. temp0R = (mid0 - side0) << shift;
  75095. temp1R = (mid1 - side1) << shift;
  75096. temp2R = (mid2 - side2) << shift;
  75097. temp3R = (mid3 - side3) << shift;
  75098. temp0L >>= 16;
  75099. temp1L >>= 16;
  75100. temp2L >>= 16;
  75101. temp3L >>= 16;
  75102. temp0R >>= 16;
  75103. temp1R >>= 16;
  75104. temp2R >>= 16;
  75105. temp3R >>= 16;
  75106. pOutputSamples[i*8+0] = (drflac_int16)temp0L;
  75107. pOutputSamples[i*8+1] = (drflac_int16)temp0R;
  75108. pOutputSamples[i*8+2] = (drflac_int16)temp1L;
  75109. pOutputSamples[i*8+3] = (drflac_int16)temp1R;
  75110. pOutputSamples[i*8+4] = (drflac_int16)temp2L;
  75111. pOutputSamples[i*8+5] = (drflac_int16)temp2R;
  75112. pOutputSamples[i*8+6] = (drflac_int16)temp3L;
  75113. pOutputSamples[i*8+7] = (drflac_int16)temp3R;
  75114. }
  75115. } else {
  75116. for (i = 0; i < frameCount4; ++i) {
  75117. drflac_uint32 temp0L;
  75118. drflac_uint32 temp1L;
  75119. drflac_uint32 temp2L;
  75120. drflac_uint32 temp3L;
  75121. drflac_uint32 temp0R;
  75122. drflac_uint32 temp1R;
  75123. drflac_uint32 temp2R;
  75124. drflac_uint32 temp3R;
  75125. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75126. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75127. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75128. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75129. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75130. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75131. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75132. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75133. mid0 = (mid0 << 1) | (side0 & 0x01);
  75134. mid1 = (mid1 << 1) | (side1 & 0x01);
  75135. mid2 = (mid2 << 1) | (side2 & 0x01);
  75136. mid3 = (mid3 << 1) | (side3 & 0x01);
  75137. temp0L = ((drflac_int32)(mid0 + side0) >> 1);
  75138. temp1L = ((drflac_int32)(mid1 + side1) >> 1);
  75139. temp2L = ((drflac_int32)(mid2 + side2) >> 1);
  75140. temp3L = ((drflac_int32)(mid3 + side3) >> 1);
  75141. temp0R = ((drflac_int32)(mid0 - side0) >> 1);
  75142. temp1R = ((drflac_int32)(mid1 - side1) >> 1);
  75143. temp2R = ((drflac_int32)(mid2 - side2) >> 1);
  75144. temp3R = ((drflac_int32)(mid3 - side3) >> 1);
  75145. temp0L >>= 16;
  75146. temp1L >>= 16;
  75147. temp2L >>= 16;
  75148. temp3L >>= 16;
  75149. temp0R >>= 16;
  75150. temp1R >>= 16;
  75151. temp2R >>= 16;
  75152. temp3R >>= 16;
  75153. pOutputSamples[i*8+0] = (drflac_int16)temp0L;
  75154. pOutputSamples[i*8+1] = (drflac_int16)temp0R;
  75155. pOutputSamples[i*8+2] = (drflac_int16)temp1L;
  75156. pOutputSamples[i*8+3] = (drflac_int16)temp1R;
  75157. pOutputSamples[i*8+4] = (drflac_int16)temp2L;
  75158. pOutputSamples[i*8+5] = (drflac_int16)temp2R;
  75159. pOutputSamples[i*8+6] = (drflac_int16)temp3L;
  75160. pOutputSamples[i*8+7] = (drflac_int16)temp3R;
  75161. }
  75162. }
  75163. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75164. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75165. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75166. mid = (mid << 1) | (side & 0x01);
  75167. pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
  75168. pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
  75169. }
  75170. }
  75171. #if defined(DRFLAC_SUPPORT_SSE2)
  75172. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75173. {
  75174. drflac_uint64 i;
  75175. drflac_uint64 frameCount4 = frameCount >> 2;
  75176. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75177. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75178. drflac_uint32 shift = unusedBitsPerSample;
  75179. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75180. if (shift == 0) {
  75181. for (i = 0; i < frameCount4; ++i) {
  75182. __m128i mid;
  75183. __m128i side;
  75184. __m128i left;
  75185. __m128i right;
  75186. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75187. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75188. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  75189. left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  75190. right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  75191. left = _mm_srai_epi32(left, 16);
  75192. right = _mm_srai_epi32(right, 16);
  75193. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  75194. }
  75195. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75196. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75197. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75198. mid = (mid << 1) | (side & 0x01);
  75199. pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
  75200. pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
  75201. }
  75202. } else {
  75203. shift -= 1;
  75204. for (i = 0; i < frameCount4; ++i) {
  75205. __m128i mid;
  75206. __m128i side;
  75207. __m128i left;
  75208. __m128i right;
  75209. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75210. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75211. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  75212. left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  75213. right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  75214. left = _mm_srai_epi32(left, 16);
  75215. right = _mm_srai_epi32(right, 16);
  75216. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  75217. }
  75218. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75219. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75220. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75221. mid = (mid << 1) | (side & 0x01);
  75222. pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
  75223. pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
  75224. }
  75225. }
  75226. }
  75227. #endif
  75228. #if defined(DRFLAC_SUPPORT_NEON)
  75229. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75230. {
  75231. drflac_uint64 i;
  75232. drflac_uint64 frameCount4 = frameCount >> 2;
  75233. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75234. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75235. drflac_uint32 shift = unusedBitsPerSample;
  75236. int32x4_t wbpsShift0_4;
  75237. int32x4_t wbpsShift1_4;
  75238. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75239. wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75240. wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75241. if (shift == 0) {
  75242. for (i = 0; i < frameCount4; ++i) {
  75243. uint32x4_t mid;
  75244. uint32x4_t side;
  75245. int32x4_t left;
  75246. int32x4_t right;
  75247. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  75248. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  75249. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  75250. left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  75251. right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  75252. left = vshrq_n_s32(left, 16);
  75253. right = vshrq_n_s32(right, 16);
  75254. drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  75255. }
  75256. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75257. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75258. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75259. mid = (mid << 1) | (side & 0x01);
  75260. pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
  75261. pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
  75262. }
  75263. } else {
  75264. int32x4_t shift4;
  75265. shift -= 1;
  75266. shift4 = vdupq_n_s32(shift);
  75267. for (i = 0; i < frameCount4; ++i) {
  75268. uint32x4_t mid;
  75269. uint32x4_t side;
  75270. int32x4_t left;
  75271. int32x4_t right;
  75272. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  75273. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  75274. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  75275. left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  75276. right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  75277. left = vshrq_n_s32(left, 16);
  75278. right = vshrq_n_s32(right, 16);
  75279. drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  75280. }
  75281. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75282. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75283. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75284. mid = (mid << 1) | (side & 0x01);
  75285. pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
  75286. pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
  75287. }
  75288. }
  75289. }
  75290. #endif
  75291. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75292. {
  75293. #if defined(DRFLAC_SUPPORT_SSE2)
  75294. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  75295. drflac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75296. } else
  75297. #elif defined(DRFLAC_SUPPORT_NEON)
  75298. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  75299. drflac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75300. } else
  75301. #endif
  75302. {
  75303. #if 0
  75304. drflac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75305. #else
  75306. drflac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75307. #endif
  75308. }
  75309. }
  75310. #if 0
  75311. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75312. {
  75313. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  75314. pOutputSamples[i*2+0] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16);
  75315. pOutputSamples[i*2+1] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16);
  75316. }
  75317. }
  75318. #endif
  75319. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75320. {
  75321. drflac_uint64 i;
  75322. drflac_uint64 frameCount4 = frameCount >> 2;
  75323. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75324. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75325. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75326. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75327. for (i = 0; i < frameCount4; ++i) {
  75328. drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  75329. drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  75330. drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  75331. drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  75332. drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  75333. drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  75334. drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  75335. drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  75336. tempL0 >>= 16;
  75337. tempL1 >>= 16;
  75338. tempL2 >>= 16;
  75339. tempL3 >>= 16;
  75340. tempR0 >>= 16;
  75341. tempR1 >>= 16;
  75342. tempR2 >>= 16;
  75343. tempR3 >>= 16;
  75344. pOutputSamples[i*8+0] = (drflac_int16)tempL0;
  75345. pOutputSamples[i*8+1] = (drflac_int16)tempR0;
  75346. pOutputSamples[i*8+2] = (drflac_int16)tempL1;
  75347. pOutputSamples[i*8+3] = (drflac_int16)tempR1;
  75348. pOutputSamples[i*8+4] = (drflac_int16)tempL2;
  75349. pOutputSamples[i*8+5] = (drflac_int16)tempR2;
  75350. pOutputSamples[i*8+6] = (drflac_int16)tempL3;
  75351. pOutputSamples[i*8+7] = (drflac_int16)tempR3;
  75352. }
  75353. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75354. pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
  75355. pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
  75356. }
  75357. }
  75358. #if defined(DRFLAC_SUPPORT_SSE2)
  75359. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75360. {
  75361. drflac_uint64 i;
  75362. drflac_uint64 frameCount4 = frameCount >> 2;
  75363. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75364. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75365. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75366. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75367. for (i = 0; i < frameCount4; ++i) {
  75368. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  75369. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  75370. left = _mm_srai_epi32(left, 16);
  75371. right = _mm_srai_epi32(right, 16);
  75372. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  75373. }
  75374. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75375. pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
  75376. pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
  75377. }
  75378. }
  75379. #endif
  75380. #if defined(DRFLAC_SUPPORT_NEON)
  75381. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75382. {
  75383. drflac_uint64 i;
  75384. drflac_uint64 frameCount4 = frameCount >> 2;
  75385. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75386. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75387. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75388. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75389. int32x4_t shift0_4 = vdupq_n_s32(shift0);
  75390. int32x4_t shift1_4 = vdupq_n_s32(shift1);
  75391. for (i = 0; i < frameCount4; ++i) {
  75392. int32x4_t left;
  75393. int32x4_t right;
  75394. left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
  75395. right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
  75396. left = vshrq_n_s32(left, 16);
  75397. right = vshrq_n_s32(right, 16);
  75398. drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  75399. }
  75400. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75401. pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
  75402. pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
  75403. }
  75404. }
  75405. #endif
  75406. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  75407. {
  75408. #if defined(DRFLAC_SUPPORT_SSE2)
  75409. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  75410. drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75411. } else
  75412. #elif defined(DRFLAC_SUPPORT_NEON)
  75413. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  75414. drflac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75415. } else
  75416. #endif
  75417. {
  75418. #if 0
  75419. drflac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75420. #else
  75421. drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75422. #endif
  75423. }
  75424. }
  75425. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut)
  75426. {
  75427. drflac_uint64 framesRead;
  75428. drflac_uint32 unusedBitsPerSample;
  75429. if (pFlac == NULL || framesToRead == 0) {
  75430. return 0;
  75431. }
  75432. if (pBufferOut == NULL) {
  75433. return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  75434. }
  75435. DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
  75436. unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  75437. framesRead = 0;
  75438. while (framesToRead > 0) {
  75439. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  75440. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  75441. break;
  75442. }
  75443. } else {
  75444. unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  75445. drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  75446. drflac_uint64 frameCountThisIteration = framesToRead;
  75447. if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  75448. frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  75449. }
  75450. if (channelCount == 2) {
  75451. const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  75452. const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  75453. switch (pFlac->currentFLACFrame.header.channelAssignment)
  75454. {
  75455. case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  75456. {
  75457. drflac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75458. } break;
  75459. case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  75460. {
  75461. drflac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75462. } break;
  75463. case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  75464. {
  75465. drflac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75466. } break;
  75467. case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  75468. default:
  75469. {
  75470. drflac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75471. } break;
  75472. }
  75473. } else {
  75474. drflac_uint64 i;
  75475. for (i = 0; i < frameCountThisIteration; ++i) {
  75476. unsigned int j;
  75477. for (j = 0; j < channelCount; ++j) {
  75478. drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  75479. pBufferOut[(i*channelCount)+j] = (drflac_int16)(sampleS32 >> 16);
  75480. }
  75481. }
  75482. }
  75483. framesRead += frameCountThisIteration;
  75484. pBufferOut += frameCountThisIteration * channelCount;
  75485. framesToRead -= frameCountThisIteration;
  75486. pFlac->currentPCMFrame += frameCountThisIteration;
  75487. pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
  75488. }
  75489. }
  75490. return framesRead;
  75491. }
  75492. #if 0
  75493. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75494. {
  75495. drflac_uint64 i;
  75496. for (i = 0; i < frameCount; ++i) {
  75497. drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75498. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75499. drflac_uint32 right = left - side;
  75500. pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
  75501. pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
  75502. }
  75503. }
  75504. #endif
  75505. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75506. {
  75507. drflac_uint64 i;
  75508. drflac_uint64 frameCount4 = frameCount >> 2;
  75509. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75510. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75511. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75512. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75513. float factor = 1 / 2147483648.0;
  75514. for (i = 0; i < frameCount4; ++i) {
  75515. drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  75516. drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  75517. drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  75518. drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  75519. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  75520. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  75521. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  75522. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  75523. drflac_uint32 right0 = left0 - side0;
  75524. drflac_uint32 right1 = left1 - side1;
  75525. drflac_uint32 right2 = left2 - side2;
  75526. drflac_uint32 right3 = left3 - side3;
  75527. pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
  75528. pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
  75529. pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
  75530. pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
  75531. pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
  75532. pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
  75533. pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
  75534. pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
  75535. }
  75536. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75537. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  75538. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  75539. drflac_uint32 right = left - side;
  75540. pOutputSamples[i*2+0] = (drflac_int32)left * factor;
  75541. pOutputSamples[i*2+1] = (drflac_int32)right * factor;
  75542. }
  75543. }
  75544. #if defined(DRFLAC_SUPPORT_SSE2)
  75545. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75546. {
  75547. drflac_uint64 i;
  75548. drflac_uint64 frameCount4 = frameCount >> 2;
  75549. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75550. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75551. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75552. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75553. __m128 factor;
  75554. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75555. factor = _mm_set1_ps(1.0f / 8388608.0f);
  75556. for (i = 0; i < frameCount4; ++i) {
  75557. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  75558. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  75559. __m128i right = _mm_sub_epi32(left, side);
  75560. __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
  75561. __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
  75562. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  75563. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  75564. }
  75565. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75566. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  75567. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  75568. drflac_uint32 right = left - side;
  75569. pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
  75570. pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  75571. }
  75572. }
  75573. #endif
  75574. #if defined(DRFLAC_SUPPORT_NEON)
  75575. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75576. {
  75577. drflac_uint64 i;
  75578. drflac_uint64 frameCount4 = frameCount >> 2;
  75579. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75580. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75581. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75582. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75583. float32x4_t factor4;
  75584. int32x4_t shift0_4;
  75585. int32x4_t shift1_4;
  75586. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75587. factor4 = vdupq_n_f32(1.0f / 8388608.0f);
  75588. shift0_4 = vdupq_n_s32(shift0);
  75589. shift1_4 = vdupq_n_s32(shift1);
  75590. for (i = 0; i < frameCount4; ++i) {
  75591. uint32x4_t left;
  75592. uint32x4_t side;
  75593. uint32x4_t right;
  75594. float32x4_t leftf;
  75595. float32x4_t rightf;
  75596. left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  75597. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  75598. right = vsubq_u32(left, side);
  75599. leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
  75600. rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
  75601. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  75602. }
  75603. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75604. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  75605. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  75606. drflac_uint32 right = left - side;
  75607. pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
  75608. pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  75609. }
  75610. }
  75611. #endif
  75612. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75613. {
  75614. #if defined(DRFLAC_SUPPORT_SSE2)
  75615. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  75616. drflac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75617. } else
  75618. #elif defined(DRFLAC_SUPPORT_NEON)
  75619. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  75620. drflac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75621. } else
  75622. #endif
  75623. {
  75624. #if 0
  75625. drflac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75626. #else
  75627. drflac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75628. #endif
  75629. }
  75630. }
  75631. #if 0
  75632. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75633. {
  75634. drflac_uint64 i;
  75635. for (i = 0; i < frameCount; ++i) {
  75636. drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75637. drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75638. drflac_uint32 left = right + side;
  75639. pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
  75640. pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
  75641. }
  75642. }
  75643. #endif
  75644. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75645. {
  75646. drflac_uint64 i;
  75647. drflac_uint64 frameCount4 = frameCount >> 2;
  75648. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75649. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75650. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75651. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75652. float factor = 1 / 2147483648.0;
  75653. for (i = 0; i < frameCount4; ++i) {
  75654. drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
  75655. drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
  75656. drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
  75657. drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
  75658. drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  75659. drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  75660. drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  75661. drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  75662. drflac_uint32 left0 = right0 + side0;
  75663. drflac_uint32 left1 = right1 + side1;
  75664. drflac_uint32 left2 = right2 + side2;
  75665. drflac_uint32 left3 = right3 + side3;
  75666. pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
  75667. pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
  75668. pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
  75669. pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
  75670. pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
  75671. pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
  75672. pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
  75673. pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
  75674. }
  75675. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75676. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  75677. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  75678. drflac_uint32 left = right + side;
  75679. pOutputSamples[i*2+0] = (drflac_int32)left * factor;
  75680. pOutputSamples[i*2+1] = (drflac_int32)right * factor;
  75681. }
  75682. }
  75683. #if defined(DRFLAC_SUPPORT_SSE2)
  75684. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75685. {
  75686. drflac_uint64 i;
  75687. drflac_uint64 frameCount4 = frameCount >> 2;
  75688. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75689. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75690. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75691. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75692. __m128 factor;
  75693. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75694. factor = _mm_set1_ps(1.0f / 8388608.0f);
  75695. for (i = 0; i < frameCount4; ++i) {
  75696. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  75697. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  75698. __m128i left = _mm_add_epi32(right, side);
  75699. __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
  75700. __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
  75701. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  75702. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  75703. }
  75704. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75705. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  75706. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  75707. drflac_uint32 left = right + side;
  75708. pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
  75709. pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  75710. }
  75711. }
  75712. #endif
  75713. #if defined(DRFLAC_SUPPORT_NEON)
  75714. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75715. {
  75716. drflac_uint64 i;
  75717. drflac_uint64 frameCount4 = frameCount >> 2;
  75718. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75719. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75720. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75721. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75722. float32x4_t factor4;
  75723. int32x4_t shift0_4;
  75724. int32x4_t shift1_4;
  75725. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75726. factor4 = vdupq_n_f32(1.0f / 8388608.0f);
  75727. shift0_4 = vdupq_n_s32(shift0);
  75728. shift1_4 = vdupq_n_s32(shift1);
  75729. for (i = 0; i < frameCount4; ++i) {
  75730. uint32x4_t side;
  75731. uint32x4_t right;
  75732. uint32x4_t left;
  75733. float32x4_t leftf;
  75734. float32x4_t rightf;
  75735. side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  75736. right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  75737. left = vaddq_u32(right, side);
  75738. leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
  75739. rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
  75740. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  75741. }
  75742. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75743. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  75744. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  75745. drflac_uint32 left = right + side;
  75746. pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
  75747. pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  75748. }
  75749. }
  75750. #endif
  75751. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75752. {
  75753. #if defined(DRFLAC_SUPPORT_SSE2)
  75754. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  75755. drflac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75756. } else
  75757. #elif defined(DRFLAC_SUPPORT_NEON)
  75758. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  75759. drflac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75760. } else
  75761. #endif
  75762. {
  75763. #if 0
  75764. drflac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75765. #else
  75766. drflac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75767. #endif
  75768. }
  75769. }
  75770. #if 0
  75771. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75772. {
  75773. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  75774. drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75775. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75776. mid = (mid << 1) | (side & 0x01);
  75777. pOutputSamples[i*2+0] = (float)((((drflac_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
  75778. pOutputSamples[i*2+1] = (float)((((drflac_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
  75779. }
  75780. }
  75781. #endif
  75782. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75783. {
  75784. drflac_uint64 i;
  75785. drflac_uint64 frameCount4 = frameCount >> 2;
  75786. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75787. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75788. drflac_uint32 shift = unusedBitsPerSample;
  75789. float factor = 1 / 2147483648.0;
  75790. if (shift > 0) {
  75791. shift -= 1;
  75792. for (i = 0; i < frameCount4; ++i) {
  75793. drflac_uint32 temp0L;
  75794. drflac_uint32 temp1L;
  75795. drflac_uint32 temp2L;
  75796. drflac_uint32 temp3L;
  75797. drflac_uint32 temp0R;
  75798. drflac_uint32 temp1R;
  75799. drflac_uint32 temp2R;
  75800. drflac_uint32 temp3R;
  75801. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75802. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75803. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75804. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75805. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75806. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75807. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75808. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75809. mid0 = (mid0 << 1) | (side0 & 0x01);
  75810. mid1 = (mid1 << 1) | (side1 & 0x01);
  75811. mid2 = (mid2 << 1) | (side2 & 0x01);
  75812. mid3 = (mid3 << 1) | (side3 & 0x01);
  75813. temp0L = (mid0 + side0) << shift;
  75814. temp1L = (mid1 + side1) << shift;
  75815. temp2L = (mid2 + side2) << shift;
  75816. temp3L = (mid3 + side3) << shift;
  75817. temp0R = (mid0 - side0) << shift;
  75818. temp1R = (mid1 - side1) << shift;
  75819. temp2R = (mid2 - side2) << shift;
  75820. temp3R = (mid3 - side3) << shift;
  75821. pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
  75822. pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
  75823. pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
  75824. pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
  75825. pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
  75826. pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
  75827. pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
  75828. pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
  75829. }
  75830. } else {
  75831. for (i = 0; i < frameCount4; ++i) {
  75832. drflac_uint32 temp0L;
  75833. drflac_uint32 temp1L;
  75834. drflac_uint32 temp2L;
  75835. drflac_uint32 temp3L;
  75836. drflac_uint32 temp0R;
  75837. drflac_uint32 temp1R;
  75838. drflac_uint32 temp2R;
  75839. drflac_uint32 temp3R;
  75840. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75841. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75842. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75843. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75844. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75845. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75846. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75847. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75848. mid0 = (mid0 << 1) | (side0 & 0x01);
  75849. mid1 = (mid1 << 1) | (side1 & 0x01);
  75850. mid2 = (mid2 << 1) | (side2 & 0x01);
  75851. mid3 = (mid3 << 1) | (side3 & 0x01);
  75852. temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
  75853. temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
  75854. temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
  75855. temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
  75856. temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
  75857. temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
  75858. temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
  75859. temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
  75860. pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
  75861. pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
  75862. pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
  75863. pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
  75864. pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
  75865. pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
  75866. pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
  75867. pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
  75868. }
  75869. }
  75870. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75871. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75872. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75873. mid = (mid << 1) | (side & 0x01);
  75874. pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor;
  75875. pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor;
  75876. }
  75877. }
  75878. #if defined(DRFLAC_SUPPORT_SSE2)
  75879. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75880. {
  75881. drflac_uint64 i;
  75882. drflac_uint64 frameCount4 = frameCount >> 2;
  75883. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75884. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75885. drflac_uint32 shift = unusedBitsPerSample - 8;
  75886. float factor;
  75887. __m128 factor128;
  75888. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75889. factor = 1.0f / 8388608.0f;
  75890. factor128 = _mm_set1_ps(factor);
  75891. if (shift == 0) {
  75892. for (i = 0; i < frameCount4; ++i) {
  75893. __m128i mid;
  75894. __m128i side;
  75895. __m128i tempL;
  75896. __m128i tempR;
  75897. __m128 leftf;
  75898. __m128 rightf;
  75899. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75900. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75901. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  75902. tempL = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  75903. tempR = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  75904. leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
  75905. rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
  75906. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  75907. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  75908. }
  75909. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75910. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75911. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75912. mid = (mid << 1) | (side & 0x01);
  75913. pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
  75914. pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
  75915. }
  75916. } else {
  75917. shift -= 1;
  75918. for (i = 0; i < frameCount4; ++i) {
  75919. __m128i mid;
  75920. __m128i side;
  75921. __m128i tempL;
  75922. __m128i tempR;
  75923. __m128 leftf;
  75924. __m128 rightf;
  75925. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75926. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75927. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  75928. tempL = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  75929. tempR = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  75930. leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
  75931. rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
  75932. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  75933. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  75934. }
  75935. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75936. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75937. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75938. mid = (mid << 1) | (side & 0x01);
  75939. pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
  75940. pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
  75941. }
  75942. }
  75943. }
  75944. #endif
  75945. #if defined(DRFLAC_SUPPORT_NEON)
  75946. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  75947. {
  75948. drflac_uint64 i;
  75949. drflac_uint64 frameCount4 = frameCount >> 2;
  75950. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  75951. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  75952. drflac_uint32 shift = unusedBitsPerSample - 8;
  75953. float factor;
  75954. float32x4_t factor4;
  75955. int32x4_t shift4;
  75956. int32x4_t wbps0_4;
  75957. int32x4_t wbps1_4;
  75958. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75959. factor = 1.0f / 8388608.0f;
  75960. factor4 = vdupq_n_f32(factor);
  75961. wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75962. wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75963. if (shift == 0) {
  75964. for (i = 0; i < frameCount4; ++i) {
  75965. int32x4_t lefti;
  75966. int32x4_t righti;
  75967. float32x4_t leftf;
  75968. float32x4_t rightf;
  75969. uint32x4_t mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
  75970. uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
  75971. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  75972. lefti = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  75973. righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  75974. leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
  75975. rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  75976. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  75977. }
  75978. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75979. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75980. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75981. mid = (mid << 1) | (side & 0x01);
  75982. pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
  75983. pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
  75984. }
  75985. } else {
  75986. shift -= 1;
  75987. shift4 = vdupq_n_s32(shift);
  75988. for (i = 0; i < frameCount4; ++i) {
  75989. uint32x4_t mid;
  75990. uint32x4_t side;
  75991. int32x4_t lefti;
  75992. int32x4_t righti;
  75993. float32x4_t leftf;
  75994. float32x4_t rightf;
  75995. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
  75996. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
  75997. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  75998. lefti = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  75999. righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  76000. leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
  76001. rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  76002. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  76003. }
  76004. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  76005. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  76006. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  76007. mid = (mid << 1) | (side & 0x01);
  76008. pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
  76009. pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
  76010. }
  76011. }
  76012. }
  76013. #endif
  76014. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  76015. {
  76016. #if defined(DRFLAC_SUPPORT_SSE2)
  76017. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  76018. drflac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  76019. } else
  76020. #elif defined(DRFLAC_SUPPORT_NEON)
  76021. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  76022. drflac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  76023. } else
  76024. #endif
  76025. {
  76026. #if 0
  76027. drflac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  76028. #else
  76029. drflac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  76030. #endif
  76031. }
  76032. }
  76033. #if 0
  76034. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  76035. {
  76036. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  76037. pOutputSamples[i*2+0] = (float)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0);
  76038. pOutputSamples[i*2+1] = (float)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0);
  76039. }
  76040. }
  76041. #endif
  76042. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  76043. {
  76044. drflac_uint64 i;
  76045. drflac_uint64 frameCount4 = frameCount >> 2;
  76046. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  76047. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  76048. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  76049. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  76050. float factor = 1 / 2147483648.0;
  76051. for (i = 0; i < frameCount4; ++i) {
  76052. drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  76053. drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  76054. drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  76055. drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  76056. drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  76057. drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  76058. drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  76059. drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  76060. pOutputSamples[i*8+0] = (drflac_int32)tempL0 * factor;
  76061. pOutputSamples[i*8+1] = (drflac_int32)tempR0 * factor;
  76062. pOutputSamples[i*8+2] = (drflac_int32)tempL1 * factor;
  76063. pOutputSamples[i*8+3] = (drflac_int32)tempR1 * factor;
  76064. pOutputSamples[i*8+4] = (drflac_int32)tempL2 * factor;
  76065. pOutputSamples[i*8+5] = (drflac_int32)tempR2 * factor;
  76066. pOutputSamples[i*8+6] = (drflac_int32)tempL3 * factor;
  76067. pOutputSamples[i*8+7] = (drflac_int32)tempR3 * factor;
  76068. }
  76069. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  76070. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
  76071. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
  76072. }
  76073. }
  76074. #if defined(DRFLAC_SUPPORT_SSE2)
  76075. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  76076. {
  76077. drflac_uint64 i;
  76078. drflac_uint64 frameCount4 = frameCount >> 2;
  76079. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  76080. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  76081. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  76082. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  76083. float factor = 1.0f / 8388608.0f;
  76084. __m128 factor128 = _mm_set1_ps(factor);
  76085. for (i = 0; i < frameCount4; ++i) {
  76086. __m128i lefti;
  76087. __m128i righti;
  76088. __m128 leftf;
  76089. __m128 rightf;
  76090. lefti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  76091. righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  76092. leftf = _mm_mul_ps(_mm_cvtepi32_ps(lefti), factor128);
  76093. rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128);
  76094. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  76095. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  76096. }
  76097. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  76098. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
  76099. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
  76100. }
  76101. }
  76102. #endif
  76103. #if defined(DRFLAC_SUPPORT_NEON)
  76104. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  76105. {
  76106. drflac_uint64 i;
  76107. drflac_uint64 frameCount4 = frameCount >> 2;
  76108. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  76109. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  76110. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  76111. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  76112. float factor = 1.0f / 8388608.0f;
  76113. float32x4_t factor4 = vdupq_n_f32(factor);
  76114. int32x4_t shift0_4 = vdupq_n_s32(shift0);
  76115. int32x4_t shift1_4 = vdupq_n_s32(shift1);
  76116. for (i = 0; i < frameCount4; ++i) {
  76117. int32x4_t lefti;
  76118. int32x4_t righti;
  76119. float32x4_t leftf;
  76120. float32x4_t rightf;
  76121. lefti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
  76122. righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
  76123. leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
  76124. rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  76125. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  76126. }
  76127. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  76128. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
  76129. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
  76130. }
  76131. }
  76132. #endif
  76133. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  76134. {
  76135. #if defined(DRFLAC_SUPPORT_SSE2)
  76136. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  76137. drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  76138. } else
  76139. #elif defined(DRFLAC_SUPPORT_NEON)
  76140. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  76141. drflac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  76142. } else
  76143. #endif
  76144. {
  76145. #if 0
  76146. drflac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  76147. #else
  76148. drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  76149. #endif
  76150. }
  76151. }
  76152. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut)
  76153. {
  76154. drflac_uint64 framesRead;
  76155. drflac_uint32 unusedBitsPerSample;
  76156. if (pFlac == NULL || framesToRead == 0) {
  76157. return 0;
  76158. }
  76159. if (pBufferOut == NULL) {
  76160. return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  76161. }
  76162. DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
  76163. unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  76164. framesRead = 0;
  76165. while (framesToRead > 0) {
  76166. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  76167. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  76168. break;
  76169. }
  76170. } else {
  76171. unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  76172. drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  76173. drflac_uint64 frameCountThisIteration = framesToRead;
  76174. if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  76175. frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  76176. }
  76177. if (channelCount == 2) {
  76178. const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  76179. const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  76180. switch (pFlac->currentFLACFrame.header.channelAssignment)
  76181. {
  76182. case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  76183. {
  76184. drflac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  76185. } break;
  76186. case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  76187. {
  76188. drflac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  76189. } break;
  76190. case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  76191. {
  76192. drflac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  76193. } break;
  76194. case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  76195. default:
  76196. {
  76197. drflac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  76198. } break;
  76199. }
  76200. } else {
  76201. drflac_uint64 i;
  76202. for (i = 0; i < frameCountThisIteration; ++i) {
  76203. unsigned int j;
  76204. for (j = 0; j < channelCount; ++j) {
  76205. drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  76206. pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0);
  76207. }
  76208. }
  76209. }
  76210. framesRead += frameCountThisIteration;
  76211. pBufferOut += frameCountThisIteration * channelCount;
  76212. framesToRead -= frameCountThisIteration;
  76213. pFlac->currentPCMFrame += frameCountThisIteration;
  76214. pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration;
  76215. }
  76216. }
  76217. return framesRead;
  76218. }
  76219. DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  76220. {
  76221. if (pFlac == NULL) {
  76222. return DRFLAC_FALSE;
  76223. }
  76224. if (pFlac->currentPCMFrame == pcmFrameIndex) {
  76225. return DRFLAC_TRUE;
  76226. }
  76227. if (pFlac->firstFLACFramePosInBytes == 0) {
  76228. return DRFLAC_FALSE;
  76229. }
  76230. if (pcmFrameIndex == 0) {
  76231. pFlac->currentPCMFrame = 0;
  76232. return drflac__seek_to_first_frame(pFlac);
  76233. } else {
  76234. drflac_bool32 wasSuccessful = DRFLAC_FALSE;
  76235. drflac_uint64 originalPCMFrame = pFlac->currentPCMFrame;
  76236. if (pcmFrameIndex > pFlac->totalPCMFrameCount) {
  76237. pcmFrameIndex = pFlac->totalPCMFrameCount;
  76238. }
  76239. if (pcmFrameIndex > pFlac->currentPCMFrame) {
  76240. drflac_uint32 offset = (drflac_uint32)(pcmFrameIndex - pFlac->currentPCMFrame);
  76241. if (pFlac->currentFLACFrame.pcmFramesRemaining > offset) {
  76242. pFlac->currentFLACFrame.pcmFramesRemaining -= offset;
  76243. pFlac->currentPCMFrame = pcmFrameIndex;
  76244. return DRFLAC_TRUE;
  76245. }
  76246. } else {
  76247. drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentPCMFrame - pcmFrameIndex);
  76248. drflac_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  76249. drflac_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining;
  76250. if (currentFLACFramePCMFramesConsumed > offsetAbs) {
  76251. pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs;
  76252. pFlac->currentPCMFrame = pcmFrameIndex;
  76253. return DRFLAC_TRUE;
  76254. }
  76255. }
  76256. #ifndef DR_FLAC_NO_OGG
  76257. if (pFlac->container == drflac_container_ogg)
  76258. {
  76259. wasSuccessful = drflac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex);
  76260. }
  76261. else
  76262. #endif
  76263. {
  76264. if (!pFlac->_noSeekTableSeek) {
  76265. wasSuccessful = drflac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex);
  76266. }
  76267. #if !defined(DR_FLAC_NO_CRC)
  76268. if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) {
  76269. wasSuccessful = drflac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex);
  76270. }
  76271. #endif
  76272. if (!wasSuccessful && !pFlac->_noBruteForceSeek) {
  76273. wasSuccessful = drflac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex);
  76274. }
  76275. }
  76276. if (wasSuccessful) {
  76277. pFlac->currentPCMFrame = pcmFrameIndex;
  76278. } else {
  76279. if (drflac_seek_to_pcm_frame(pFlac, originalPCMFrame) == DRFLAC_FALSE) {
  76280. drflac_seek_to_pcm_frame(pFlac, 0);
  76281. }
  76282. }
  76283. return wasSuccessful;
  76284. }
  76285. }
  76286. #if defined(SIZE_MAX)
  76287. #define DRFLAC_SIZE_MAX SIZE_MAX
  76288. #else
  76289. #if defined(DRFLAC_64BIT)
  76290. #define DRFLAC_SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF)
  76291. #else
  76292. #define DRFLAC_SIZE_MAX 0xFFFFFFFF
  76293. #endif
  76294. #endif
  76295. #define DRFLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \
  76296. static type* drflac__full_read_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut)\
  76297. { \
  76298. type* pSampleData = NULL; \
  76299. drflac_uint64 totalPCMFrameCount; \
  76300. \
  76301. DRFLAC_ASSERT(pFlac != NULL); \
  76302. \
  76303. totalPCMFrameCount = pFlac->totalPCMFrameCount; \
  76304. \
  76305. if (totalPCMFrameCount == 0) { \
  76306. type buffer[4096]; \
  76307. drflac_uint64 pcmFramesRead; \
  76308. size_t sampleDataBufferSize = sizeof(buffer); \
  76309. \
  76310. pSampleData = (type*)drflac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks); \
  76311. if (pSampleData == NULL) { \
  76312. goto on_error; \
  76313. } \
  76314. \
  76315. while ((pcmFramesRead = (drflac_uint64)drflac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \
  76316. if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \
  76317. type* pNewSampleData; \
  76318. size_t newSampleDataBufferSize; \
  76319. \
  76320. newSampleDataBufferSize = sampleDataBufferSize * 2; \
  76321. pNewSampleData = (type*)drflac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks); \
  76322. if (pNewSampleData == NULL) { \
  76323. drflac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks); \
  76324. goto on_error; \
  76325. } \
  76326. \
  76327. sampleDataBufferSize = newSampleDataBufferSize; \
  76328. pSampleData = pNewSampleData; \
  76329. } \
  76330. \
  76331. DRFLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \
  76332. totalPCMFrameCount += pcmFramesRead; \
  76333. } \
  76334. \
  76335. \
  76336. DRFLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \
  76337. } else { \
  76338. drflac_uint64 dataSize = totalPCMFrameCount*pFlac->channels*sizeof(type); \
  76339. if (dataSize > (drflac_uint64)DRFLAC_SIZE_MAX) { \
  76340. goto on_error; \
  76341. } \
  76342. \
  76343. pSampleData = (type*)drflac__malloc_from_callbacks((size_t)dataSize, &pFlac->allocationCallbacks); \
  76344. if (pSampleData == NULL) { \
  76345. goto on_error; \
  76346. } \
  76347. \
  76348. totalPCMFrameCount = drflac_read_pcm_frames_##extension(pFlac, pFlac->totalPCMFrameCount, pSampleData); \
  76349. } \
  76350. \
  76351. if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \
  76352. if (channelsOut) *channelsOut = pFlac->channels; \
  76353. if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \
  76354. \
  76355. drflac_close(pFlac); \
  76356. return pSampleData; \
  76357. \
  76358. on_error: \
  76359. drflac_close(pFlac); \
  76360. return NULL; \
  76361. }
  76362. DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s32, drflac_int32)
  76363. DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s16, drflac_int16)
  76364. DRFLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float)
  76365. DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
  76366. {
  76367. drflac* pFlac;
  76368. if (channelsOut) {
  76369. *channelsOut = 0;
  76370. }
  76371. if (sampleRateOut) {
  76372. *sampleRateOut = 0;
  76373. }
  76374. if (totalPCMFrameCountOut) {
  76375. *totalPCMFrameCountOut = 0;
  76376. }
  76377. pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  76378. if (pFlac == NULL) {
  76379. return NULL;
  76380. }
  76381. return drflac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  76382. }
  76383. DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
  76384. {
  76385. drflac* pFlac;
  76386. if (channelsOut) {
  76387. *channelsOut = 0;
  76388. }
  76389. if (sampleRateOut) {
  76390. *sampleRateOut = 0;
  76391. }
  76392. if (totalPCMFrameCountOut) {
  76393. *totalPCMFrameCountOut = 0;
  76394. }
  76395. pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  76396. if (pFlac == NULL) {
  76397. return NULL;
  76398. }
  76399. return drflac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  76400. }
  76401. DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
  76402. {
  76403. drflac* pFlac;
  76404. if (channelsOut) {
  76405. *channelsOut = 0;
  76406. }
  76407. if (sampleRateOut) {
  76408. *sampleRateOut = 0;
  76409. }
  76410. if (totalPCMFrameCountOut) {
  76411. *totalPCMFrameCountOut = 0;
  76412. }
  76413. pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  76414. if (pFlac == NULL) {
  76415. return NULL;
  76416. }
  76417. return drflac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  76418. }
  76419. #ifndef DR_FLAC_NO_STDIO
  76420. DRFLAC_API drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  76421. {
  76422. drflac* pFlac;
  76423. if (sampleRate) {
  76424. *sampleRate = 0;
  76425. }
  76426. if (channels) {
  76427. *channels = 0;
  76428. }
  76429. if (totalPCMFrameCount) {
  76430. *totalPCMFrameCount = 0;
  76431. }
  76432. pFlac = drflac_open_file(filename, pAllocationCallbacks);
  76433. if (pFlac == NULL) {
  76434. return NULL;
  76435. }
  76436. return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
  76437. }
  76438. DRFLAC_API drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  76439. {
  76440. drflac* pFlac;
  76441. if (sampleRate) {
  76442. *sampleRate = 0;
  76443. }
  76444. if (channels) {
  76445. *channels = 0;
  76446. }
  76447. if (totalPCMFrameCount) {
  76448. *totalPCMFrameCount = 0;
  76449. }
  76450. pFlac = drflac_open_file(filename, pAllocationCallbacks);
  76451. if (pFlac == NULL) {
  76452. return NULL;
  76453. }
  76454. return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
  76455. }
  76456. DRFLAC_API float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  76457. {
  76458. drflac* pFlac;
  76459. if (sampleRate) {
  76460. *sampleRate = 0;
  76461. }
  76462. if (channels) {
  76463. *channels = 0;
  76464. }
  76465. if (totalPCMFrameCount) {
  76466. *totalPCMFrameCount = 0;
  76467. }
  76468. pFlac = drflac_open_file(filename, pAllocationCallbacks);
  76469. if (pFlac == NULL) {
  76470. return NULL;
  76471. }
  76472. return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
  76473. }
  76474. #endif
  76475. DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  76476. {
  76477. drflac* pFlac;
  76478. if (sampleRate) {
  76479. *sampleRate = 0;
  76480. }
  76481. if (channels) {
  76482. *channels = 0;
  76483. }
  76484. if (totalPCMFrameCount) {
  76485. *totalPCMFrameCount = 0;
  76486. }
  76487. pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
  76488. if (pFlac == NULL) {
  76489. return NULL;
  76490. }
  76491. return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
  76492. }
  76493. DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  76494. {
  76495. drflac* pFlac;
  76496. if (sampleRate) {
  76497. *sampleRate = 0;
  76498. }
  76499. if (channels) {
  76500. *channels = 0;
  76501. }
  76502. if (totalPCMFrameCount) {
  76503. *totalPCMFrameCount = 0;
  76504. }
  76505. pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
  76506. if (pFlac == NULL) {
  76507. return NULL;
  76508. }
  76509. return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
  76510. }
  76511. DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  76512. {
  76513. drflac* pFlac;
  76514. if (sampleRate) {
  76515. *sampleRate = 0;
  76516. }
  76517. if (channels) {
  76518. *channels = 0;
  76519. }
  76520. if (totalPCMFrameCount) {
  76521. *totalPCMFrameCount = 0;
  76522. }
  76523. pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
  76524. if (pFlac == NULL) {
  76525. return NULL;
  76526. }
  76527. return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
  76528. }
  76529. DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
  76530. {
  76531. if (pAllocationCallbacks != NULL) {
  76532. drflac__free_from_callbacks(p, pAllocationCallbacks);
  76533. } else {
  76534. drflac__free_default(p, NULL);
  76535. }
  76536. }
  76537. DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments)
  76538. {
  76539. if (pIter == NULL) {
  76540. return;
  76541. }
  76542. pIter->countRemaining = commentCount;
  76543. pIter->pRunningData = (const char*)pComments;
  76544. }
  76545. DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut)
  76546. {
  76547. drflac_int32 length;
  76548. const char* pComment;
  76549. if (pCommentLengthOut) {
  76550. *pCommentLengthOut = 0;
  76551. }
  76552. if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
  76553. return NULL;
  76554. }
  76555. length = drflac__le2host_32_ptr_unaligned(pIter->pRunningData);
  76556. pIter->pRunningData += 4;
  76557. pComment = pIter->pRunningData;
  76558. pIter->pRunningData += length;
  76559. pIter->countRemaining -= 1;
  76560. if (pCommentLengthOut) {
  76561. *pCommentLengthOut = length;
  76562. }
  76563. return pComment;
  76564. }
  76565. DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData)
  76566. {
  76567. if (pIter == NULL) {
  76568. return;
  76569. }
  76570. pIter->countRemaining = trackCount;
  76571. pIter->pRunningData = (const char*)pTrackData;
  76572. }
  76573. DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack)
  76574. {
  76575. drflac_cuesheet_track cuesheetTrack;
  76576. const char* pRunningData;
  76577. drflac_uint64 offsetHi;
  76578. drflac_uint64 offsetLo;
  76579. if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
  76580. return DRFLAC_FALSE;
  76581. }
  76582. pRunningData = pIter->pRunningData;
  76583. offsetHi = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  76584. offsetLo = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  76585. cuesheetTrack.offset = offsetLo | (offsetHi << 32);
  76586. cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1;
  76587. DRFLAC_COPY_MEMORY(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC)); pRunningData += 12;
  76588. cuesheetTrack.isAudio = (pRunningData[0] & 0x80) != 0;
  76589. cuesheetTrack.preEmphasis = (pRunningData[0] & 0x40) != 0; pRunningData += 14;
  76590. cuesheetTrack.indexCount = pRunningData[0]; pRunningData += 1;
  76591. cuesheetTrack.pIndexPoints = (const drflac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(drflac_cuesheet_track_index);
  76592. pIter->pRunningData = pRunningData;
  76593. pIter->countRemaining -= 1;
  76594. if (pCuesheetTrack) {
  76595. *pCuesheetTrack = cuesheetTrack;
  76596. }
  76597. return DRFLAC_TRUE;
  76598. }
  76599. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  76600. #pragma GCC diagnostic pop
  76601. #endif
  76602. #endif
  76603. /* dr_flac_c end */
  76604. #endif /* DRFLAC_IMPLEMENTATION */
  76605. #endif /* MA_NO_FLAC */
  76606. #if !defined(MA_NO_MP3) && !defined(MA_NO_DECODING)
  76607. #if !defined(DR_MP3_IMPLEMENTATION) && !defined(DRMP3_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
  76608. /* dr_mp3_c begin */
  76609. #ifndef dr_mp3_c
  76610. #define dr_mp3_c
  76611. #include <stdlib.h>
  76612. #include <string.h>
  76613. #include <limits.h>
  76614. DRMP3_API void drmp3_version(drmp3_uint32* pMajor, drmp3_uint32* pMinor, drmp3_uint32* pRevision)
  76615. {
  76616. if (pMajor) {
  76617. *pMajor = DRMP3_VERSION_MAJOR;
  76618. }
  76619. if (pMinor) {
  76620. *pMinor = DRMP3_VERSION_MINOR;
  76621. }
  76622. if (pRevision) {
  76623. *pRevision = DRMP3_VERSION_REVISION;
  76624. }
  76625. }
  76626. DRMP3_API const char* drmp3_version_string(void)
  76627. {
  76628. return DRMP3_VERSION_STRING;
  76629. }
  76630. #if defined(__TINYC__)
  76631. #define DR_MP3_NO_SIMD
  76632. #endif
  76633. #define DRMP3_OFFSET_PTR(p, offset) ((void*)((drmp3_uint8*)(p) + (offset)))
  76634. #define DRMP3_MAX_FREE_FORMAT_FRAME_SIZE 2304
  76635. #ifndef DRMP3_MAX_FRAME_SYNC_MATCHES
  76636. #define DRMP3_MAX_FRAME_SYNC_MATCHES 10
  76637. #endif
  76638. #define DRMP3_MAX_L3_FRAME_PAYLOAD_BYTES DRMP3_MAX_FREE_FORMAT_FRAME_SIZE
  76639. #define DRMP3_MAX_BITRESERVOIR_BYTES 511
  76640. #define DRMP3_SHORT_BLOCK_TYPE 2
  76641. #define DRMP3_STOP_BLOCK_TYPE 3
  76642. #define DRMP3_MODE_MONO 3
  76643. #define DRMP3_MODE_JOINT_STEREO 1
  76644. #define DRMP3_HDR_SIZE 4
  76645. #define DRMP3_HDR_IS_MONO(h) (((h[3]) & 0xC0) == 0xC0)
  76646. #define DRMP3_HDR_IS_MS_STEREO(h) (((h[3]) & 0xE0) == 0x60)
  76647. #define DRMP3_HDR_IS_FREE_FORMAT(h) (((h[2]) & 0xF0) == 0)
  76648. #define DRMP3_HDR_IS_CRC(h) (!((h[1]) & 1))
  76649. #define DRMP3_HDR_TEST_PADDING(h) ((h[2]) & 0x2)
  76650. #define DRMP3_HDR_TEST_MPEG1(h) ((h[1]) & 0x8)
  76651. #define DRMP3_HDR_TEST_NOT_MPEG25(h) ((h[1]) & 0x10)
  76652. #define DRMP3_HDR_TEST_I_STEREO(h) ((h[3]) & 0x10)
  76653. #define DRMP3_HDR_TEST_MS_STEREO(h) ((h[3]) & 0x20)
  76654. #define DRMP3_HDR_GET_STEREO_MODE(h) (((h[3]) >> 6) & 3)
  76655. #define DRMP3_HDR_GET_STEREO_MODE_EXT(h) (((h[3]) >> 4) & 3)
  76656. #define DRMP3_HDR_GET_LAYER(h) (((h[1]) >> 1) & 3)
  76657. #define DRMP3_HDR_GET_BITRATE(h) ((h[2]) >> 4)
  76658. #define DRMP3_HDR_GET_SAMPLE_RATE(h) (((h[2]) >> 2) & 3)
  76659. #define DRMP3_HDR_GET_MY_SAMPLE_RATE(h) (DRMP3_HDR_GET_SAMPLE_RATE(h) + (((h[1] >> 3) & 1) + ((h[1] >> 4) & 1))*3)
  76660. #define DRMP3_HDR_IS_FRAME_576(h) ((h[1] & 14) == 2)
  76661. #define DRMP3_HDR_IS_LAYER_1(h) ((h[1] & 6) == 6)
  76662. #define DRMP3_BITS_DEQUANTIZER_OUT -1
  76663. #define DRMP3_MAX_SCF (255 + DRMP3_BITS_DEQUANTIZER_OUT*4 - 210)
  76664. #define DRMP3_MAX_SCFI ((DRMP3_MAX_SCF + 3) & ~3)
  76665. #define DRMP3_MIN(a, b) ((a) > (b) ? (b) : (a))
  76666. #define DRMP3_MAX(a, b) ((a) < (b) ? (b) : (a))
  76667. #if !defined(DR_MP3_NO_SIMD)
  76668. #if !defined(DR_MP3_ONLY_SIMD) && (defined(_M_X64) || defined(__x86_64__) || defined(__aarch64__) || defined(_M_ARM64))
  76669. #define DR_MP3_ONLY_SIMD
  76670. #endif
  76671. #if ((defined(_MSC_VER) && _MSC_VER >= 1400) && defined(_M_X64)) || ((defined(__i386) || defined(_M_IX86) || defined(__i386__) || defined(__x86_64__)) && ((defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)))
  76672. #if defined(_MSC_VER)
  76673. #include <intrin.h>
  76674. #endif
  76675. #include <emmintrin.h>
  76676. #define DRMP3_HAVE_SSE 1
  76677. #define DRMP3_HAVE_SIMD 1
  76678. #define DRMP3_VSTORE _mm_storeu_ps
  76679. #define DRMP3_VLD _mm_loadu_ps
  76680. #define DRMP3_VSET _mm_set1_ps
  76681. #define DRMP3_VADD _mm_add_ps
  76682. #define DRMP3_VSUB _mm_sub_ps
  76683. #define DRMP3_VMUL _mm_mul_ps
  76684. #define DRMP3_VMAC(a, x, y) _mm_add_ps(a, _mm_mul_ps(x, y))
  76685. #define DRMP3_VMSB(a, x, y) _mm_sub_ps(a, _mm_mul_ps(x, y))
  76686. #define DRMP3_VMUL_S(x, s) _mm_mul_ps(x, _mm_set1_ps(s))
  76687. #define DRMP3_VREV(x) _mm_shuffle_ps(x, x, _MM_SHUFFLE(0, 1, 2, 3))
  76688. typedef __m128 drmp3_f4;
  76689. #if defined(_MSC_VER) || defined(DR_MP3_ONLY_SIMD)
  76690. #define drmp3_cpuid __cpuid
  76691. #else
  76692. static __inline__ __attribute__((always_inline)) void drmp3_cpuid(int CPUInfo[], const int InfoType)
  76693. {
  76694. #if defined(__PIC__)
  76695. __asm__ __volatile__(
  76696. #if defined(__x86_64__)
  76697. "push %%rbx\n"
  76698. "cpuid\n"
  76699. "xchgl %%ebx, %1\n"
  76700. "pop %%rbx\n"
  76701. #else
  76702. "xchgl %%ebx, %1\n"
  76703. "cpuid\n"
  76704. "xchgl %%ebx, %1\n"
  76705. #endif
  76706. : "=a" (CPUInfo[0]), "=r" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3])
  76707. : "a" (InfoType));
  76708. #else
  76709. __asm__ __volatile__(
  76710. "cpuid"
  76711. : "=a" (CPUInfo[0]), "=b" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3])
  76712. : "a" (InfoType));
  76713. #endif
  76714. }
  76715. #endif
  76716. static int drmp3_have_simd(void)
  76717. {
  76718. #ifdef DR_MP3_ONLY_SIMD
  76719. return 1;
  76720. #else
  76721. static int g_have_simd;
  76722. int CPUInfo[4];
  76723. #ifdef MINIMP3_TEST
  76724. static int g_counter;
  76725. if (g_counter++ > 100)
  76726. return 0;
  76727. #endif
  76728. if (g_have_simd)
  76729. goto end;
  76730. drmp3_cpuid(CPUInfo, 0);
  76731. if (CPUInfo[0] > 0)
  76732. {
  76733. drmp3_cpuid(CPUInfo, 1);
  76734. g_have_simd = (CPUInfo[3] & (1 << 26)) + 1;
  76735. return g_have_simd - 1;
  76736. }
  76737. end:
  76738. return g_have_simd - 1;
  76739. #endif
  76740. }
  76741. #elif defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)
  76742. #include <arm_neon.h>
  76743. #define DRMP3_HAVE_SSE 0
  76744. #define DRMP3_HAVE_SIMD 1
  76745. #define DRMP3_VSTORE vst1q_f32
  76746. #define DRMP3_VLD vld1q_f32
  76747. #define DRMP3_VSET vmovq_n_f32
  76748. #define DRMP3_VADD vaddq_f32
  76749. #define DRMP3_VSUB vsubq_f32
  76750. #define DRMP3_VMUL vmulq_f32
  76751. #define DRMP3_VMAC(a, x, y) vmlaq_f32(a, x, y)
  76752. #define DRMP3_VMSB(a, x, y) vmlsq_f32(a, x, y)
  76753. #define DRMP3_VMUL_S(x, s) vmulq_f32(x, vmovq_n_f32(s))
  76754. #define DRMP3_VREV(x) vcombine_f32(vget_high_f32(vrev64q_f32(x)), vget_low_f32(vrev64q_f32(x)))
  76755. typedef float32x4_t drmp3_f4;
  76756. static int drmp3_have_simd(void)
  76757. {
  76758. return 1;
  76759. }
  76760. #else
  76761. #define DRMP3_HAVE_SSE 0
  76762. #define DRMP3_HAVE_SIMD 0
  76763. #ifdef DR_MP3_ONLY_SIMD
  76764. #error DR_MP3_ONLY_SIMD used, but SSE/NEON not enabled
  76765. #endif
  76766. #endif
  76767. #else
  76768. #define DRMP3_HAVE_SIMD 0
  76769. #endif
  76770. #if defined(__ARM_ARCH) && (__ARM_ARCH >= 6) && !defined(__aarch64__) && !defined(_M_ARM64)
  76771. #define DRMP3_HAVE_ARMV6 1
  76772. static __inline__ __attribute__((always_inline)) drmp3_int32 drmp3_clip_int16_arm(drmp3_int32 a)
  76773. {
  76774. drmp3_int32 x = 0;
  76775. __asm__ ("ssat %0, #16, %1" : "=r"(x) : "r"(a));
  76776. return x;
  76777. }
  76778. #else
  76779. #define DRMP3_HAVE_ARMV6 0
  76780. #endif
  76781. #ifndef DRMP3_ASSERT
  76782. #include <assert.h>
  76783. #define DRMP3_ASSERT(expression) assert(expression)
  76784. #endif
  76785. #ifndef DRMP3_COPY_MEMORY
  76786. #define DRMP3_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  76787. #endif
  76788. #ifndef DRMP3_MOVE_MEMORY
  76789. #define DRMP3_MOVE_MEMORY(dst, src, sz) memmove((dst), (src), (sz))
  76790. #endif
  76791. #ifndef DRMP3_ZERO_MEMORY
  76792. #define DRMP3_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  76793. #endif
  76794. #define DRMP3_ZERO_OBJECT(p) DRMP3_ZERO_MEMORY((p), sizeof(*(p)))
  76795. #ifndef DRMP3_MALLOC
  76796. #define DRMP3_MALLOC(sz) malloc((sz))
  76797. #endif
  76798. #ifndef DRMP3_REALLOC
  76799. #define DRMP3_REALLOC(p, sz) realloc((p), (sz))
  76800. #endif
  76801. #ifndef DRMP3_FREE
  76802. #define DRMP3_FREE(p) free((p))
  76803. #endif
  76804. typedef struct
  76805. {
  76806. const drmp3_uint8 *buf;
  76807. int pos, limit;
  76808. } drmp3_bs;
  76809. typedef struct
  76810. {
  76811. float scf[3*64];
  76812. drmp3_uint8 total_bands, stereo_bands, bitalloc[64], scfcod[64];
  76813. } drmp3_L12_scale_info;
  76814. typedef struct
  76815. {
  76816. drmp3_uint8 tab_offset, code_tab_width, band_count;
  76817. } drmp3_L12_subband_alloc;
  76818. typedef struct
  76819. {
  76820. const drmp3_uint8 *sfbtab;
  76821. drmp3_uint16 part_23_length, big_values, scalefac_compress;
  76822. drmp3_uint8 global_gain, block_type, mixed_block_flag, n_long_sfb, n_short_sfb;
  76823. drmp3_uint8 table_select[3], region_count[3], subblock_gain[3];
  76824. drmp3_uint8 preflag, scalefac_scale, count1_table, scfsi;
  76825. } drmp3_L3_gr_info;
  76826. typedef struct
  76827. {
  76828. drmp3_bs bs;
  76829. drmp3_uint8 maindata[DRMP3_MAX_BITRESERVOIR_BYTES + DRMP3_MAX_L3_FRAME_PAYLOAD_BYTES];
  76830. drmp3_L3_gr_info gr_info[4];
  76831. float grbuf[2][576], scf[40], syn[18 + 15][2*32];
  76832. drmp3_uint8 ist_pos[2][39];
  76833. } drmp3dec_scratch;
  76834. static void drmp3_bs_init(drmp3_bs *bs, const drmp3_uint8 *data, int bytes)
  76835. {
  76836. bs->buf = data;
  76837. bs->pos = 0;
  76838. bs->limit = bytes*8;
  76839. }
  76840. static drmp3_uint32 drmp3_bs_get_bits(drmp3_bs *bs, int n)
  76841. {
  76842. drmp3_uint32 next, cache = 0, s = bs->pos & 7;
  76843. int shl = n + s;
  76844. const drmp3_uint8 *p = bs->buf + (bs->pos >> 3);
  76845. if ((bs->pos += n) > bs->limit)
  76846. return 0;
  76847. next = *p++ & (255 >> s);
  76848. while ((shl -= 8) > 0)
  76849. {
  76850. cache |= next << shl;
  76851. next = *p++;
  76852. }
  76853. return cache | (next >> -shl);
  76854. }
  76855. static int drmp3_hdr_valid(const drmp3_uint8 *h)
  76856. {
  76857. return h[0] == 0xff &&
  76858. ((h[1] & 0xF0) == 0xf0 || (h[1] & 0xFE) == 0xe2) &&
  76859. (DRMP3_HDR_GET_LAYER(h) != 0) &&
  76860. (DRMP3_HDR_GET_BITRATE(h) != 15) &&
  76861. (DRMP3_HDR_GET_SAMPLE_RATE(h) != 3);
  76862. }
  76863. static int drmp3_hdr_compare(const drmp3_uint8 *h1, const drmp3_uint8 *h2)
  76864. {
  76865. return drmp3_hdr_valid(h2) &&
  76866. ((h1[1] ^ h2[1]) & 0xFE) == 0 &&
  76867. ((h1[2] ^ h2[2]) & 0x0C) == 0 &&
  76868. !(DRMP3_HDR_IS_FREE_FORMAT(h1) ^ DRMP3_HDR_IS_FREE_FORMAT(h2));
  76869. }
  76870. static unsigned drmp3_hdr_bitrate_kbps(const drmp3_uint8 *h)
  76871. {
  76872. static const drmp3_uint8 halfrate[2][3][15] = {
  76873. { { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 }, { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 }, { 0,16,24,28,32,40,48,56,64,72,80,88,96,112,128 } },
  76874. { { 0,16,20,24,28,32,40,48,56,64,80,96,112,128,160 }, { 0,16,24,28,32,40,48,56,64,80,96,112,128,160,192 }, { 0,16,32,48,64,80,96,112,128,144,160,176,192,208,224 } },
  76875. };
  76876. return 2*halfrate[!!DRMP3_HDR_TEST_MPEG1(h)][DRMP3_HDR_GET_LAYER(h) - 1][DRMP3_HDR_GET_BITRATE(h)];
  76877. }
  76878. static unsigned drmp3_hdr_sample_rate_hz(const drmp3_uint8 *h)
  76879. {
  76880. static const unsigned g_hz[3] = { 44100, 48000, 32000 };
  76881. return g_hz[DRMP3_HDR_GET_SAMPLE_RATE(h)] >> (int)!DRMP3_HDR_TEST_MPEG1(h) >> (int)!DRMP3_HDR_TEST_NOT_MPEG25(h);
  76882. }
  76883. static unsigned drmp3_hdr_frame_samples(const drmp3_uint8 *h)
  76884. {
  76885. return DRMP3_HDR_IS_LAYER_1(h) ? 384 : (1152 >> (int)DRMP3_HDR_IS_FRAME_576(h));
  76886. }
  76887. static int drmp3_hdr_frame_bytes(const drmp3_uint8 *h, int free_format_size)
  76888. {
  76889. int frame_bytes = drmp3_hdr_frame_samples(h)*drmp3_hdr_bitrate_kbps(h)*125/drmp3_hdr_sample_rate_hz(h);
  76890. if (DRMP3_HDR_IS_LAYER_1(h))
  76891. {
  76892. frame_bytes &= ~3;
  76893. }
  76894. return frame_bytes ? frame_bytes : free_format_size;
  76895. }
  76896. static int drmp3_hdr_padding(const drmp3_uint8 *h)
  76897. {
  76898. return DRMP3_HDR_TEST_PADDING(h) ? (DRMP3_HDR_IS_LAYER_1(h) ? 4 : 1) : 0;
  76899. }
  76900. #ifndef DR_MP3_ONLY_MP3
  76901. static const drmp3_L12_subband_alloc *drmp3_L12_subband_alloc_table(const drmp3_uint8 *hdr, drmp3_L12_scale_info *sci)
  76902. {
  76903. const drmp3_L12_subband_alloc *alloc;
  76904. int mode = DRMP3_HDR_GET_STEREO_MODE(hdr);
  76905. int nbands, stereo_bands = (mode == DRMP3_MODE_MONO) ? 0 : (mode == DRMP3_MODE_JOINT_STEREO) ? (DRMP3_HDR_GET_STEREO_MODE_EXT(hdr) << 2) + 4 : 32;
  76906. if (DRMP3_HDR_IS_LAYER_1(hdr))
  76907. {
  76908. static const drmp3_L12_subband_alloc g_alloc_L1[] = { { 76, 4, 32 } };
  76909. alloc = g_alloc_L1;
  76910. nbands = 32;
  76911. } else if (!DRMP3_HDR_TEST_MPEG1(hdr))
  76912. {
  76913. static const drmp3_L12_subband_alloc g_alloc_L2M2[] = { { 60, 4, 4 }, { 44, 3, 7 }, { 44, 2, 19 } };
  76914. alloc = g_alloc_L2M2;
  76915. nbands = 30;
  76916. } else
  76917. {
  76918. static const drmp3_L12_subband_alloc g_alloc_L2M1[] = { { 0, 4, 3 }, { 16, 4, 8 }, { 32, 3, 12 }, { 40, 2, 7 } };
  76919. int sample_rate_idx = DRMP3_HDR_GET_SAMPLE_RATE(hdr);
  76920. unsigned kbps = drmp3_hdr_bitrate_kbps(hdr) >> (int)(mode != DRMP3_MODE_MONO);
  76921. if (!kbps)
  76922. {
  76923. kbps = 192;
  76924. }
  76925. alloc = g_alloc_L2M1;
  76926. nbands = 27;
  76927. if (kbps < 56)
  76928. {
  76929. static const drmp3_L12_subband_alloc g_alloc_L2M1_lowrate[] = { { 44, 4, 2 }, { 44, 3, 10 } };
  76930. alloc = g_alloc_L2M1_lowrate;
  76931. nbands = sample_rate_idx == 2 ? 12 : 8;
  76932. } else if (kbps >= 96 && sample_rate_idx != 1)
  76933. {
  76934. nbands = 30;
  76935. }
  76936. }
  76937. sci->total_bands = (drmp3_uint8)nbands;
  76938. sci->stereo_bands = (drmp3_uint8)DRMP3_MIN(stereo_bands, nbands);
  76939. return alloc;
  76940. }
  76941. static void drmp3_L12_read_scalefactors(drmp3_bs *bs, drmp3_uint8 *pba, drmp3_uint8 *scfcod, int bands, float *scf)
  76942. {
  76943. static const float g_deq_L12[18*3] = {
  76944. #define DRMP3_DQ(x) 9.53674316e-07f/x, 7.56931807e-07f/x, 6.00777173e-07f/x
  76945. DRMP3_DQ(3),DRMP3_DQ(7),DRMP3_DQ(15),DRMP3_DQ(31),DRMP3_DQ(63),DRMP3_DQ(127),DRMP3_DQ(255),DRMP3_DQ(511),DRMP3_DQ(1023),DRMP3_DQ(2047),DRMP3_DQ(4095),DRMP3_DQ(8191),DRMP3_DQ(16383),DRMP3_DQ(32767),DRMP3_DQ(65535),DRMP3_DQ(3),DRMP3_DQ(5),DRMP3_DQ(9)
  76946. };
  76947. int i, m;
  76948. for (i = 0; i < bands; i++)
  76949. {
  76950. float s = 0;
  76951. int ba = *pba++;
  76952. int mask = ba ? 4 + ((19 >> scfcod[i]) & 3) : 0;
  76953. for (m = 4; m; m >>= 1)
  76954. {
  76955. if (mask & m)
  76956. {
  76957. int b = drmp3_bs_get_bits(bs, 6);
  76958. s = g_deq_L12[ba*3 - 6 + b % 3]*(int)(1 << 21 >> b/3);
  76959. }
  76960. *scf++ = s;
  76961. }
  76962. }
  76963. }
  76964. static void drmp3_L12_read_scale_info(const drmp3_uint8 *hdr, drmp3_bs *bs, drmp3_L12_scale_info *sci)
  76965. {
  76966. static const drmp3_uint8 g_bitalloc_code_tab[] = {
  76967. 0,17, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16,
  76968. 0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,16,
  76969. 0,17,18, 3,19,4,5,16,
  76970. 0,17,18,16,
  76971. 0,17,18,19, 4,5,6, 7,8, 9,10,11,12,13,14,15,
  76972. 0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,14,
  76973. 0, 2, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16
  76974. };
  76975. const drmp3_L12_subband_alloc *subband_alloc = drmp3_L12_subband_alloc_table(hdr, sci);
  76976. int i, k = 0, ba_bits = 0;
  76977. const drmp3_uint8 *ba_code_tab = g_bitalloc_code_tab;
  76978. for (i = 0; i < sci->total_bands; i++)
  76979. {
  76980. drmp3_uint8 ba;
  76981. if (i == k)
  76982. {
  76983. k += subband_alloc->band_count;
  76984. ba_bits = subband_alloc->code_tab_width;
  76985. ba_code_tab = g_bitalloc_code_tab + subband_alloc->tab_offset;
  76986. subband_alloc++;
  76987. }
  76988. ba = ba_code_tab[drmp3_bs_get_bits(bs, ba_bits)];
  76989. sci->bitalloc[2*i] = ba;
  76990. if (i < sci->stereo_bands)
  76991. {
  76992. ba = ba_code_tab[drmp3_bs_get_bits(bs, ba_bits)];
  76993. }
  76994. sci->bitalloc[2*i + 1] = sci->stereo_bands ? ba : 0;
  76995. }
  76996. for (i = 0; i < 2*sci->total_bands; i++)
  76997. {
  76998. sci->scfcod[i] = (drmp3_uint8)(sci->bitalloc[i] ? DRMP3_HDR_IS_LAYER_1(hdr) ? 2 : drmp3_bs_get_bits(bs, 2) : 6);
  76999. }
  77000. drmp3_L12_read_scalefactors(bs, sci->bitalloc, sci->scfcod, sci->total_bands*2, sci->scf);
  77001. for (i = sci->stereo_bands; i < sci->total_bands; i++)
  77002. {
  77003. sci->bitalloc[2*i + 1] = 0;
  77004. }
  77005. }
  77006. static int drmp3_L12_dequantize_granule(float *grbuf, drmp3_bs *bs, drmp3_L12_scale_info *sci, int group_size)
  77007. {
  77008. int i, j, k, choff = 576;
  77009. for (j = 0; j < 4; j++)
  77010. {
  77011. float *dst = grbuf + group_size*j;
  77012. for (i = 0; i < 2*sci->total_bands; i++)
  77013. {
  77014. int ba = sci->bitalloc[i];
  77015. if (ba != 0)
  77016. {
  77017. if (ba < 17)
  77018. {
  77019. int half = (1 << (ba - 1)) - 1;
  77020. for (k = 0; k < group_size; k++)
  77021. {
  77022. dst[k] = (float)((int)drmp3_bs_get_bits(bs, ba) - half);
  77023. }
  77024. } else
  77025. {
  77026. unsigned mod = (2 << (ba - 17)) + 1;
  77027. unsigned code = drmp3_bs_get_bits(bs, mod + 2 - (mod >> 3));
  77028. for (k = 0; k < group_size; k++, code /= mod)
  77029. {
  77030. dst[k] = (float)((int)(code % mod - mod/2));
  77031. }
  77032. }
  77033. }
  77034. dst += choff;
  77035. choff = 18 - choff;
  77036. }
  77037. }
  77038. return group_size*4;
  77039. }
  77040. static void drmp3_L12_apply_scf_384(drmp3_L12_scale_info *sci, const float *scf, float *dst)
  77041. {
  77042. int i, k;
  77043. DRMP3_COPY_MEMORY(dst + 576 + sci->stereo_bands*18, dst + sci->stereo_bands*18, (sci->total_bands - sci->stereo_bands)*18*sizeof(float));
  77044. for (i = 0; i < sci->total_bands; i++, dst += 18, scf += 6)
  77045. {
  77046. for (k = 0; k < 12; k++)
  77047. {
  77048. dst[k + 0] *= scf[0];
  77049. dst[k + 576] *= scf[3];
  77050. }
  77051. }
  77052. }
  77053. #endif
  77054. static int drmp3_L3_read_side_info(drmp3_bs *bs, drmp3_L3_gr_info *gr, const drmp3_uint8 *hdr)
  77055. {
  77056. static const drmp3_uint8 g_scf_long[8][23] = {
  77057. { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 },
  77058. { 12,12,12,12,12,12,16,20,24,28,32,40,48,56,64,76,90,2,2,2,2,2,0 },
  77059. { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 },
  77060. { 6,6,6,6,6,6,8,10,12,14,16,18,22,26,32,38,46,54,62,70,76,36,0 },
  77061. { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 },
  77062. { 4,4,4,4,4,4,6,6,8,8,10,12,16,20,24,28,34,42,50,54,76,158,0 },
  77063. { 4,4,4,4,4,4,6,6,6,8,10,12,16,18,22,28,34,40,46,54,54,192,0 },
  77064. { 4,4,4,4,4,4,6,6,8,10,12,16,20,24,30,38,46,56,68,84,102,26,0 }
  77065. };
  77066. static const drmp3_uint8 g_scf_short[8][40] = {
  77067. { 4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,30,30,30,40,40,40,18,18,18,0 },
  77068. { 8,8,8,8,8,8,8,8,8,12,12,12,16,16,16,20,20,20,24,24,24,28,28,28,36,36,36,2,2,2,2,2,2,2,2,2,26,26,26,0 },
  77069. { 4,4,4,4,4,4,4,4,4,6,6,6,6,6,6,8,8,8,10,10,10,14,14,14,18,18,18,26,26,26,32,32,32,42,42,42,18,18,18,0 },
  77070. { 4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,32,32,32,44,44,44,12,12,12,0 },
  77071. { 4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,30,30,30,40,40,40,18,18,18,0 },
  77072. { 4,4,4,4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,22,22,22,30,30,30,56,56,56,0 },
  77073. { 4,4,4,4,4,4,4,4,4,4,4,4,6,6,6,6,6,6,10,10,10,12,12,12,14,14,14,16,16,16,20,20,20,26,26,26,66,66,66,0 },
  77074. { 4,4,4,4,4,4,4,4,4,4,4,4,6,6,6,8,8,8,12,12,12,16,16,16,20,20,20,26,26,26,34,34,34,42,42,42,12,12,12,0 }
  77075. };
  77076. static const drmp3_uint8 g_scf_mixed[8][40] = {
  77077. { 6,6,6,6,6,6,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,30,30,30,40,40,40,18,18,18,0 },
  77078. { 12,12,12,4,4,4,8,8,8,12,12,12,16,16,16,20,20,20,24,24,24,28,28,28,36,36,36,2,2,2,2,2,2,2,2,2,26,26,26,0 },
  77079. { 6,6,6,6,6,6,6,6,6,6,6,6,8,8,8,10,10,10,14,14,14,18,18,18,26,26,26,32,32,32,42,42,42,18,18,18,0 },
  77080. { 6,6,6,6,6,6,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,32,32,32,44,44,44,12,12,12,0 },
  77081. { 6,6,6,6,6,6,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,24,24,24,30,30,30,40,40,40,18,18,18,0 },
  77082. { 4,4,4,4,4,4,6,6,4,4,4,6,6,6,8,8,8,10,10,10,12,12,12,14,14,14,18,18,18,22,22,22,30,30,30,56,56,56,0 },
  77083. { 4,4,4,4,4,4,6,6,4,4,4,6,6,6,6,6,6,10,10,10,12,12,12,14,14,14,16,16,16,20,20,20,26,26,26,66,66,66,0 },
  77084. { 4,4,4,4,4,4,6,6,4,4,4,6,6,6,8,8,8,12,12,12,16,16,16,20,20,20,26,26,26,34,34,34,42,42,42,12,12,12,0 }
  77085. };
  77086. unsigned tables, scfsi = 0;
  77087. int main_data_begin, part_23_sum = 0;
  77088. int gr_count = DRMP3_HDR_IS_MONO(hdr) ? 1 : 2;
  77089. int sr_idx = DRMP3_HDR_GET_MY_SAMPLE_RATE(hdr); sr_idx -= (sr_idx != 0);
  77090. if (DRMP3_HDR_TEST_MPEG1(hdr))
  77091. {
  77092. gr_count *= 2;
  77093. main_data_begin = drmp3_bs_get_bits(bs, 9);
  77094. scfsi = drmp3_bs_get_bits(bs, 7 + gr_count);
  77095. } else
  77096. {
  77097. main_data_begin = drmp3_bs_get_bits(bs, 8 + gr_count) >> gr_count;
  77098. }
  77099. do
  77100. {
  77101. if (DRMP3_HDR_IS_MONO(hdr))
  77102. {
  77103. scfsi <<= 4;
  77104. }
  77105. gr->part_23_length = (drmp3_uint16)drmp3_bs_get_bits(bs, 12);
  77106. part_23_sum += gr->part_23_length;
  77107. gr->big_values = (drmp3_uint16)drmp3_bs_get_bits(bs, 9);
  77108. if (gr->big_values > 288)
  77109. {
  77110. return -1;
  77111. }
  77112. gr->global_gain = (drmp3_uint8)drmp3_bs_get_bits(bs, 8);
  77113. gr->scalefac_compress = (drmp3_uint16)drmp3_bs_get_bits(bs, DRMP3_HDR_TEST_MPEG1(hdr) ? 4 : 9);
  77114. gr->sfbtab = g_scf_long[sr_idx];
  77115. gr->n_long_sfb = 22;
  77116. gr->n_short_sfb = 0;
  77117. if (drmp3_bs_get_bits(bs, 1))
  77118. {
  77119. gr->block_type = (drmp3_uint8)drmp3_bs_get_bits(bs, 2);
  77120. if (!gr->block_type)
  77121. {
  77122. return -1;
  77123. }
  77124. gr->mixed_block_flag = (drmp3_uint8)drmp3_bs_get_bits(bs, 1);
  77125. gr->region_count[0] = 7;
  77126. gr->region_count[1] = 255;
  77127. if (gr->block_type == DRMP3_SHORT_BLOCK_TYPE)
  77128. {
  77129. scfsi &= 0x0F0F;
  77130. if (!gr->mixed_block_flag)
  77131. {
  77132. gr->region_count[0] = 8;
  77133. gr->sfbtab = g_scf_short[sr_idx];
  77134. gr->n_long_sfb = 0;
  77135. gr->n_short_sfb = 39;
  77136. } else
  77137. {
  77138. gr->sfbtab = g_scf_mixed[sr_idx];
  77139. gr->n_long_sfb = DRMP3_HDR_TEST_MPEG1(hdr) ? 8 : 6;
  77140. gr->n_short_sfb = 30;
  77141. }
  77142. }
  77143. tables = drmp3_bs_get_bits(bs, 10);
  77144. tables <<= 5;
  77145. gr->subblock_gain[0] = (drmp3_uint8)drmp3_bs_get_bits(bs, 3);
  77146. gr->subblock_gain[1] = (drmp3_uint8)drmp3_bs_get_bits(bs, 3);
  77147. gr->subblock_gain[2] = (drmp3_uint8)drmp3_bs_get_bits(bs, 3);
  77148. } else
  77149. {
  77150. gr->block_type = 0;
  77151. gr->mixed_block_flag = 0;
  77152. tables = drmp3_bs_get_bits(bs, 15);
  77153. gr->region_count[0] = (drmp3_uint8)drmp3_bs_get_bits(bs, 4);
  77154. gr->region_count[1] = (drmp3_uint8)drmp3_bs_get_bits(bs, 3);
  77155. gr->region_count[2] = 255;
  77156. }
  77157. gr->table_select[0] = (drmp3_uint8)(tables >> 10);
  77158. gr->table_select[1] = (drmp3_uint8)((tables >> 5) & 31);
  77159. gr->table_select[2] = (drmp3_uint8)((tables) & 31);
  77160. gr->preflag = (drmp3_uint8)(DRMP3_HDR_TEST_MPEG1(hdr) ? drmp3_bs_get_bits(bs, 1) : (gr->scalefac_compress >= 500));
  77161. gr->scalefac_scale = (drmp3_uint8)drmp3_bs_get_bits(bs, 1);
  77162. gr->count1_table = (drmp3_uint8)drmp3_bs_get_bits(bs, 1);
  77163. gr->scfsi = (drmp3_uint8)((scfsi >> 12) & 15);
  77164. scfsi <<= 4;
  77165. gr++;
  77166. } while(--gr_count);
  77167. if (part_23_sum + bs->pos > bs->limit + main_data_begin*8)
  77168. {
  77169. return -1;
  77170. }
  77171. return main_data_begin;
  77172. }
  77173. static void drmp3_L3_read_scalefactors(drmp3_uint8 *scf, drmp3_uint8 *ist_pos, const drmp3_uint8 *scf_size, const drmp3_uint8 *scf_count, drmp3_bs *bitbuf, int scfsi)
  77174. {
  77175. int i, k;
  77176. for (i = 0; i < 4 && scf_count[i]; i++, scfsi *= 2)
  77177. {
  77178. int cnt = scf_count[i];
  77179. if (scfsi & 8)
  77180. {
  77181. DRMP3_COPY_MEMORY(scf, ist_pos, cnt);
  77182. } else
  77183. {
  77184. int bits = scf_size[i];
  77185. if (!bits)
  77186. {
  77187. DRMP3_ZERO_MEMORY(scf, cnt);
  77188. DRMP3_ZERO_MEMORY(ist_pos, cnt);
  77189. } else
  77190. {
  77191. int max_scf = (scfsi < 0) ? (1 << bits) - 1 : -1;
  77192. for (k = 0; k < cnt; k++)
  77193. {
  77194. int s = drmp3_bs_get_bits(bitbuf, bits);
  77195. ist_pos[k] = (drmp3_uint8)(s == max_scf ? -1 : s);
  77196. scf[k] = (drmp3_uint8)s;
  77197. }
  77198. }
  77199. }
  77200. ist_pos += cnt;
  77201. scf += cnt;
  77202. }
  77203. scf[0] = scf[1] = scf[2] = 0;
  77204. }
  77205. static float drmp3_L3_ldexp_q2(float y, int exp_q2)
  77206. {
  77207. static const float g_expfrac[4] = { 9.31322575e-10f,7.83145814e-10f,6.58544508e-10f,5.53767716e-10f };
  77208. int e;
  77209. do
  77210. {
  77211. e = DRMP3_MIN(30*4, exp_q2);
  77212. y *= g_expfrac[e & 3]*(1 << 30 >> (e >> 2));
  77213. } while ((exp_q2 -= e) > 0);
  77214. return y;
  77215. }
  77216. static void drmp3_L3_decode_scalefactors(const drmp3_uint8 *hdr, drmp3_uint8 *ist_pos, drmp3_bs *bs, const drmp3_L3_gr_info *gr, float *scf, int ch)
  77217. {
  77218. static const drmp3_uint8 g_scf_partitions[3][28] = {
  77219. { 6,5,5, 5,6,5,5,5,6,5, 7,3,11,10,0,0, 7, 7, 7,0, 6, 6,6,3, 8, 8,5,0 },
  77220. { 8,9,6,12,6,9,9,9,6,9,12,6,15,18,0,0, 6,15,12,0, 6,12,9,6, 6,18,9,0 },
  77221. { 9,9,6,12,9,9,9,9,9,9,12,6,18,18,0,0,12,12,12,0,12, 9,9,6,15,12,9,0 }
  77222. };
  77223. const drmp3_uint8 *scf_partition = g_scf_partitions[!!gr->n_short_sfb + !gr->n_long_sfb];
  77224. drmp3_uint8 scf_size[4], iscf[40];
  77225. int i, scf_shift = gr->scalefac_scale + 1, gain_exp, scfsi = gr->scfsi;
  77226. float gain;
  77227. if (DRMP3_HDR_TEST_MPEG1(hdr))
  77228. {
  77229. static const drmp3_uint8 g_scfc_decode[16] = { 0,1,2,3, 12,5,6,7, 9,10,11,13, 14,15,18,19 };
  77230. int part = g_scfc_decode[gr->scalefac_compress];
  77231. scf_size[1] = scf_size[0] = (drmp3_uint8)(part >> 2);
  77232. scf_size[3] = scf_size[2] = (drmp3_uint8)(part & 3);
  77233. } else
  77234. {
  77235. static const drmp3_uint8 g_mod[6*4] = { 5,5,4,4,5,5,4,1,4,3,1,1,5,6,6,1,4,4,4,1,4,3,1,1 };
  77236. int k, modprod, sfc, ist = DRMP3_HDR_TEST_I_STEREO(hdr) && ch;
  77237. sfc = gr->scalefac_compress >> ist;
  77238. for (k = ist*3*4; sfc >= 0; sfc -= modprod, k += 4)
  77239. {
  77240. for (modprod = 1, i = 3; i >= 0; i--)
  77241. {
  77242. scf_size[i] = (drmp3_uint8)(sfc / modprod % g_mod[k + i]);
  77243. modprod *= g_mod[k + i];
  77244. }
  77245. }
  77246. scf_partition += k;
  77247. scfsi = -16;
  77248. }
  77249. drmp3_L3_read_scalefactors(iscf, ist_pos, scf_size, scf_partition, bs, scfsi);
  77250. if (gr->n_short_sfb)
  77251. {
  77252. int sh = 3 - scf_shift;
  77253. for (i = 0; i < gr->n_short_sfb; i += 3)
  77254. {
  77255. iscf[gr->n_long_sfb + i + 0] = (drmp3_uint8)(iscf[gr->n_long_sfb + i + 0] + (gr->subblock_gain[0] << sh));
  77256. iscf[gr->n_long_sfb + i + 1] = (drmp3_uint8)(iscf[gr->n_long_sfb + i + 1] + (gr->subblock_gain[1] << sh));
  77257. iscf[gr->n_long_sfb + i + 2] = (drmp3_uint8)(iscf[gr->n_long_sfb + i + 2] + (gr->subblock_gain[2] << sh));
  77258. }
  77259. } else if (gr->preflag)
  77260. {
  77261. static const drmp3_uint8 g_preamp[10] = { 1,1,1,1,2,2,3,3,3,2 };
  77262. for (i = 0; i < 10; i++)
  77263. {
  77264. iscf[11 + i] = (drmp3_uint8)(iscf[11 + i] + g_preamp[i]);
  77265. }
  77266. }
  77267. gain_exp = gr->global_gain + DRMP3_BITS_DEQUANTIZER_OUT*4 - 210 - (DRMP3_HDR_IS_MS_STEREO(hdr) ? 2 : 0);
  77268. gain = drmp3_L3_ldexp_q2(1 << (DRMP3_MAX_SCFI/4), DRMP3_MAX_SCFI - gain_exp);
  77269. for (i = 0; i < (int)(gr->n_long_sfb + gr->n_short_sfb); i++)
  77270. {
  77271. scf[i] = drmp3_L3_ldexp_q2(gain, iscf[i] << scf_shift);
  77272. }
  77273. }
  77274. static const float g_drmp3_pow43[129 + 16] = {
  77275. 0,-1,-2.519842f,-4.326749f,-6.349604f,-8.549880f,-10.902724f,-13.390518f,-16.000000f,-18.720754f,-21.544347f,-24.463781f,-27.473142f,-30.567351f,-33.741992f,-36.993181f,
  77276. 0,1,2.519842f,4.326749f,6.349604f,8.549880f,10.902724f,13.390518f,16.000000f,18.720754f,21.544347f,24.463781f,27.473142f,30.567351f,33.741992f,36.993181f,40.317474f,43.711787f,47.173345f,50.699631f,54.288352f,57.937408f,61.644865f,65.408941f,69.227979f,73.100443f,77.024898f,81.000000f,85.024491f,89.097188f,93.216975f,97.382800f,101.593667f,105.848633f,110.146801f,114.487321f,118.869381f,123.292209f,127.755065f,132.257246f,136.798076f,141.376907f,145.993119f,150.646117f,155.335327f,160.060199f,164.820202f,169.614826f,174.443577f,179.305980f,184.201575f,189.129918f,194.090580f,199.083145f,204.107210f,209.162385f,214.248292f,219.364564f,224.510845f,229.686789f,234.892058f,240.126328f,245.389280f,250.680604f,256.000000f,261.347174f,266.721841f,272.123723f,277.552547f,283.008049f,288.489971f,293.998060f,299.532071f,305.091761f,310.676898f,316.287249f,321.922592f,327.582707f,333.267377f,338.976394f,344.709550f,350.466646f,356.247482f,362.051866f,367.879608f,373.730522f,379.604427f,385.501143f,391.420496f,397.362314f,403.326427f,409.312672f,415.320884f,421.350905f,427.402579f,433.475750f,439.570269f,445.685987f,451.822757f,457.980436f,464.158883f,470.357960f,476.577530f,482.817459f,489.077615f,495.357868f,501.658090f,507.978156f,514.317941f,520.677324f,527.056184f,533.454404f,539.871867f,546.308458f,552.764065f,559.238575f,565.731879f,572.243870f,578.774440f,585.323483f,591.890898f,598.476581f,605.080431f,611.702349f,618.342238f,625.000000f,631.675540f,638.368763f,645.079578f
  77277. };
  77278. static float drmp3_L3_pow_43(int x)
  77279. {
  77280. float frac;
  77281. int sign, mult = 256;
  77282. if (x < 129)
  77283. {
  77284. return g_drmp3_pow43[16 + x];
  77285. }
  77286. if (x < 1024)
  77287. {
  77288. mult = 16;
  77289. x <<= 3;
  77290. }
  77291. sign = 2*x & 64;
  77292. frac = (float)((x & 63) - sign) / ((x & ~63) + sign);
  77293. return g_drmp3_pow43[16 + ((x + sign) >> 6)]*(1.f + frac*((4.f/3) + frac*(2.f/9)))*mult;
  77294. }
  77295. static void drmp3_L3_huffman(float *dst, drmp3_bs *bs, const drmp3_L3_gr_info *gr_info, const float *scf, int layer3gr_limit)
  77296. {
  77297. static const drmp3_int16 tabs[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  77298. 785,785,785,785,784,784,784,784,513,513,513,513,513,513,513,513,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,
  77299. -255,1313,1298,1282,785,785,785,785,784,784,784,784,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,290,288,
  77300. -255,1313,1298,1282,769,769,769,769,529,529,529,529,529,529,529,529,528,528,528,528,528,528,528,528,512,512,512,512,512,512,512,512,290,288,
  77301. -253,-318,-351,-367,785,785,785,785,784,784,784,784,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,819,818,547,547,275,275,275,275,561,560,515,546,289,274,288,258,
  77302. -254,-287,1329,1299,1314,1312,1057,1057,1042,1042,1026,1026,784,784,784,784,529,529,529,529,529,529,529,529,769,769,769,769,768,768,768,768,563,560,306,306,291,259,
  77303. -252,-413,-477,-542,1298,-575,1041,1041,784,784,784,784,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,-383,-399,1107,1092,1106,1061,849,849,789,789,1104,1091,773,773,1076,1075,341,340,325,309,834,804,577,577,532,532,516,516,832,818,803,816,561,561,531,531,515,546,289,289,288,258,
  77304. -252,-429,-493,-559,1057,1057,1042,1042,529,529,529,529,529,529,529,529,784,784,784,784,769,769,769,769,512,512,512,512,512,512,512,512,-382,1077,-415,1106,1061,1104,849,849,789,789,1091,1076,1029,1075,834,834,597,581,340,340,339,324,804,833,532,532,832,772,818,803,817,787,816,771,290,290,290,290,288,258,
  77305. -253,-349,-414,-447,-463,1329,1299,-479,1314,1312,1057,1057,1042,1042,1026,1026,785,785,785,785,784,784,784,784,769,769,769,769,768,768,768,768,-319,851,821,-335,836,850,805,849,341,340,325,336,533,533,579,579,564,564,773,832,578,548,563,516,321,276,306,291,304,259,
  77306. -251,-572,-733,-830,-863,-879,1041,1041,784,784,784,784,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,-511,-527,-543,1396,1351,1381,1366,1395,1335,1380,-559,1334,1138,1138,1063,1063,1350,1392,1031,1031,1062,1062,1364,1363,1120,1120,1333,1348,881,881,881,881,375,374,359,373,343,358,341,325,791,791,1123,1122,-703,1105,1045,-719,865,865,790,790,774,774,1104,1029,338,293,323,308,-799,-815,833,788,772,818,803,816,322,292,307,320,561,531,515,546,289,274,288,258,
  77307. -251,-525,-605,-685,-765,-831,-846,1298,1057,1057,1312,1282,785,785,785,785,784,784,784,784,769,769,769,769,512,512,512,512,512,512,512,512,1399,1398,1383,1367,1382,1396,1351,-511,1381,1366,1139,1139,1079,1079,1124,1124,1364,1349,1363,1333,882,882,882,882,807,807,807,807,1094,1094,1136,1136,373,341,535,535,881,775,867,822,774,-591,324,338,-671,849,550,550,866,864,609,609,293,336,534,534,789,835,773,-751,834,804,308,307,833,788,832,772,562,562,547,547,305,275,560,515,290,290,
  77308. -252,-397,-477,-557,-622,-653,-719,-735,-750,1329,1299,1314,1057,1057,1042,1042,1312,1282,1024,1024,785,785,785,785,784,784,784,784,769,769,769,769,-383,1127,1141,1111,1126,1140,1095,1110,869,869,883,883,1079,1109,882,882,375,374,807,868,838,881,791,-463,867,822,368,263,852,837,836,-543,610,610,550,550,352,336,534,534,865,774,851,821,850,805,593,533,579,564,773,832,578,578,548,548,577,577,307,276,306,291,516,560,259,259,
  77309. -250,-2107,-2507,-2764,-2909,-2974,-3007,-3023,1041,1041,1040,1040,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,-767,-1052,-1213,-1277,-1358,-1405,-1469,-1535,-1550,-1582,-1614,-1647,-1662,-1694,-1726,-1759,-1774,-1807,-1822,-1854,-1886,1565,-1919,-1935,-1951,-1967,1731,1730,1580,1717,-1983,1729,1564,-1999,1548,-2015,-2031,1715,1595,-2047,1714,-2063,1610,-2079,1609,-2095,1323,1323,1457,1457,1307,1307,1712,1547,1641,1700,1699,1594,1685,1625,1442,1442,1322,1322,-780,-973,-910,1279,1278,1277,1262,1276,1261,1275,1215,1260,1229,-959,974,974,989,989,-943,735,478,478,495,463,506,414,-1039,1003,958,1017,927,942,987,957,431,476,1272,1167,1228,-1183,1256,-1199,895,895,941,941,1242,1227,1212,1135,1014,1014,490,489,503,487,910,1013,985,925,863,894,970,955,1012,847,-1343,831,755,755,984,909,428,366,754,559,-1391,752,486,457,924,997,698,698,983,893,740,740,908,877,739,739,667,667,953,938,497,287,271,271,683,606,590,712,726,574,302,302,738,736,481,286,526,725,605,711,636,724,696,651,589,681,666,710,364,467,573,695,466,466,301,465,379,379,709,604,665,679,316,316,634,633,436,436,464,269,424,394,452,332,438,363,347,408,393,448,331,422,362,407,392,421,346,406,391,376,375,359,1441,1306,-2367,1290,-2383,1337,-2399,-2415,1426,1321,-2431,1411,1336,-2447,-2463,-2479,1169,1169,1049,1049,1424,1289,1412,1352,1319,-2495,1154,1154,1064,1064,1153,1153,416,390,360,404,403,389,344,374,373,343,358,372,327,357,342,311,356,326,1395,1394,1137,1137,1047,1047,1365,1392,1287,1379,1334,1364,1349,1378,1318,1363,792,792,792,792,1152,1152,1032,1032,1121,1121,1046,1046,1120,1120,1030,1030,-2895,1106,1061,1104,849,849,789,789,1091,1076,1029,1090,1060,1075,833,833,309,324,532,532,832,772,818,803,561,561,531,560,515,546,289,274,288,258,
  77310. -250,-1179,-1579,-1836,-1996,-2124,-2253,-2333,-2413,-2477,-2542,-2574,-2607,-2622,-2655,1314,1313,1298,1312,1282,785,785,785,785,1040,1040,1025,1025,768,768,768,768,-766,-798,-830,-862,-895,-911,-927,-943,-959,-975,-991,-1007,-1023,-1039,-1055,-1070,1724,1647,-1103,-1119,1631,1767,1662,1738,1708,1723,-1135,1780,1615,1779,1599,1677,1646,1778,1583,-1151,1777,1567,1737,1692,1765,1722,1707,1630,1751,1661,1764,1614,1736,1676,1763,1750,1645,1598,1721,1691,1762,1706,1582,1761,1566,-1167,1749,1629,767,766,751,765,494,494,735,764,719,749,734,763,447,447,748,718,477,506,431,491,446,476,461,505,415,430,475,445,504,399,460,489,414,503,383,474,429,459,502,502,746,752,488,398,501,473,413,472,486,271,480,270,-1439,-1455,1357,-1471,-1487,-1503,1341,1325,-1519,1489,1463,1403,1309,-1535,1372,1448,1418,1476,1356,1462,1387,-1551,1475,1340,1447,1402,1386,-1567,1068,1068,1474,1461,455,380,468,440,395,425,410,454,364,467,466,464,453,269,409,448,268,432,1371,1473,1432,1417,1308,1460,1355,1446,1459,1431,1083,1083,1401,1416,1458,1445,1067,1067,1370,1457,1051,1051,1291,1430,1385,1444,1354,1415,1400,1443,1082,1082,1173,1113,1186,1066,1185,1050,-1967,1158,1128,1172,1097,1171,1081,-1983,1157,1112,416,266,375,400,1170,1142,1127,1065,793,793,1169,1033,1156,1096,1141,1111,1155,1080,1126,1140,898,898,808,808,897,897,792,792,1095,1152,1032,1125,1110,1139,1079,1124,882,807,838,881,853,791,-2319,867,368,263,822,852,837,866,806,865,-2399,851,352,262,534,534,821,836,594,594,549,549,593,593,533,533,848,773,579,579,564,578,548,563,276,276,577,576,306,291,516,560,305,305,275,259,
  77311. -251,-892,-2058,-2620,-2828,-2957,-3023,-3039,1041,1041,1040,1040,769,769,769,769,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,256,-511,-527,-543,-559,1530,-575,-591,1528,1527,1407,1526,1391,1023,1023,1023,1023,1525,1375,1268,1268,1103,1103,1087,1087,1039,1039,1523,-604,815,815,815,815,510,495,509,479,508,463,507,447,431,505,415,399,-734,-782,1262,-815,1259,1244,-831,1258,1228,-847,-863,1196,-879,1253,987,987,748,-767,493,493,462,477,414,414,686,669,478,446,461,445,474,429,487,458,412,471,1266,1264,1009,1009,799,799,-1019,-1276,-1452,-1581,-1677,-1757,-1821,-1886,-1933,-1997,1257,1257,1483,1468,1512,1422,1497,1406,1467,1496,1421,1510,1134,1134,1225,1225,1466,1451,1374,1405,1252,1252,1358,1480,1164,1164,1251,1251,1238,1238,1389,1465,-1407,1054,1101,-1423,1207,-1439,830,830,1248,1038,1237,1117,1223,1148,1236,1208,411,426,395,410,379,269,1193,1222,1132,1235,1221,1116,976,976,1192,1162,1177,1220,1131,1191,963,963,-1647,961,780,-1663,558,558,994,993,437,408,393,407,829,978,813,797,947,-1743,721,721,377,392,844,950,828,890,706,706,812,859,796,960,948,843,934,874,571,571,-1919,690,555,689,421,346,539,539,944,779,918,873,932,842,903,888,570,570,931,917,674,674,-2575,1562,-2591,1609,-2607,1654,1322,1322,1441,1441,1696,1546,1683,1593,1669,1624,1426,1426,1321,1321,1639,1680,1425,1425,1305,1305,1545,1668,1608,1623,1667,1592,1638,1666,1320,1320,1652,1607,1409,1409,1304,1304,1288,1288,1664,1637,1395,1395,1335,1335,1622,1636,1394,1394,1319,1319,1606,1621,1392,1392,1137,1137,1137,1137,345,390,360,375,404,373,1047,-2751,-2767,-2783,1062,1121,1046,-2799,1077,-2815,1106,1061,789,789,1105,1104,263,355,310,340,325,354,352,262,339,324,1091,1076,1029,1090,1060,1075,833,833,788,788,1088,1028,818,818,803,803,561,561,531,531,816,771,546,546,289,274,288,258,
  77312. -253,-317,-381,-446,-478,-509,1279,1279,-811,-1179,-1451,-1756,-1900,-2028,-2189,-2253,-2333,-2414,-2445,-2511,-2526,1313,1298,-2559,1041,1041,1040,1040,1025,1025,1024,1024,1022,1007,1021,991,1020,975,1019,959,687,687,1018,1017,671,671,655,655,1016,1015,639,639,758,758,623,623,757,607,756,591,755,575,754,559,543,543,1009,783,-575,-621,-685,-749,496,-590,750,749,734,748,974,989,1003,958,988,973,1002,942,987,957,972,1001,926,986,941,971,956,1000,910,985,925,999,894,970,-1071,-1087,-1102,1390,-1135,1436,1509,1451,1374,-1151,1405,1358,1480,1420,-1167,1507,1494,1389,1342,1465,1435,1450,1326,1505,1310,1493,1373,1479,1404,1492,1464,1419,428,443,472,397,736,526,464,464,486,457,442,471,484,482,1357,1449,1434,1478,1388,1491,1341,1490,1325,1489,1463,1403,1309,1477,1372,1448,1418,1433,1476,1356,1462,1387,-1439,1475,1340,1447,1402,1474,1324,1461,1371,1473,269,448,1432,1417,1308,1460,-1711,1459,-1727,1441,1099,1099,1446,1386,1431,1401,-1743,1289,1083,1083,1160,1160,1458,1445,1067,1067,1370,1457,1307,1430,1129,1129,1098,1098,268,432,267,416,266,400,-1887,1144,1187,1082,1173,1113,1186,1066,1050,1158,1128,1143,1172,1097,1171,1081,420,391,1157,1112,1170,1142,1127,1065,1169,1049,1156,1096,1141,1111,1155,1080,1126,1154,1064,1153,1140,1095,1048,-2159,1125,1110,1137,-2175,823,823,1139,1138,807,807,384,264,368,263,868,838,853,791,867,822,852,837,866,806,865,790,-2319,851,821,836,352,262,850,805,849,-2399,533,533,835,820,336,261,578,548,563,577,532,532,832,772,562,562,547,547,305,275,560,515,290,290,288,258 };
  77313. static const drmp3_uint8 tab32[] = { 130,162,193,209,44,28,76,140,9,9,9,9,9,9,9,9,190,254,222,238,126,94,157,157,109,61,173,205};
  77314. static const drmp3_uint8 tab33[] = { 252,236,220,204,188,172,156,140,124,108,92,76,60,44,28,12 };
  77315. static const drmp3_int16 tabindex[2*16] = { 0,32,64,98,0,132,180,218,292,364,426,538,648,746,0,1126,1460,1460,1460,1460,1460,1460,1460,1460,1842,1842,1842,1842,1842,1842,1842,1842 };
  77316. static const drmp3_uint8 g_linbits[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,6,8,10,13,4,5,6,7,8,9,11,13 };
  77317. #define DRMP3_PEEK_BITS(n) (bs_cache >> (32 - (n)))
  77318. #define DRMP3_FLUSH_BITS(n) { bs_cache <<= (n); bs_sh += (n); }
  77319. #define DRMP3_CHECK_BITS while (bs_sh >= 0) { bs_cache |= (drmp3_uint32)*bs_next_ptr++ << bs_sh; bs_sh -= 8; }
  77320. #define DRMP3_BSPOS ((bs_next_ptr - bs->buf)*8 - 24 + bs_sh)
  77321. float one = 0.0f;
  77322. int ireg = 0, big_val_cnt = gr_info->big_values;
  77323. const drmp3_uint8 *sfb = gr_info->sfbtab;
  77324. const drmp3_uint8 *bs_next_ptr = bs->buf + bs->pos/8;
  77325. drmp3_uint32 bs_cache = (((bs_next_ptr[0]*256u + bs_next_ptr[1])*256u + bs_next_ptr[2])*256u + bs_next_ptr[3]) << (bs->pos & 7);
  77326. int pairs_to_decode, np, bs_sh = (bs->pos & 7) - 8;
  77327. bs_next_ptr += 4;
  77328. while (big_val_cnt > 0)
  77329. {
  77330. int tab_num = gr_info->table_select[ireg];
  77331. int sfb_cnt = gr_info->region_count[ireg++];
  77332. const drmp3_int16 *codebook = tabs + tabindex[tab_num];
  77333. int linbits = g_linbits[tab_num];
  77334. if (linbits)
  77335. {
  77336. do
  77337. {
  77338. np = *sfb++ / 2;
  77339. pairs_to_decode = DRMP3_MIN(big_val_cnt, np);
  77340. one = *scf++;
  77341. do
  77342. {
  77343. int j, w = 5;
  77344. int leaf = codebook[DRMP3_PEEK_BITS(w)];
  77345. while (leaf < 0)
  77346. {
  77347. DRMP3_FLUSH_BITS(w);
  77348. w = leaf & 7;
  77349. leaf = codebook[DRMP3_PEEK_BITS(w) - (leaf >> 3)];
  77350. }
  77351. DRMP3_FLUSH_BITS(leaf >> 8);
  77352. for (j = 0; j < 2; j++, dst++, leaf >>= 4)
  77353. {
  77354. int lsb = leaf & 0x0F;
  77355. if (lsb == 15)
  77356. {
  77357. lsb += DRMP3_PEEK_BITS(linbits);
  77358. DRMP3_FLUSH_BITS(linbits);
  77359. DRMP3_CHECK_BITS;
  77360. *dst = one*drmp3_L3_pow_43(lsb)*((drmp3_int32)bs_cache < 0 ? -1: 1);
  77361. } else
  77362. {
  77363. *dst = g_drmp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one;
  77364. }
  77365. DRMP3_FLUSH_BITS(lsb ? 1 : 0);
  77366. }
  77367. DRMP3_CHECK_BITS;
  77368. } while (--pairs_to_decode);
  77369. } while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0);
  77370. } else
  77371. {
  77372. do
  77373. {
  77374. np = *sfb++ / 2;
  77375. pairs_to_decode = DRMP3_MIN(big_val_cnt, np);
  77376. one = *scf++;
  77377. do
  77378. {
  77379. int j, w = 5;
  77380. int leaf = codebook[DRMP3_PEEK_BITS(w)];
  77381. while (leaf < 0)
  77382. {
  77383. DRMP3_FLUSH_BITS(w);
  77384. w = leaf & 7;
  77385. leaf = codebook[DRMP3_PEEK_BITS(w) - (leaf >> 3)];
  77386. }
  77387. DRMP3_FLUSH_BITS(leaf >> 8);
  77388. for (j = 0; j < 2; j++, dst++, leaf >>= 4)
  77389. {
  77390. int lsb = leaf & 0x0F;
  77391. *dst = g_drmp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one;
  77392. DRMP3_FLUSH_BITS(lsb ? 1 : 0);
  77393. }
  77394. DRMP3_CHECK_BITS;
  77395. } while (--pairs_to_decode);
  77396. } while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0);
  77397. }
  77398. }
  77399. for (np = 1 - big_val_cnt;; dst += 4)
  77400. {
  77401. const drmp3_uint8 *codebook_count1 = (gr_info->count1_table) ? tab33 : tab32;
  77402. int leaf = codebook_count1[DRMP3_PEEK_BITS(4)];
  77403. if (!(leaf & 8))
  77404. {
  77405. leaf = codebook_count1[(leaf >> 3) + (bs_cache << 4 >> (32 - (leaf & 3)))];
  77406. }
  77407. DRMP3_FLUSH_BITS(leaf & 7);
  77408. if (DRMP3_BSPOS > layer3gr_limit)
  77409. {
  77410. break;
  77411. }
  77412. #define DRMP3_RELOAD_SCALEFACTOR if (!--np) { np = *sfb++/2; if (!np) break; one = *scf++; }
  77413. #define DRMP3_DEQ_COUNT1(s) if (leaf & (128 >> s)) { dst[s] = ((drmp3_int32)bs_cache < 0) ? -one : one; DRMP3_FLUSH_BITS(1) }
  77414. DRMP3_RELOAD_SCALEFACTOR;
  77415. DRMP3_DEQ_COUNT1(0);
  77416. DRMP3_DEQ_COUNT1(1);
  77417. DRMP3_RELOAD_SCALEFACTOR;
  77418. DRMP3_DEQ_COUNT1(2);
  77419. DRMP3_DEQ_COUNT1(3);
  77420. DRMP3_CHECK_BITS;
  77421. }
  77422. bs->pos = layer3gr_limit;
  77423. }
  77424. static void drmp3_L3_midside_stereo(float *left, int n)
  77425. {
  77426. int i = 0;
  77427. float *right = left + 576;
  77428. #if DRMP3_HAVE_SIMD
  77429. if (drmp3_have_simd())
  77430. {
  77431. for (; i < n - 3; i += 4)
  77432. {
  77433. drmp3_f4 vl = DRMP3_VLD(left + i);
  77434. drmp3_f4 vr = DRMP3_VLD(right + i);
  77435. DRMP3_VSTORE(left + i, DRMP3_VADD(vl, vr));
  77436. DRMP3_VSTORE(right + i, DRMP3_VSUB(vl, vr));
  77437. }
  77438. #ifdef __GNUC__
  77439. if (__builtin_constant_p(n % 4 == 0) && n % 4 == 0)
  77440. return;
  77441. #endif
  77442. }
  77443. #endif
  77444. for (; i < n; i++)
  77445. {
  77446. float a = left[i];
  77447. float b = right[i];
  77448. left[i] = a + b;
  77449. right[i] = a - b;
  77450. }
  77451. }
  77452. static void drmp3_L3_intensity_stereo_band(float *left, int n, float kl, float kr)
  77453. {
  77454. int i;
  77455. for (i = 0; i < n; i++)
  77456. {
  77457. left[i + 576] = left[i]*kr;
  77458. left[i] = left[i]*kl;
  77459. }
  77460. }
  77461. static void drmp3_L3_stereo_top_band(const float *right, const drmp3_uint8 *sfb, int nbands, int max_band[3])
  77462. {
  77463. int i, k;
  77464. max_band[0] = max_band[1] = max_band[2] = -1;
  77465. for (i = 0; i < nbands; i++)
  77466. {
  77467. for (k = 0; k < sfb[i]; k += 2)
  77468. {
  77469. if (right[k] != 0 || right[k + 1] != 0)
  77470. {
  77471. max_band[i % 3] = i;
  77472. break;
  77473. }
  77474. }
  77475. right += sfb[i];
  77476. }
  77477. }
  77478. static void drmp3_L3_stereo_process(float *left, const drmp3_uint8 *ist_pos, const drmp3_uint8 *sfb, const drmp3_uint8 *hdr, int max_band[3], int mpeg2_sh)
  77479. {
  77480. static const float g_pan[7*2] = { 0,1,0.21132487f,0.78867513f,0.36602540f,0.63397460f,0.5f,0.5f,0.63397460f,0.36602540f,0.78867513f,0.21132487f,1,0 };
  77481. unsigned i, max_pos = DRMP3_HDR_TEST_MPEG1(hdr) ? 7 : 64;
  77482. for (i = 0; sfb[i]; i++)
  77483. {
  77484. unsigned ipos = ist_pos[i];
  77485. if ((int)i > max_band[i % 3] && ipos < max_pos)
  77486. {
  77487. float kl, kr, s = DRMP3_HDR_TEST_MS_STEREO(hdr) ? 1.41421356f : 1;
  77488. if (DRMP3_HDR_TEST_MPEG1(hdr))
  77489. {
  77490. kl = g_pan[2*ipos];
  77491. kr = g_pan[2*ipos + 1];
  77492. } else
  77493. {
  77494. kl = 1;
  77495. kr = drmp3_L3_ldexp_q2(1, (ipos + 1) >> 1 << mpeg2_sh);
  77496. if (ipos & 1)
  77497. {
  77498. kl = kr;
  77499. kr = 1;
  77500. }
  77501. }
  77502. drmp3_L3_intensity_stereo_band(left, sfb[i], kl*s, kr*s);
  77503. } else if (DRMP3_HDR_TEST_MS_STEREO(hdr))
  77504. {
  77505. drmp3_L3_midside_stereo(left, sfb[i]);
  77506. }
  77507. left += sfb[i];
  77508. }
  77509. }
  77510. static void drmp3_L3_intensity_stereo(float *left, drmp3_uint8 *ist_pos, const drmp3_L3_gr_info *gr, const drmp3_uint8 *hdr)
  77511. {
  77512. int max_band[3], n_sfb = gr->n_long_sfb + gr->n_short_sfb;
  77513. int i, max_blocks = gr->n_short_sfb ? 3 : 1;
  77514. drmp3_L3_stereo_top_band(left + 576, gr->sfbtab, n_sfb, max_band);
  77515. if (gr->n_long_sfb)
  77516. {
  77517. max_band[0] = max_band[1] = max_band[2] = DRMP3_MAX(DRMP3_MAX(max_band[0], max_band[1]), max_band[2]);
  77518. }
  77519. for (i = 0; i < max_blocks; i++)
  77520. {
  77521. int default_pos = DRMP3_HDR_TEST_MPEG1(hdr) ? 3 : 0;
  77522. int itop = n_sfb - max_blocks + i;
  77523. int prev = itop - max_blocks;
  77524. ist_pos[itop] = (drmp3_uint8)(max_band[i] >= prev ? default_pos : ist_pos[prev]);
  77525. }
  77526. drmp3_L3_stereo_process(left, ist_pos, gr->sfbtab, hdr, max_band, gr[1].scalefac_compress & 1);
  77527. }
  77528. static void drmp3_L3_reorder(float *grbuf, float *scratch, const drmp3_uint8 *sfb)
  77529. {
  77530. int i, len;
  77531. float *src = grbuf, *dst = scratch;
  77532. for (;0 != (len = *sfb); sfb += 3, src += 2*len)
  77533. {
  77534. for (i = 0; i < len; i++, src++)
  77535. {
  77536. *dst++ = src[0*len];
  77537. *dst++ = src[1*len];
  77538. *dst++ = src[2*len];
  77539. }
  77540. }
  77541. DRMP3_COPY_MEMORY(grbuf, scratch, (dst - scratch)*sizeof(float));
  77542. }
  77543. static void drmp3_L3_antialias(float *grbuf, int nbands)
  77544. {
  77545. static const float g_aa[2][8] = {
  77546. {0.85749293f,0.88174200f,0.94962865f,0.98331459f,0.99551782f,0.99916056f,0.99989920f,0.99999316f},
  77547. {0.51449576f,0.47173197f,0.31337745f,0.18191320f,0.09457419f,0.04096558f,0.01419856f,0.00369997f}
  77548. };
  77549. for (; nbands > 0; nbands--, grbuf += 18)
  77550. {
  77551. int i = 0;
  77552. #if DRMP3_HAVE_SIMD
  77553. if (drmp3_have_simd()) for (; i < 8; i += 4)
  77554. {
  77555. drmp3_f4 vu = DRMP3_VLD(grbuf + 18 + i);
  77556. drmp3_f4 vd = DRMP3_VLD(grbuf + 14 - i);
  77557. drmp3_f4 vc0 = DRMP3_VLD(g_aa[0] + i);
  77558. drmp3_f4 vc1 = DRMP3_VLD(g_aa[1] + i);
  77559. vd = DRMP3_VREV(vd);
  77560. DRMP3_VSTORE(grbuf + 18 + i, DRMP3_VSUB(DRMP3_VMUL(vu, vc0), DRMP3_VMUL(vd, vc1)));
  77561. vd = DRMP3_VADD(DRMP3_VMUL(vu, vc1), DRMP3_VMUL(vd, vc0));
  77562. DRMP3_VSTORE(grbuf + 14 - i, DRMP3_VREV(vd));
  77563. }
  77564. #endif
  77565. #ifndef DR_MP3_ONLY_SIMD
  77566. for(; i < 8; i++)
  77567. {
  77568. float u = grbuf[18 + i];
  77569. float d = grbuf[17 - i];
  77570. grbuf[18 + i] = u*g_aa[0][i] - d*g_aa[1][i];
  77571. grbuf[17 - i] = u*g_aa[1][i] + d*g_aa[0][i];
  77572. }
  77573. #endif
  77574. }
  77575. }
  77576. static void drmp3_L3_dct3_9(float *y)
  77577. {
  77578. float s0, s1, s2, s3, s4, s5, s6, s7, s8, t0, t2, t4;
  77579. s0 = y[0]; s2 = y[2]; s4 = y[4]; s6 = y[6]; s8 = y[8];
  77580. t0 = s0 + s6*0.5f;
  77581. s0 -= s6;
  77582. t4 = (s4 + s2)*0.93969262f;
  77583. t2 = (s8 + s2)*0.76604444f;
  77584. s6 = (s4 - s8)*0.17364818f;
  77585. s4 += s8 - s2;
  77586. s2 = s0 - s4*0.5f;
  77587. y[4] = s4 + s0;
  77588. s8 = t0 - t2 + s6;
  77589. s0 = t0 - t4 + t2;
  77590. s4 = t0 + t4 - s6;
  77591. s1 = y[1]; s3 = y[3]; s5 = y[5]; s7 = y[7];
  77592. s3 *= 0.86602540f;
  77593. t0 = (s5 + s1)*0.98480775f;
  77594. t4 = (s5 - s7)*0.34202014f;
  77595. t2 = (s1 + s7)*0.64278761f;
  77596. s1 = (s1 - s5 - s7)*0.86602540f;
  77597. s5 = t0 - s3 - t2;
  77598. s7 = t4 - s3 - t0;
  77599. s3 = t4 + s3 - t2;
  77600. y[0] = s4 - s7;
  77601. y[1] = s2 + s1;
  77602. y[2] = s0 - s3;
  77603. y[3] = s8 + s5;
  77604. y[5] = s8 - s5;
  77605. y[6] = s0 + s3;
  77606. y[7] = s2 - s1;
  77607. y[8] = s4 + s7;
  77608. }
  77609. static void drmp3_L3_imdct36(float *grbuf, float *overlap, const float *window, int nbands)
  77610. {
  77611. int i, j;
  77612. static const float g_twid9[18] = {
  77613. 0.73727734f,0.79335334f,0.84339145f,0.88701083f,0.92387953f,0.95371695f,0.97629601f,0.99144486f,0.99904822f,0.67559021f,0.60876143f,0.53729961f,0.46174861f,0.38268343f,0.30070580f,0.21643961f,0.13052619f,0.04361938f
  77614. };
  77615. for (j = 0; j < nbands; j++, grbuf += 18, overlap += 9)
  77616. {
  77617. float co[9], si[9];
  77618. co[0] = -grbuf[0];
  77619. si[0] = grbuf[17];
  77620. for (i = 0; i < 4; i++)
  77621. {
  77622. si[8 - 2*i] = grbuf[4*i + 1] - grbuf[4*i + 2];
  77623. co[1 + 2*i] = grbuf[4*i + 1] + grbuf[4*i + 2];
  77624. si[7 - 2*i] = grbuf[4*i + 4] - grbuf[4*i + 3];
  77625. co[2 + 2*i] = -(grbuf[4*i + 3] + grbuf[4*i + 4]);
  77626. }
  77627. drmp3_L3_dct3_9(co);
  77628. drmp3_L3_dct3_9(si);
  77629. si[1] = -si[1];
  77630. si[3] = -si[3];
  77631. si[5] = -si[5];
  77632. si[7] = -si[7];
  77633. i = 0;
  77634. #if DRMP3_HAVE_SIMD
  77635. if (drmp3_have_simd()) for (; i < 8; i += 4)
  77636. {
  77637. drmp3_f4 vovl = DRMP3_VLD(overlap + i);
  77638. drmp3_f4 vc = DRMP3_VLD(co + i);
  77639. drmp3_f4 vs = DRMP3_VLD(si + i);
  77640. drmp3_f4 vr0 = DRMP3_VLD(g_twid9 + i);
  77641. drmp3_f4 vr1 = DRMP3_VLD(g_twid9 + 9 + i);
  77642. drmp3_f4 vw0 = DRMP3_VLD(window + i);
  77643. drmp3_f4 vw1 = DRMP3_VLD(window + 9 + i);
  77644. drmp3_f4 vsum = DRMP3_VADD(DRMP3_VMUL(vc, vr1), DRMP3_VMUL(vs, vr0));
  77645. DRMP3_VSTORE(overlap + i, DRMP3_VSUB(DRMP3_VMUL(vc, vr0), DRMP3_VMUL(vs, vr1)));
  77646. DRMP3_VSTORE(grbuf + i, DRMP3_VSUB(DRMP3_VMUL(vovl, vw0), DRMP3_VMUL(vsum, vw1)));
  77647. vsum = DRMP3_VADD(DRMP3_VMUL(vovl, vw1), DRMP3_VMUL(vsum, vw0));
  77648. DRMP3_VSTORE(grbuf + 14 - i, DRMP3_VREV(vsum));
  77649. }
  77650. #endif
  77651. for (; i < 9; i++)
  77652. {
  77653. float ovl = overlap[i];
  77654. float sum = co[i]*g_twid9[9 + i] + si[i]*g_twid9[0 + i];
  77655. overlap[i] = co[i]*g_twid9[0 + i] - si[i]*g_twid9[9 + i];
  77656. grbuf[i] = ovl*window[0 + i] - sum*window[9 + i];
  77657. grbuf[17 - i] = ovl*window[9 + i] + sum*window[0 + i];
  77658. }
  77659. }
  77660. }
  77661. static void drmp3_L3_idct3(float x0, float x1, float x2, float *dst)
  77662. {
  77663. float m1 = x1*0.86602540f;
  77664. float a1 = x0 - x2*0.5f;
  77665. dst[1] = x0 + x2;
  77666. dst[0] = a1 + m1;
  77667. dst[2] = a1 - m1;
  77668. }
  77669. static void drmp3_L3_imdct12(float *x, float *dst, float *overlap)
  77670. {
  77671. static const float g_twid3[6] = { 0.79335334f,0.92387953f,0.99144486f, 0.60876143f,0.38268343f,0.13052619f };
  77672. float co[3], si[3];
  77673. int i;
  77674. drmp3_L3_idct3(-x[0], x[6] + x[3], x[12] + x[9], co);
  77675. drmp3_L3_idct3(x[15], x[12] - x[9], x[6] - x[3], si);
  77676. si[1] = -si[1];
  77677. for (i = 0; i < 3; i++)
  77678. {
  77679. float ovl = overlap[i];
  77680. float sum = co[i]*g_twid3[3 + i] + si[i]*g_twid3[0 + i];
  77681. overlap[i] = co[i]*g_twid3[0 + i] - si[i]*g_twid3[3 + i];
  77682. dst[i] = ovl*g_twid3[2 - i] - sum*g_twid3[5 - i];
  77683. dst[5 - i] = ovl*g_twid3[5 - i] + sum*g_twid3[2 - i];
  77684. }
  77685. }
  77686. static void drmp3_L3_imdct_short(float *grbuf, float *overlap, int nbands)
  77687. {
  77688. for (;nbands > 0; nbands--, overlap += 9, grbuf += 18)
  77689. {
  77690. float tmp[18];
  77691. DRMP3_COPY_MEMORY(tmp, grbuf, sizeof(tmp));
  77692. DRMP3_COPY_MEMORY(grbuf, overlap, 6*sizeof(float));
  77693. drmp3_L3_imdct12(tmp, grbuf + 6, overlap + 6);
  77694. drmp3_L3_imdct12(tmp + 1, grbuf + 12, overlap + 6);
  77695. drmp3_L3_imdct12(tmp + 2, overlap, overlap + 6);
  77696. }
  77697. }
  77698. static void drmp3_L3_change_sign(float *grbuf)
  77699. {
  77700. int b, i;
  77701. for (b = 0, grbuf += 18; b < 32; b += 2, grbuf += 36)
  77702. for (i = 1; i < 18; i += 2)
  77703. grbuf[i] = -grbuf[i];
  77704. }
  77705. static void drmp3_L3_imdct_gr(float *grbuf, float *overlap, unsigned block_type, unsigned n_long_bands)
  77706. {
  77707. static const float g_mdct_window[2][18] = {
  77708. { 0.99904822f,0.99144486f,0.97629601f,0.95371695f,0.92387953f,0.88701083f,0.84339145f,0.79335334f,0.73727734f,0.04361938f,0.13052619f,0.21643961f,0.30070580f,0.38268343f,0.46174861f,0.53729961f,0.60876143f,0.67559021f },
  77709. { 1,1,1,1,1,1,0.99144486f,0.92387953f,0.79335334f,0,0,0,0,0,0,0.13052619f,0.38268343f,0.60876143f }
  77710. };
  77711. if (n_long_bands)
  77712. {
  77713. drmp3_L3_imdct36(grbuf, overlap, g_mdct_window[0], n_long_bands);
  77714. grbuf += 18*n_long_bands;
  77715. overlap += 9*n_long_bands;
  77716. }
  77717. if (block_type == DRMP3_SHORT_BLOCK_TYPE)
  77718. drmp3_L3_imdct_short(grbuf, overlap, 32 - n_long_bands);
  77719. else
  77720. drmp3_L3_imdct36(grbuf, overlap, g_mdct_window[block_type == DRMP3_STOP_BLOCK_TYPE], 32 - n_long_bands);
  77721. }
  77722. static void drmp3_L3_save_reservoir(drmp3dec *h, drmp3dec_scratch *s)
  77723. {
  77724. int pos = (s->bs.pos + 7)/8u;
  77725. int remains = s->bs.limit/8u - pos;
  77726. if (remains > DRMP3_MAX_BITRESERVOIR_BYTES)
  77727. {
  77728. pos += remains - DRMP3_MAX_BITRESERVOIR_BYTES;
  77729. remains = DRMP3_MAX_BITRESERVOIR_BYTES;
  77730. }
  77731. if (remains > 0)
  77732. {
  77733. DRMP3_MOVE_MEMORY(h->reserv_buf, s->maindata + pos, remains);
  77734. }
  77735. h->reserv = remains;
  77736. }
  77737. static int drmp3_L3_restore_reservoir(drmp3dec *h, drmp3_bs *bs, drmp3dec_scratch *s, int main_data_begin)
  77738. {
  77739. int frame_bytes = (bs->limit - bs->pos)/8;
  77740. int bytes_have = DRMP3_MIN(h->reserv, main_data_begin);
  77741. DRMP3_COPY_MEMORY(s->maindata, h->reserv_buf + DRMP3_MAX(0, h->reserv - main_data_begin), DRMP3_MIN(h->reserv, main_data_begin));
  77742. DRMP3_COPY_MEMORY(s->maindata + bytes_have, bs->buf + bs->pos/8, frame_bytes);
  77743. drmp3_bs_init(&s->bs, s->maindata, bytes_have + frame_bytes);
  77744. return h->reserv >= main_data_begin;
  77745. }
  77746. static void drmp3_L3_decode(drmp3dec *h, drmp3dec_scratch *s, drmp3_L3_gr_info *gr_info, int nch)
  77747. {
  77748. int ch;
  77749. for (ch = 0; ch < nch; ch++)
  77750. {
  77751. int layer3gr_limit = s->bs.pos + gr_info[ch].part_23_length;
  77752. drmp3_L3_decode_scalefactors(h->header, s->ist_pos[ch], &s->bs, gr_info + ch, s->scf, ch);
  77753. drmp3_L3_huffman(s->grbuf[ch], &s->bs, gr_info + ch, s->scf, layer3gr_limit);
  77754. }
  77755. if (DRMP3_HDR_TEST_I_STEREO(h->header))
  77756. {
  77757. drmp3_L3_intensity_stereo(s->grbuf[0], s->ist_pos[1], gr_info, h->header);
  77758. } else if (DRMP3_HDR_IS_MS_STEREO(h->header))
  77759. {
  77760. drmp3_L3_midside_stereo(s->grbuf[0], 576);
  77761. }
  77762. for (ch = 0; ch < nch; ch++, gr_info++)
  77763. {
  77764. int aa_bands = 31;
  77765. int n_long_bands = (gr_info->mixed_block_flag ? 2 : 0) << (int)(DRMP3_HDR_GET_MY_SAMPLE_RATE(h->header) == 2);
  77766. if (gr_info->n_short_sfb)
  77767. {
  77768. aa_bands = n_long_bands - 1;
  77769. drmp3_L3_reorder(s->grbuf[ch] + n_long_bands*18, s->syn[0], gr_info->sfbtab + gr_info->n_long_sfb);
  77770. }
  77771. drmp3_L3_antialias(s->grbuf[ch], aa_bands);
  77772. drmp3_L3_imdct_gr(s->grbuf[ch], h->mdct_overlap[ch], gr_info->block_type, n_long_bands);
  77773. drmp3_L3_change_sign(s->grbuf[ch]);
  77774. }
  77775. }
  77776. static void drmp3d_DCT_II(float *grbuf, int n)
  77777. {
  77778. static const float g_sec[24] = {
  77779. 10.19000816f,0.50060302f,0.50241929f,3.40760851f,0.50547093f,0.52249861f,2.05778098f,0.51544732f,0.56694406f,1.48416460f,0.53104258f,0.64682180f,1.16943991f,0.55310392f,0.78815460f,0.97256821f,0.58293498f,1.06067765f,0.83934963f,0.62250412f,1.72244716f,0.74453628f,0.67480832f,5.10114861f
  77780. };
  77781. int i, k = 0;
  77782. #if DRMP3_HAVE_SIMD
  77783. if (drmp3_have_simd()) for (; k < n; k += 4)
  77784. {
  77785. drmp3_f4 t[4][8], *x;
  77786. float *y = grbuf + k;
  77787. for (x = t[0], i = 0; i < 8; i++, x++)
  77788. {
  77789. drmp3_f4 x0 = DRMP3_VLD(&y[i*18]);
  77790. drmp3_f4 x1 = DRMP3_VLD(&y[(15 - i)*18]);
  77791. drmp3_f4 x2 = DRMP3_VLD(&y[(16 + i)*18]);
  77792. drmp3_f4 x3 = DRMP3_VLD(&y[(31 - i)*18]);
  77793. drmp3_f4 t0 = DRMP3_VADD(x0, x3);
  77794. drmp3_f4 t1 = DRMP3_VADD(x1, x2);
  77795. drmp3_f4 t2 = DRMP3_VMUL_S(DRMP3_VSUB(x1, x2), g_sec[3*i + 0]);
  77796. drmp3_f4 t3 = DRMP3_VMUL_S(DRMP3_VSUB(x0, x3), g_sec[3*i + 1]);
  77797. x[0] = DRMP3_VADD(t0, t1);
  77798. x[8] = DRMP3_VMUL_S(DRMP3_VSUB(t0, t1), g_sec[3*i + 2]);
  77799. x[16] = DRMP3_VADD(t3, t2);
  77800. x[24] = DRMP3_VMUL_S(DRMP3_VSUB(t3, t2), g_sec[3*i + 2]);
  77801. }
  77802. for (x = t[0], i = 0; i < 4; i++, x += 8)
  77803. {
  77804. drmp3_f4 x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3], x4 = x[4], x5 = x[5], x6 = x[6], x7 = x[7], xt;
  77805. xt = DRMP3_VSUB(x0, x7); x0 = DRMP3_VADD(x0, x7);
  77806. x7 = DRMP3_VSUB(x1, x6); x1 = DRMP3_VADD(x1, x6);
  77807. x6 = DRMP3_VSUB(x2, x5); x2 = DRMP3_VADD(x2, x5);
  77808. x5 = DRMP3_VSUB(x3, x4); x3 = DRMP3_VADD(x3, x4);
  77809. x4 = DRMP3_VSUB(x0, x3); x0 = DRMP3_VADD(x0, x3);
  77810. x3 = DRMP3_VSUB(x1, x2); x1 = DRMP3_VADD(x1, x2);
  77811. x[0] = DRMP3_VADD(x0, x1);
  77812. x[4] = DRMP3_VMUL_S(DRMP3_VSUB(x0, x1), 0.70710677f);
  77813. x5 = DRMP3_VADD(x5, x6);
  77814. x6 = DRMP3_VMUL_S(DRMP3_VADD(x6, x7), 0.70710677f);
  77815. x7 = DRMP3_VADD(x7, xt);
  77816. x3 = DRMP3_VMUL_S(DRMP3_VADD(x3, x4), 0.70710677f);
  77817. x5 = DRMP3_VSUB(x5, DRMP3_VMUL_S(x7, 0.198912367f));
  77818. x7 = DRMP3_VADD(x7, DRMP3_VMUL_S(x5, 0.382683432f));
  77819. x5 = DRMP3_VSUB(x5, DRMP3_VMUL_S(x7, 0.198912367f));
  77820. x0 = DRMP3_VSUB(xt, x6); xt = DRMP3_VADD(xt, x6);
  77821. x[1] = DRMP3_VMUL_S(DRMP3_VADD(xt, x7), 0.50979561f);
  77822. x[2] = DRMP3_VMUL_S(DRMP3_VADD(x4, x3), 0.54119611f);
  77823. x[3] = DRMP3_VMUL_S(DRMP3_VSUB(x0, x5), 0.60134488f);
  77824. x[5] = DRMP3_VMUL_S(DRMP3_VADD(x0, x5), 0.89997619f);
  77825. x[6] = DRMP3_VMUL_S(DRMP3_VSUB(x4, x3), 1.30656302f);
  77826. x[7] = DRMP3_VMUL_S(DRMP3_VSUB(xt, x7), 2.56291556f);
  77827. }
  77828. if (k > n - 3)
  77829. {
  77830. #if DRMP3_HAVE_SSE
  77831. #define DRMP3_VSAVE2(i, v) _mm_storel_pi((__m64 *)(void*)&y[i*18], v)
  77832. #else
  77833. #define DRMP3_VSAVE2(i, v) vst1_f32((float32_t *)&y[(i)*18], vget_low_f32(v))
  77834. #endif
  77835. for (i = 0; i < 7; i++, y += 4*18)
  77836. {
  77837. drmp3_f4 s = DRMP3_VADD(t[3][i], t[3][i + 1]);
  77838. DRMP3_VSAVE2(0, t[0][i]);
  77839. DRMP3_VSAVE2(1, DRMP3_VADD(t[2][i], s));
  77840. DRMP3_VSAVE2(2, DRMP3_VADD(t[1][i], t[1][i + 1]));
  77841. DRMP3_VSAVE2(3, DRMP3_VADD(t[2][1 + i], s));
  77842. }
  77843. DRMP3_VSAVE2(0, t[0][7]);
  77844. DRMP3_VSAVE2(1, DRMP3_VADD(t[2][7], t[3][7]));
  77845. DRMP3_VSAVE2(2, t[1][7]);
  77846. DRMP3_VSAVE2(3, t[3][7]);
  77847. } else
  77848. {
  77849. #define DRMP3_VSAVE4(i, v) DRMP3_VSTORE(&y[(i)*18], v)
  77850. for (i = 0; i < 7; i++, y += 4*18)
  77851. {
  77852. drmp3_f4 s = DRMP3_VADD(t[3][i], t[3][i + 1]);
  77853. DRMP3_VSAVE4(0, t[0][i]);
  77854. DRMP3_VSAVE4(1, DRMP3_VADD(t[2][i], s));
  77855. DRMP3_VSAVE4(2, DRMP3_VADD(t[1][i], t[1][i + 1]));
  77856. DRMP3_VSAVE4(3, DRMP3_VADD(t[2][1 + i], s));
  77857. }
  77858. DRMP3_VSAVE4(0, t[0][7]);
  77859. DRMP3_VSAVE4(1, DRMP3_VADD(t[2][7], t[3][7]));
  77860. DRMP3_VSAVE4(2, t[1][7]);
  77861. DRMP3_VSAVE4(3, t[3][7]);
  77862. }
  77863. } else
  77864. #endif
  77865. #ifdef DR_MP3_ONLY_SIMD
  77866. {}
  77867. #else
  77868. for (; k < n; k++)
  77869. {
  77870. float t[4][8], *x, *y = grbuf + k;
  77871. for (x = t[0], i = 0; i < 8; i++, x++)
  77872. {
  77873. float x0 = y[i*18];
  77874. float x1 = y[(15 - i)*18];
  77875. float x2 = y[(16 + i)*18];
  77876. float x3 = y[(31 - i)*18];
  77877. float t0 = x0 + x3;
  77878. float t1 = x1 + x2;
  77879. float t2 = (x1 - x2)*g_sec[3*i + 0];
  77880. float t3 = (x0 - x3)*g_sec[3*i + 1];
  77881. x[0] = t0 + t1;
  77882. x[8] = (t0 - t1)*g_sec[3*i + 2];
  77883. x[16] = t3 + t2;
  77884. x[24] = (t3 - t2)*g_sec[3*i + 2];
  77885. }
  77886. for (x = t[0], i = 0; i < 4; i++, x += 8)
  77887. {
  77888. float x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3], x4 = x[4], x5 = x[5], x6 = x[6], x7 = x[7], xt;
  77889. xt = x0 - x7; x0 += x7;
  77890. x7 = x1 - x6; x1 += x6;
  77891. x6 = x2 - x5; x2 += x5;
  77892. x5 = x3 - x4; x3 += x4;
  77893. x4 = x0 - x3; x0 += x3;
  77894. x3 = x1 - x2; x1 += x2;
  77895. x[0] = x0 + x1;
  77896. x[4] = (x0 - x1)*0.70710677f;
  77897. x5 = x5 + x6;
  77898. x6 = (x6 + x7)*0.70710677f;
  77899. x7 = x7 + xt;
  77900. x3 = (x3 + x4)*0.70710677f;
  77901. x5 -= x7*0.198912367f;
  77902. x7 += x5*0.382683432f;
  77903. x5 -= x7*0.198912367f;
  77904. x0 = xt - x6; xt += x6;
  77905. x[1] = (xt + x7)*0.50979561f;
  77906. x[2] = (x4 + x3)*0.54119611f;
  77907. x[3] = (x0 - x5)*0.60134488f;
  77908. x[5] = (x0 + x5)*0.89997619f;
  77909. x[6] = (x4 - x3)*1.30656302f;
  77910. x[7] = (xt - x7)*2.56291556f;
  77911. }
  77912. for (i = 0; i < 7; i++, y += 4*18)
  77913. {
  77914. y[0*18] = t[0][i];
  77915. y[1*18] = t[2][i] + t[3][i] + t[3][i + 1];
  77916. y[2*18] = t[1][i] + t[1][i + 1];
  77917. y[3*18] = t[2][i + 1] + t[3][i] + t[3][i + 1];
  77918. }
  77919. y[0*18] = t[0][7];
  77920. y[1*18] = t[2][7] + t[3][7];
  77921. y[2*18] = t[1][7];
  77922. y[3*18] = t[3][7];
  77923. }
  77924. #endif
  77925. }
  77926. #ifndef DR_MP3_FLOAT_OUTPUT
  77927. typedef drmp3_int16 drmp3d_sample_t;
  77928. static drmp3_int16 drmp3d_scale_pcm(float sample)
  77929. {
  77930. drmp3_int16 s;
  77931. #if DRMP3_HAVE_ARMV6
  77932. drmp3_int32 s32 = (drmp3_int32)(sample + .5f);
  77933. s32 -= (s32 < 0);
  77934. s = (drmp3_int16)drmp3_clip_int16_arm(s32);
  77935. #else
  77936. if (sample >= 32766.5) return (drmp3_int16) 32767;
  77937. if (sample <= -32767.5) return (drmp3_int16)-32768;
  77938. s = (drmp3_int16)(sample + .5f);
  77939. s -= (s < 0);
  77940. #endif
  77941. return s;
  77942. }
  77943. #else
  77944. typedef float drmp3d_sample_t;
  77945. static float drmp3d_scale_pcm(float sample)
  77946. {
  77947. return sample*(1.f/32768.f);
  77948. }
  77949. #endif
  77950. static void drmp3d_synth_pair(drmp3d_sample_t *pcm, int nch, const float *z)
  77951. {
  77952. float a;
  77953. a = (z[14*64] - z[ 0]) * 29;
  77954. a += (z[ 1*64] + z[13*64]) * 213;
  77955. a += (z[12*64] - z[ 2*64]) * 459;
  77956. a += (z[ 3*64] + z[11*64]) * 2037;
  77957. a += (z[10*64] - z[ 4*64]) * 5153;
  77958. a += (z[ 5*64] + z[ 9*64]) * 6574;
  77959. a += (z[ 8*64] - z[ 6*64]) * 37489;
  77960. a += z[ 7*64] * 75038;
  77961. pcm[0] = drmp3d_scale_pcm(a);
  77962. z += 2;
  77963. a = z[14*64] * 104;
  77964. a += z[12*64] * 1567;
  77965. a += z[10*64] * 9727;
  77966. a += z[ 8*64] * 64019;
  77967. a += z[ 6*64] * -9975;
  77968. a += z[ 4*64] * -45;
  77969. a += z[ 2*64] * 146;
  77970. a += z[ 0*64] * -5;
  77971. pcm[16*nch] = drmp3d_scale_pcm(a);
  77972. }
  77973. static void drmp3d_synth(float *xl, drmp3d_sample_t *dstl, int nch, float *lins)
  77974. {
  77975. int i;
  77976. float *xr = xl + 576*(nch - 1);
  77977. drmp3d_sample_t *dstr = dstl + (nch - 1);
  77978. static const float g_win[] = {
  77979. -1,26,-31,208,218,401,-519,2063,2000,4788,-5517,7134,5959,35640,-39336,74992,
  77980. -1,24,-35,202,222,347,-581,2080,1952,4425,-5879,7640,5288,33791,-41176,74856,
  77981. -1,21,-38,196,225,294,-645,2087,1893,4063,-6237,8092,4561,31947,-43006,74630,
  77982. -1,19,-41,190,227,244,-711,2085,1822,3705,-6589,8492,3776,30112,-44821,74313,
  77983. -1,17,-45,183,228,197,-779,2075,1739,3351,-6935,8840,2935,28289,-46617,73908,
  77984. -1,16,-49,176,228,153,-848,2057,1644,3004,-7271,9139,2037,26482,-48390,73415,
  77985. -2,14,-53,169,227,111,-919,2032,1535,2663,-7597,9389,1082,24694,-50137,72835,
  77986. -2,13,-58,161,224,72,-991,2001,1414,2330,-7910,9592,70,22929,-51853,72169,
  77987. -2,11,-63,154,221,36,-1064,1962,1280,2006,-8209,9750,-998,21189,-53534,71420,
  77988. -2,10,-68,147,215,2,-1137,1919,1131,1692,-8491,9863,-2122,19478,-55178,70590,
  77989. -3,9,-73,139,208,-29,-1210,1870,970,1388,-8755,9935,-3300,17799,-56778,69679,
  77990. -3,8,-79,132,200,-57,-1283,1817,794,1095,-8998,9966,-4533,16155,-58333,68692,
  77991. -4,7,-85,125,189,-83,-1356,1759,605,814,-9219,9959,-5818,14548,-59838,67629,
  77992. -4,7,-91,117,177,-106,-1428,1698,402,545,-9416,9916,-7154,12980,-61289,66494,
  77993. -5,6,-97,111,163,-127,-1498,1634,185,288,-9585,9838,-8540,11455,-62684,65290
  77994. };
  77995. float *zlin = lins + 15*64;
  77996. const float *w = g_win;
  77997. zlin[4*15] = xl[18*16];
  77998. zlin[4*15 + 1] = xr[18*16];
  77999. zlin[4*15 + 2] = xl[0];
  78000. zlin[4*15 + 3] = xr[0];
  78001. zlin[4*31] = xl[1 + 18*16];
  78002. zlin[4*31 + 1] = xr[1 + 18*16];
  78003. zlin[4*31 + 2] = xl[1];
  78004. zlin[4*31 + 3] = xr[1];
  78005. drmp3d_synth_pair(dstr, nch, lins + 4*15 + 1);
  78006. drmp3d_synth_pair(dstr + 32*nch, nch, lins + 4*15 + 64 + 1);
  78007. drmp3d_synth_pair(dstl, nch, lins + 4*15);
  78008. drmp3d_synth_pair(dstl + 32*nch, nch, lins + 4*15 + 64);
  78009. #if DRMP3_HAVE_SIMD
  78010. if (drmp3_have_simd()) for (i = 14; i >= 0; i--)
  78011. {
  78012. #define DRMP3_VLOAD(k) drmp3_f4 w0 = DRMP3_VSET(*w++); drmp3_f4 w1 = DRMP3_VSET(*w++); drmp3_f4 vz = DRMP3_VLD(&zlin[4*i - 64*k]); drmp3_f4 vy = DRMP3_VLD(&zlin[4*i - 64*(15 - k)]);
  78013. #define DRMP3_V0(k) { DRMP3_VLOAD(k) b = DRMP3_VADD(DRMP3_VMUL(vz, w1), DRMP3_VMUL(vy, w0)) ; a = DRMP3_VSUB(DRMP3_VMUL(vz, w0), DRMP3_VMUL(vy, w1)); }
  78014. #define DRMP3_V1(k) { DRMP3_VLOAD(k) b = DRMP3_VADD(b, DRMP3_VADD(DRMP3_VMUL(vz, w1), DRMP3_VMUL(vy, w0))); a = DRMP3_VADD(a, DRMP3_VSUB(DRMP3_VMUL(vz, w0), DRMP3_VMUL(vy, w1))); }
  78015. #define DRMP3_V2(k) { DRMP3_VLOAD(k) b = DRMP3_VADD(b, DRMP3_VADD(DRMP3_VMUL(vz, w1), DRMP3_VMUL(vy, w0))); a = DRMP3_VADD(a, DRMP3_VSUB(DRMP3_VMUL(vy, w1), DRMP3_VMUL(vz, w0))); }
  78016. drmp3_f4 a, b;
  78017. zlin[4*i] = xl[18*(31 - i)];
  78018. zlin[4*i + 1] = xr[18*(31 - i)];
  78019. zlin[4*i + 2] = xl[1 + 18*(31 - i)];
  78020. zlin[4*i + 3] = xr[1 + 18*(31 - i)];
  78021. zlin[4*i + 64] = xl[1 + 18*(1 + i)];
  78022. zlin[4*i + 64 + 1] = xr[1 + 18*(1 + i)];
  78023. zlin[4*i - 64 + 2] = xl[18*(1 + i)];
  78024. zlin[4*i - 64 + 3] = xr[18*(1 + i)];
  78025. DRMP3_V0(0) DRMP3_V2(1) DRMP3_V1(2) DRMP3_V2(3) DRMP3_V1(4) DRMP3_V2(5) DRMP3_V1(6) DRMP3_V2(7)
  78026. {
  78027. #ifndef DR_MP3_FLOAT_OUTPUT
  78028. #if DRMP3_HAVE_SSE
  78029. static const drmp3_f4 g_max = { 32767.0f, 32767.0f, 32767.0f, 32767.0f };
  78030. static const drmp3_f4 g_min = { -32768.0f, -32768.0f, -32768.0f, -32768.0f };
  78031. __m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, g_max), g_min)),
  78032. _mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, g_max), g_min)));
  78033. dstr[(15 - i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 1);
  78034. dstr[(17 + i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 5);
  78035. dstl[(15 - i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 0);
  78036. dstl[(17 + i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 4);
  78037. dstr[(47 - i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 3);
  78038. dstr[(49 + i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 7);
  78039. dstl[(47 - i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 2);
  78040. dstl[(49 + i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 6);
  78041. #else
  78042. int16x4_t pcma, pcmb;
  78043. a = DRMP3_VADD(a, DRMP3_VSET(0.5f));
  78044. b = DRMP3_VADD(b, DRMP3_VSET(0.5f));
  78045. pcma = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(a), vreinterpretq_s32_u32(vcltq_f32(a, DRMP3_VSET(0)))));
  78046. pcmb = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(b), vreinterpretq_s32_u32(vcltq_f32(b, DRMP3_VSET(0)))));
  78047. vst1_lane_s16(dstr + (15 - i)*nch, pcma, 1);
  78048. vst1_lane_s16(dstr + (17 + i)*nch, pcmb, 1);
  78049. vst1_lane_s16(dstl + (15 - i)*nch, pcma, 0);
  78050. vst1_lane_s16(dstl + (17 + i)*nch, pcmb, 0);
  78051. vst1_lane_s16(dstr + (47 - i)*nch, pcma, 3);
  78052. vst1_lane_s16(dstr + (49 + i)*nch, pcmb, 3);
  78053. vst1_lane_s16(dstl + (47 - i)*nch, pcma, 2);
  78054. vst1_lane_s16(dstl + (49 + i)*nch, pcmb, 2);
  78055. #endif
  78056. #else
  78057. #if DRMP3_HAVE_SSE
  78058. static const drmp3_f4 g_scale = { 1.0f/32768.0f, 1.0f/32768.0f, 1.0f/32768.0f, 1.0f/32768.0f };
  78059. #else
  78060. const drmp3_f4 g_scale = vdupq_n_f32(1.0f/32768.0f);
  78061. #endif
  78062. a = DRMP3_VMUL(a, g_scale);
  78063. b = DRMP3_VMUL(b, g_scale);
  78064. #if DRMP3_HAVE_SSE
  78065. _mm_store_ss(dstr + (15 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1)));
  78066. _mm_store_ss(dstr + (17 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(1, 1, 1, 1)));
  78067. _mm_store_ss(dstl + (15 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)));
  78068. _mm_store_ss(dstl + (17 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(0, 0, 0, 0)));
  78069. _mm_store_ss(dstr + (47 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 3, 3, 3)));
  78070. _mm_store_ss(dstr + (49 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 3, 3, 3)));
  78071. _mm_store_ss(dstl + (47 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2)));
  78072. _mm_store_ss(dstl + (49 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(2, 2, 2, 2)));
  78073. #else
  78074. vst1q_lane_f32(dstr + (15 - i)*nch, a, 1);
  78075. vst1q_lane_f32(dstr + (17 + i)*nch, b, 1);
  78076. vst1q_lane_f32(dstl + (15 - i)*nch, a, 0);
  78077. vst1q_lane_f32(dstl + (17 + i)*nch, b, 0);
  78078. vst1q_lane_f32(dstr + (47 - i)*nch, a, 3);
  78079. vst1q_lane_f32(dstr + (49 + i)*nch, b, 3);
  78080. vst1q_lane_f32(dstl + (47 - i)*nch, a, 2);
  78081. vst1q_lane_f32(dstl + (49 + i)*nch, b, 2);
  78082. #endif
  78083. #endif
  78084. }
  78085. } else
  78086. #endif
  78087. #ifdef DR_MP3_ONLY_SIMD
  78088. {}
  78089. #else
  78090. for (i = 14; i >= 0; i--)
  78091. {
  78092. #define DRMP3_LOAD(k) float w0 = *w++; float w1 = *w++; float *vz = &zlin[4*i - k*64]; float *vy = &zlin[4*i - (15 - k)*64];
  78093. #define DRMP3_S0(k) { int j; DRMP3_LOAD(k); for (j = 0; j < 4; j++) b[j] = vz[j]*w1 + vy[j]*w0, a[j] = vz[j]*w0 - vy[j]*w1; }
  78094. #define DRMP3_S1(k) { int j; DRMP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vz[j]*w0 - vy[j]*w1; }
  78095. #define DRMP3_S2(k) { int j; DRMP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vy[j]*w1 - vz[j]*w0; }
  78096. float a[4], b[4];
  78097. zlin[4*i] = xl[18*(31 - i)];
  78098. zlin[4*i + 1] = xr[18*(31 - i)];
  78099. zlin[4*i + 2] = xl[1 + 18*(31 - i)];
  78100. zlin[4*i + 3] = xr[1 + 18*(31 - i)];
  78101. zlin[4*(i + 16)] = xl[1 + 18*(1 + i)];
  78102. zlin[4*(i + 16) + 1] = xr[1 + 18*(1 + i)];
  78103. zlin[4*(i - 16) + 2] = xl[18*(1 + i)];
  78104. zlin[4*(i - 16) + 3] = xr[18*(1 + i)];
  78105. DRMP3_S0(0) DRMP3_S2(1) DRMP3_S1(2) DRMP3_S2(3) DRMP3_S1(4) DRMP3_S2(5) DRMP3_S1(6) DRMP3_S2(7)
  78106. dstr[(15 - i)*nch] = drmp3d_scale_pcm(a[1]);
  78107. dstr[(17 + i)*nch] = drmp3d_scale_pcm(b[1]);
  78108. dstl[(15 - i)*nch] = drmp3d_scale_pcm(a[0]);
  78109. dstl[(17 + i)*nch] = drmp3d_scale_pcm(b[0]);
  78110. dstr[(47 - i)*nch] = drmp3d_scale_pcm(a[3]);
  78111. dstr[(49 + i)*nch] = drmp3d_scale_pcm(b[3]);
  78112. dstl[(47 - i)*nch] = drmp3d_scale_pcm(a[2]);
  78113. dstl[(49 + i)*nch] = drmp3d_scale_pcm(b[2]);
  78114. }
  78115. #endif
  78116. }
  78117. static void drmp3d_synth_granule(float *qmf_state, float *grbuf, int nbands, int nch, drmp3d_sample_t *pcm, float *lins)
  78118. {
  78119. int i;
  78120. for (i = 0; i < nch; i++)
  78121. {
  78122. drmp3d_DCT_II(grbuf + 576*i, nbands);
  78123. }
  78124. DRMP3_COPY_MEMORY(lins, qmf_state, sizeof(float)*15*64);
  78125. for (i = 0; i < nbands; i += 2)
  78126. {
  78127. drmp3d_synth(grbuf + i, pcm + 32*nch*i, nch, lins + i*64);
  78128. }
  78129. #ifndef DR_MP3_NONSTANDARD_BUT_LOGICAL
  78130. if (nch == 1)
  78131. {
  78132. for (i = 0; i < 15*64; i += 2)
  78133. {
  78134. qmf_state[i] = lins[nbands*64 + i];
  78135. }
  78136. } else
  78137. #endif
  78138. {
  78139. DRMP3_COPY_MEMORY(qmf_state, lins + nbands*64, sizeof(float)*15*64);
  78140. }
  78141. }
  78142. static int drmp3d_match_frame(const drmp3_uint8 *hdr, int mp3_bytes, int frame_bytes)
  78143. {
  78144. int i, nmatch;
  78145. for (i = 0, nmatch = 0; nmatch < DRMP3_MAX_FRAME_SYNC_MATCHES; nmatch++)
  78146. {
  78147. i += drmp3_hdr_frame_bytes(hdr + i, frame_bytes) + drmp3_hdr_padding(hdr + i);
  78148. if (i + DRMP3_HDR_SIZE > mp3_bytes)
  78149. return nmatch > 0;
  78150. if (!drmp3_hdr_compare(hdr, hdr + i))
  78151. return 0;
  78152. }
  78153. return 1;
  78154. }
  78155. static int drmp3d_find_frame(const drmp3_uint8 *mp3, int mp3_bytes, int *free_format_bytes, int *ptr_frame_bytes)
  78156. {
  78157. int i, k;
  78158. for (i = 0; i < mp3_bytes - DRMP3_HDR_SIZE; i++, mp3++)
  78159. {
  78160. if (drmp3_hdr_valid(mp3))
  78161. {
  78162. int frame_bytes = drmp3_hdr_frame_bytes(mp3, *free_format_bytes);
  78163. int frame_and_padding = frame_bytes + drmp3_hdr_padding(mp3);
  78164. for (k = DRMP3_HDR_SIZE; !frame_bytes && k < DRMP3_MAX_FREE_FORMAT_FRAME_SIZE && i + 2*k < mp3_bytes - DRMP3_HDR_SIZE; k++)
  78165. {
  78166. if (drmp3_hdr_compare(mp3, mp3 + k))
  78167. {
  78168. int fb = k - drmp3_hdr_padding(mp3);
  78169. int nextfb = fb + drmp3_hdr_padding(mp3 + k);
  78170. if (i + k + nextfb + DRMP3_HDR_SIZE > mp3_bytes || !drmp3_hdr_compare(mp3, mp3 + k + nextfb))
  78171. continue;
  78172. frame_and_padding = k;
  78173. frame_bytes = fb;
  78174. *free_format_bytes = fb;
  78175. }
  78176. }
  78177. if ((frame_bytes && i + frame_and_padding <= mp3_bytes &&
  78178. drmp3d_match_frame(mp3, mp3_bytes - i, frame_bytes)) ||
  78179. (!i && frame_and_padding == mp3_bytes))
  78180. {
  78181. *ptr_frame_bytes = frame_and_padding;
  78182. return i;
  78183. }
  78184. *free_format_bytes = 0;
  78185. }
  78186. }
  78187. *ptr_frame_bytes = 0;
  78188. return mp3_bytes;
  78189. }
  78190. DRMP3_API void drmp3dec_init(drmp3dec *dec)
  78191. {
  78192. dec->header[0] = 0;
  78193. }
  78194. DRMP3_API int drmp3dec_decode_frame(drmp3dec *dec, const drmp3_uint8 *mp3, int mp3_bytes, void *pcm, drmp3dec_frame_info *info)
  78195. {
  78196. int i = 0, igr, frame_size = 0, success = 1;
  78197. const drmp3_uint8 *hdr;
  78198. drmp3_bs bs_frame[1];
  78199. drmp3dec_scratch scratch;
  78200. if (mp3_bytes > 4 && dec->header[0] == 0xff && drmp3_hdr_compare(dec->header, mp3))
  78201. {
  78202. frame_size = drmp3_hdr_frame_bytes(mp3, dec->free_format_bytes) + drmp3_hdr_padding(mp3);
  78203. if (frame_size != mp3_bytes && (frame_size + DRMP3_HDR_SIZE > mp3_bytes || !drmp3_hdr_compare(mp3, mp3 + frame_size)))
  78204. {
  78205. frame_size = 0;
  78206. }
  78207. }
  78208. if (!frame_size)
  78209. {
  78210. DRMP3_ZERO_MEMORY(dec, sizeof(drmp3dec));
  78211. i = drmp3d_find_frame(mp3, mp3_bytes, &dec->free_format_bytes, &frame_size);
  78212. if (!frame_size || i + frame_size > mp3_bytes)
  78213. {
  78214. info->frame_bytes = i;
  78215. return 0;
  78216. }
  78217. }
  78218. hdr = mp3 + i;
  78219. DRMP3_COPY_MEMORY(dec->header, hdr, DRMP3_HDR_SIZE);
  78220. info->frame_bytes = i + frame_size;
  78221. info->channels = DRMP3_HDR_IS_MONO(hdr) ? 1 : 2;
  78222. info->hz = drmp3_hdr_sample_rate_hz(hdr);
  78223. info->layer = 4 - DRMP3_HDR_GET_LAYER(hdr);
  78224. info->bitrate_kbps = drmp3_hdr_bitrate_kbps(hdr);
  78225. drmp3_bs_init(bs_frame, hdr + DRMP3_HDR_SIZE, frame_size - DRMP3_HDR_SIZE);
  78226. if (DRMP3_HDR_IS_CRC(hdr))
  78227. {
  78228. drmp3_bs_get_bits(bs_frame, 16);
  78229. }
  78230. if (info->layer == 3)
  78231. {
  78232. int main_data_begin = drmp3_L3_read_side_info(bs_frame, scratch.gr_info, hdr);
  78233. if (main_data_begin < 0 || bs_frame->pos > bs_frame->limit)
  78234. {
  78235. drmp3dec_init(dec);
  78236. return 0;
  78237. }
  78238. success = drmp3_L3_restore_reservoir(dec, bs_frame, &scratch, main_data_begin);
  78239. if (success && pcm != NULL)
  78240. {
  78241. for (igr = 0; igr < (DRMP3_HDR_TEST_MPEG1(hdr) ? 2 : 1); igr++, pcm = DRMP3_OFFSET_PTR(pcm, sizeof(drmp3d_sample_t)*576*info->channels))
  78242. {
  78243. DRMP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float));
  78244. drmp3_L3_decode(dec, &scratch, scratch.gr_info + igr*info->channels, info->channels);
  78245. drmp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 18, info->channels, (drmp3d_sample_t*)pcm, scratch.syn[0]);
  78246. }
  78247. }
  78248. drmp3_L3_save_reservoir(dec, &scratch);
  78249. } else
  78250. {
  78251. #ifdef DR_MP3_ONLY_MP3
  78252. return 0;
  78253. #else
  78254. drmp3_L12_scale_info sci[1];
  78255. if (pcm == NULL) {
  78256. return drmp3_hdr_frame_samples(hdr);
  78257. }
  78258. drmp3_L12_read_scale_info(hdr, bs_frame, sci);
  78259. DRMP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float));
  78260. for (i = 0, igr = 0; igr < 3; igr++)
  78261. {
  78262. if (12 == (i += drmp3_L12_dequantize_granule(scratch.grbuf[0] + i, bs_frame, sci, info->layer | 1)))
  78263. {
  78264. i = 0;
  78265. drmp3_L12_apply_scf_384(sci, sci->scf + igr, scratch.grbuf[0]);
  78266. drmp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 12, info->channels, (drmp3d_sample_t*)pcm, scratch.syn[0]);
  78267. DRMP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float));
  78268. pcm = DRMP3_OFFSET_PTR(pcm, sizeof(drmp3d_sample_t)*384*info->channels);
  78269. }
  78270. if (bs_frame->pos > bs_frame->limit)
  78271. {
  78272. drmp3dec_init(dec);
  78273. return 0;
  78274. }
  78275. }
  78276. #endif
  78277. }
  78278. return success*drmp3_hdr_frame_samples(dec->header);
  78279. }
  78280. DRMP3_API void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, size_t num_samples)
  78281. {
  78282. size_t i = 0;
  78283. #if DRMP3_HAVE_SIMD
  78284. size_t aligned_count = num_samples & ~7;
  78285. for(; i < aligned_count; i+=8)
  78286. {
  78287. drmp3_f4 scale = DRMP3_VSET(32768.0f);
  78288. drmp3_f4 a = DRMP3_VMUL(DRMP3_VLD(&in[i ]), scale);
  78289. drmp3_f4 b = DRMP3_VMUL(DRMP3_VLD(&in[i+4]), scale);
  78290. #if DRMP3_HAVE_SSE
  78291. drmp3_f4 s16max = DRMP3_VSET( 32767.0f);
  78292. drmp3_f4 s16min = DRMP3_VSET(-32768.0f);
  78293. __m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, s16max), s16min)),
  78294. _mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, s16max), s16min)));
  78295. out[i ] = (drmp3_int16)_mm_extract_epi16(pcm8, 0);
  78296. out[i+1] = (drmp3_int16)_mm_extract_epi16(pcm8, 1);
  78297. out[i+2] = (drmp3_int16)_mm_extract_epi16(pcm8, 2);
  78298. out[i+3] = (drmp3_int16)_mm_extract_epi16(pcm8, 3);
  78299. out[i+4] = (drmp3_int16)_mm_extract_epi16(pcm8, 4);
  78300. out[i+5] = (drmp3_int16)_mm_extract_epi16(pcm8, 5);
  78301. out[i+6] = (drmp3_int16)_mm_extract_epi16(pcm8, 6);
  78302. out[i+7] = (drmp3_int16)_mm_extract_epi16(pcm8, 7);
  78303. #else
  78304. int16x4_t pcma, pcmb;
  78305. a = DRMP3_VADD(a, DRMP3_VSET(0.5f));
  78306. b = DRMP3_VADD(b, DRMP3_VSET(0.5f));
  78307. pcma = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(a), vreinterpretq_s32_u32(vcltq_f32(a, DRMP3_VSET(0)))));
  78308. pcmb = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(b), vreinterpretq_s32_u32(vcltq_f32(b, DRMP3_VSET(0)))));
  78309. vst1_lane_s16(out+i , pcma, 0);
  78310. vst1_lane_s16(out+i+1, pcma, 1);
  78311. vst1_lane_s16(out+i+2, pcma, 2);
  78312. vst1_lane_s16(out+i+3, pcma, 3);
  78313. vst1_lane_s16(out+i+4, pcmb, 0);
  78314. vst1_lane_s16(out+i+5, pcmb, 1);
  78315. vst1_lane_s16(out+i+6, pcmb, 2);
  78316. vst1_lane_s16(out+i+7, pcmb, 3);
  78317. #endif
  78318. }
  78319. #endif
  78320. for(; i < num_samples; i++)
  78321. {
  78322. float sample = in[i] * 32768.0f;
  78323. if (sample >= 32766.5)
  78324. out[i] = (drmp3_int16) 32767;
  78325. else if (sample <= -32767.5)
  78326. out[i] = (drmp3_int16)-32768;
  78327. else
  78328. {
  78329. short s = (drmp3_int16)(sample + .5f);
  78330. s -= (s < 0);
  78331. out[i] = s;
  78332. }
  78333. }
  78334. }
  78335. #if defined(SIZE_MAX)
  78336. #define DRMP3_SIZE_MAX SIZE_MAX
  78337. #else
  78338. #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
  78339. #define DRMP3_SIZE_MAX ((drmp3_uint64)0xFFFFFFFFFFFFFFFF)
  78340. #else
  78341. #define DRMP3_SIZE_MAX 0xFFFFFFFF
  78342. #endif
  78343. #endif
  78344. #ifndef DRMP3_SEEK_LEADING_MP3_FRAMES
  78345. #define DRMP3_SEEK_LEADING_MP3_FRAMES 2
  78346. #endif
  78347. #define DRMP3_MIN_DATA_CHUNK_SIZE 16384
  78348. #ifndef DRMP3_DATA_CHUNK_SIZE
  78349. #define DRMP3_DATA_CHUNK_SIZE (DRMP3_MIN_DATA_CHUNK_SIZE*4)
  78350. #endif
  78351. #define DRMP3_COUNTOF(x) (sizeof(x) / sizeof(x[0]))
  78352. #define DRMP3_CLAMP(x, lo, hi) (DRMP3_MAX(lo, DRMP3_MIN(x, hi)))
  78353. #ifndef DRMP3_PI_D
  78354. #define DRMP3_PI_D 3.14159265358979323846264
  78355. #endif
  78356. #define DRMP3_DEFAULT_RESAMPLER_LPF_ORDER 2
  78357. static DRMP3_INLINE float drmp3_mix_f32(float x, float y, float a)
  78358. {
  78359. return x*(1-a) + y*a;
  78360. }
  78361. static DRMP3_INLINE float drmp3_mix_f32_fast(float x, float y, float a)
  78362. {
  78363. float r0 = (y - x);
  78364. float r1 = r0*a;
  78365. return x + r1;
  78366. }
  78367. static DRMP3_INLINE drmp3_uint32 drmp3_gcf_u32(drmp3_uint32 a, drmp3_uint32 b)
  78368. {
  78369. for (;;) {
  78370. if (b == 0) {
  78371. break;
  78372. } else {
  78373. drmp3_uint32 t = a;
  78374. a = b;
  78375. b = t % a;
  78376. }
  78377. }
  78378. return a;
  78379. }
  78380. static void* drmp3__malloc_default(size_t sz, void* pUserData)
  78381. {
  78382. (void)pUserData;
  78383. return DRMP3_MALLOC(sz);
  78384. }
  78385. static void* drmp3__realloc_default(void* p, size_t sz, void* pUserData)
  78386. {
  78387. (void)pUserData;
  78388. return DRMP3_REALLOC(p, sz);
  78389. }
  78390. static void drmp3__free_default(void* p, void* pUserData)
  78391. {
  78392. (void)pUserData;
  78393. DRMP3_FREE(p);
  78394. }
  78395. static void* drmp3__malloc_from_callbacks(size_t sz, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78396. {
  78397. if (pAllocationCallbacks == NULL) {
  78398. return NULL;
  78399. }
  78400. if (pAllocationCallbacks->onMalloc != NULL) {
  78401. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  78402. }
  78403. if (pAllocationCallbacks->onRealloc != NULL) {
  78404. return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  78405. }
  78406. return NULL;
  78407. }
  78408. static void* drmp3__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78409. {
  78410. if (pAllocationCallbacks == NULL) {
  78411. return NULL;
  78412. }
  78413. if (pAllocationCallbacks->onRealloc != NULL) {
  78414. return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  78415. }
  78416. if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  78417. void* p2;
  78418. p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  78419. if (p2 == NULL) {
  78420. return NULL;
  78421. }
  78422. if (p != NULL) {
  78423. DRMP3_COPY_MEMORY(p2, p, szOld);
  78424. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  78425. }
  78426. return p2;
  78427. }
  78428. return NULL;
  78429. }
  78430. static void drmp3__free_from_callbacks(void* p, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78431. {
  78432. if (p == NULL || pAllocationCallbacks == NULL) {
  78433. return;
  78434. }
  78435. if (pAllocationCallbacks->onFree != NULL) {
  78436. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  78437. }
  78438. }
  78439. static drmp3_allocation_callbacks drmp3_copy_allocation_callbacks_or_defaults(const drmp3_allocation_callbacks* pAllocationCallbacks)
  78440. {
  78441. if (pAllocationCallbacks != NULL) {
  78442. return *pAllocationCallbacks;
  78443. } else {
  78444. drmp3_allocation_callbacks allocationCallbacks;
  78445. allocationCallbacks.pUserData = NULL;
  78446. allocationCallbacks.onMalloc = drmp3__malloc_default;
  78447. allocationCallbacks.onRealloc = drmp3__realloc_default;
  78448. allocationCallbacks.onFree = drmp3__free_default;
  78449. return allocationCallbacks;
  78450. }
  78451. }
  78452. static size_t drmp3__on_read(drmp3* pMP3, void* pBufferOut, size_t bytesToRead)
  78453. {
  78454. size_t bytesRead = pMP3->onRead(pMP3->pUserData, pBufferOut, bytesToRead);
  78455. pMP3->streamCursor += bytesRead;
  78456. return bytesRead;
  78457. }
  78458. static drmp3_bool32 drmp3__on_seek(drmp3* pMP3, int offset, drmp3_seek_origin origin)
  78459. {
  78460. DRMP3_ASSERT(offset >= 0);
  78461. if (!pMP3->onSeek(pMP3->pUserData, offset, origin)) {
  78462. return DRMP3_FALSE;
  78463. }
  78464. if (origin == drmp3_seek_origin_start) {
  78465. pMP3->streamCursor = (drmp3_uint64)offset;
  78466. } else {
  78467. pMP3->streamCursor += offset;
  78468. }
  78469. return DRMP3_TRUE;
  78470. }
  78471. static drmp3_bool32 drmp3__on_seek_64(drmp3* pMP3, drmp3_uint64 offset, drmp3_seek_origin origin)
  78472. {
  78473. if (offset <= 0x7FFFFFFF) {
  78474. return drmp3__on_seek(pMP3, (int)offset, origin);
  78475. }
  78476. if (!drmp3__on_seek(pMP3, 0x7FFFFFFF, drmp3_seek_origin_start)) {
  78477. return DRMP3_FALSE;
  78478. }
  78479. offset -= 0x7FFFFFFF;
  78480. while (offset > 0) {
  78481. if (offset <= 0x7FFFFFFF) {
  78482. if (!drmp3__on_seek(pMP3, (int)offset, drmp3_seek_origin_current)) {
  78483. return DRMP3_FALSE;
  78484. }
  78485. offset = 0;
  78486. } else {
  78487. if (!drmp3__on_seek(pMP3, 0x7FFFFFFF, drmp3_seek_origin_current)) {
  78488. return DRMP3_FALSE;
  78489. }
  78490. offset -= 0x7FFFFFFF;
  78491. }
  78492. }
  78493. return DRMP3_TRUE;
  78494. }
  78495. static drmp3_uint32 drmp3_decode_next_frame_ex__callbacks(drmp3* pMP3, drmp3d_sample_t* pPCMFrames)
  78496. {
  78497. drmp3_uint32 pcmFramesRead = 0;
  78498. DRMP3_ASSERT(pMP3 != NULL);
  78499. DRMP3_ASSERT(pMP3->onRead != NULL);
  78500. if (pMP3->atEnd) {
  78501. return 0;
  78502. }
  78503. for (;;) {
  78504. drmp3dec_frame_info info;
  78505. if (pMP3->dataSize < DRMP3_MIN_DATA_CHUNK_SIZE) {
  78506. size_t bytesRead;
  78507. if (pMP3->pData != NULL) {
  78508. DRMP3_MOVE_MEMORY(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize);
  78509. }
  78510. pMP3->dataConsumed = 0;
  78511. if (pMP3->dataCapacity < DRMP3_DATA_CHUNK_SIZE) {
  78512. drmp3_uint8* pNewData;
  78513. size_t newDataCap;
  78514. newDataCap = DRMP3_DATA_CHUNK_SIZE;
  78515. pNewData = (drmp3_uint8*)drmp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks);
  78516. if (pNewData == NULL) {
  78517. return 0;
  78518. }
  78519. pMP3->pData = pNewData;
  78520. pMP3->dataCapacity = newDataCap;
  78521. }
  78522. bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize));
  78523. if (bytesRead == 0) {
  78524. if (pMP3->dataSize == 0) {
  78525. pMP3->atEnd = DRMP3_TRUE;
  78526. return 0;
  78527. }
  78528. }
  78529. pMP3->dataSize += bytesRead;
  78530. }
  78531. if (pMP3->dataSize > INT_MAX) {
  78532. pMP3->atEnd = DRMP3_TRUE;
  78533. return 0;
  78534. }
  78535. DRMP3_ASSERT(pMP3->pData != NULL);
  78536. DRMP3_ASSERT(pMP3->dataCapacity > 0);
  78537. pcmFramesRead = drmp3dec_decode_frame(&pMP3->decoder, pMP3->pData + pMP3->dataConsumed, (int)pMP3->dataSize, pPCMFrames, &info);
  78538. if (info.frame_bytes > 0) {
  78539. pMP3->dataConsumed += (size_t)info.frame_bytes;
  78540. pMP3->dataSize -= (size_t)info.frame_bytes;
  78541. }
  78542. if (pcmFramesRead > 0) {
  78543. pcmFramesRead = drmp3_hdr_frame_samples(pMP3->decoder.header);
  78544. pMP3->pcmFramesConsumedInMP3Frame = 0;
  78545. pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead;
  78546. pMP3->mp3FrameChannels = info.channels;
  78547. pMP3->mp3FrameSampleRate = info.hz;
  78548. break;
  78549. } else if (info.frame_bytes == 0) {
  78550. size_t bytesRead;
  78551. DRMP3_MOVE_MEMORY(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize);
  78552. pMP3->dataConsumed = 0;
  78553. if (pMP3->dataCapacity == pMP3->dataSize) {
  78554. drmp3_uint8* pNewData;
  78555. size_t newDataCap;
  78556. newDataCap = pMP3->dataCapacity + DRMP3_DATA_CHUNK_SIZE;
  78557. pNewData = (drmp3_uint8*)drmp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks);
  78558. if (pNewData == NULL) {
  78559. return 0;
  78560. }
  78561. pMP3->pData = pNewData;
  78562. pMP3->dataCapacity = newDataCap;
  78563. }
  78564. bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize));
  78565. if (bytesRead == 0) {
  78566. pMP3->atEnd = DRMP3_TRUE;
  78567. return 0;
  78568. }
  78569. pMP3->dataSize += bytesRead;
  78570. }
  78571. };
  78572. return pcmFramesRead;
  78573. }
  78574. static drmp3_uint32 drmp3_decode_next_frame_ex__memory(drmp3* pMP3, drmp3d_sample_t* pPCMFrames)
  78575. {
  78576. drmp3_uint32 pcmFramesRead = 0;
  78577. drmp3dec_frame_info info;
  78578. DRMP3_ASSERT(pMP3 != NULL);
  78579. DRMP3_ASSERT(pMP3->memory.pData != NULL);
  78580. if (pMP3->atEnd) {
  78581. return 0;
  78582. }
  78583. for (;;) {
  78584. pcmFramesRead = drmp3dec_decode_frame(&pMP3->decoder, pMP3->memory.pData + pMP3->memory.currentReadPos, (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos), pPCMFrames, &info);
  78585. if (pcmFramesRead > 0) {
  78586. pcmFramesRead = drmp3_hdr_frame_samples(pMP3->decoder.header);
  78587. pMP3->pcmFramesConsumedInMP3Frame = 0;
  78588. pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead;
  78589. pMP3->mp3FrameChannels = info.channels;
  78590. pMP3->mp3FrameSampleRate = info.hz;
  78591. break;
  78592. } else if (info.frame_bytes > 0) {
  78593. pMP3->memory.currentReadPos += (size_t)info.frame_bytes;
  78594. } else {
  78595. break;
  78596. }
  78597. }
  78598. pMP3->memory.currentReadPos += (size_t)info.frame_bytes;
  78599. return pcmFramesRead;
  78600. }
  78601. static drmp3_uint32 drmp3_decode_next_frame_ex(drmp3* pMP3, drmp3d_sample_t* pPCMFrames)
  78602. {
  78603. if (pMP3->memory.pData != NULL && pMP3->memory.dataSize > 0) {
  78604. return drmp3_decode_next_frame_ex__memory(pMP3, pPCMFrames);
  78605. } else {
  78606. return drmp3_decode_next_frame_ex__callbacks(pMP3, pPCMFrames);
  78607. }
  78608. }
  78609. static drmp3_uint32 drmp3_decode_next_frame(drmp3* pMP3)
  78610. {
  78611. DRMP3_ASSERT(pMP3 != NULL);
  78612. return drmp3_decode_next_frame_ex(pMP3, (drmp3d_sample_t*)pMP3->pcmFrames);
  78613. }
  78614. #if 0
  78615. static drmp3_uint32 drmp3_seek_next_frame(drmp3* pMP3)
  78616. {
  78617. drmp3_uint32 pcmFrameCount;
  78618. DRMP3_ASSERT(pMP3 != NULL);
  78619. pcmFrameCount = drmp3_decode_next_frame_ex(pMP3, NULL);
  78620. if (pcmFrameCount == 0) {
  78621. return 0;
  78622. }
  78623. pMP3->currentPCMFrame += pcmFrameCount;
  78624. pMP3->pcmFramesConsumedInMP3Frame = pcmFrameCount;
  78625. pMP3->pcmFramesRemainingInMP3Frame = 0;
  78626. return pcmFrameCount;
  78627. }
  78628. #endif
  78629. static drmp3_bool32 drmp3_init_internal(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78630. {
  78631. DRMP3_ASSERT(pMP3 != NULL);
  78632. DRMP3_ASSERT(onRead != NULL);
  78633. drmp3dec_init(&pMP3->decoder);
  78634. pMP3->onRead = onRead;
  78635. pMP3->onSeek = onSeek;
  78636. pMP3->pUserData = pUserData;
  78637. pMP3->allocationCallbacks = drmp3_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
  78638. if (pMP3->allocationCallbacks.onFree == NULL || (pMP3->allocationCallbacks.onMalloc == NULL && pMP3->allocationCallbacks.onRealloc == NULL)) {
  78639. return DRMP3_FALSE;
  78640. }
  78641. if (drmp3_decode_next_frame(pMP3) == 0) {
  78642. drmp3__free_from_callbacks(pMP3->pData, &pMP3->allocationCallbacks);
  78643. return DRMP3_FALSE;
  78644. }
  78645. pMP3->channels = pMP3->mp3FrameChannels;
  78646. pMP3->sampleRate = pMP3->mp3FrameSampleRate;
  78647. return DRMP3_TRUE;
  78648. }
  78649. DRMP3_API drmp3_bool32 drmp3_init(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78650. {
  78651. if (pMP3 == NULL || onRead == NULL) {
  78652. return DRMP3_FALSE;
  78653. }
  78654. DRMP3_ZERO_OBJECT(pMP3);
  78655. return drmp3_init_internal(pMP3, onRead, onSeek, pUserData, pAllocationCallbacks);
  78656. }
  78657. static size_t drmp3__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
  78658. {
  78659. drmp3* pMP3 = (drmp3*)pUserData;
  78660. size_t bytesRemaining;
  78661. DRMP3_ASSERT(pMP3 != NULL);
  78662. DRMP3_ASSERT(pMP3->memory.dataSize >= pMP3->memory.currentReadPos);
  78663. bytesRemaining = pMP3->memory.dataSize - pMP3->memory.currentReadPos;
  78664. if (bytesToRead > bytesRemaining) {
  78665. bytesToRead = bytesRemaining;
  78666. }
  78667. if (bytesToRead > 0) {
  78668. DRMP3_COPY_MEMORY(pBufferOut, pMP3->memory.pData + pMP3->memory.currentReadPos, bytesToRead);
  78669. pMP3->memory.currentReadPos += bytesToRead;
  78670. }
  78671. return bytesToRead;
  78672. }
  78673. static drmp3_bool32 drmp3__on_seek_memory(void* pUserData, int byteOffset, drmp3_seek_origin origin)
  78674. {
  78675. drmp3* pMP3 = (drmp3*)pUserData;
  78676. DRMP3_ASSERT(pMP3 != NULL);
  78677. if (origin == drmp3_seek_origin_current) {
  78678. if (byteOffset > 0) {
  78679. if (pMP3->memory.currentReadPos + byteOffset > pMP3->memory.dataSize) {
  78680. byteOffset = (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos);
  78681. }
  78682. } else {
  78683. if (pMP3->memory.currentReadPos < (size_t)-byteOffset) {
  78684. byteOffset = -(int)pMP3->memory.currentReadPos;
  78685. }
  78686. }
  78687. pMP3->memory.currentReadPos += byteOffset;
  78688. } else {
  78689. if ((drmp3_uint32)byteOffset <= pMP3->memory.dataSize) {
  78690. pMP3->memory.currentReadPos = byteOffset;
  78691. } else {
  78692. pMP3->memory.currentReadPos = pMP3->memory.dataSize;
  78693. }
  78694. }
  78695. return DRMP3_TRUE;
  78696. }
  78697. DRMP3_API drmp3_bool32 drmp3_init_memory(drmp3* pMP3, const void* pData, size_t dataSize, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78698. {
  78699. if (pMP3 == NULL) {
  78700. return DRMP3_FALSE;
  78701. }
  78702. DRMP3_ZERO_OBJECT(pMP3);
  78703. if (pData == NULL || dataSize == 0) {
  78704. return DRMP3_FALSE;
  78705. }
  78706. pMP3->memory.pData = (const drmp3_uint8*)pData;
  78707. pMP3->memory.dataSize = dataSize;
  78708. pMP3->memory.currentReadPos = 0;
  78709. return drmp3_init_internal(pMP3, drmp3__on_read_memory, drmp3__on_seek_memory, pMP3, pAllocationCallbacks);
  78710. }
  78711. #ifndef DR_MP3_NO_STDIO
  78712. #include <stdio.h>
  78713. #include <wchar.h>
  78714. #include <errno.h>
  78715. static drmp3_result drmp3_result_from_errno(int e)
  78716. {
  78717. switch (e)
  78718. {
  78719. case 0: return DRMP3_SUCCESS;
  78720. #ifdef EPERM
  78721. case EPERM: return DRMP3_INVALID_OPERATION;
  78722. #endif
  78723. #ifdef ENOENT
  78724. case ENOENT: return DRMP3_DOES_NOT_EXIST;
  78725. #endif
  78726. #ifdef ESRCH
  78727. case ESRCH: return DRMP3_DOES_NOT_EXIST;
  78728. #endif
  78729. #ifdef EINTR
  78730. case EINTR: return DRMP3_INTERRUPT;
  78731. #endif
  78732. #ifdef EIO
  78733. case EIO: return DRMP3_IO_ERROR;
  78734. #endif
  78735. #ifdef ENXIO
  78736. case ENXIO: return DRMP3_DOES_NOT_EXIST;
  78737. #endif
  78738. #ifdef E2BIG
  78739. case E2BIG: return DRMP3_INVALID_ARGS;
  78740. #endif
  78741. #ifdef ENOEXEC
  78742. case ENOEXEC: return DRMP3_INVALID_FILE;
  78743. #endif
  78744. #ifdef EBADF
  78745. case EBADF: return DRMP3_INVALID_FILE;
  78746. #endif
  78747. #ifdef ECHILD
  78748. case ECHILD: return DRMP3_ERROR;
  78749. #endif
  78750. #ifdef EAGAIN
  78751. case EAGAIN: return DRMP3_UNAVAILABLE;
  78752. #endif
  78753. #ifdef ENOMEM
  78754. case ENOMEM: return DRMP3_OUT_OF_MEMORY;
  78755. #endif
  78756. #ifdef EACCES
  78757. case EACCES: return DRMP3_ACCESS_DENIED;
  78758. #endif
  78759. #ifdef EFAULT
  78760. case EFAULT: return DRMP3_BAD_ADDRESS;
  78761. #endif
  78762. #ifdef ENOTBLK
  78763. case ENOTBLK: return DRMP3_ERROR;
  78764. #endif
  78765. #ifdef EBUSY
  78766. case EBUSY: return DRMP3_BUSY;
  78767. #endif
  78768. #ifdef EEXIST
  78769. case EEXIST: return DRMP3_ALREADY_EXISTS;
  78770. #endif
  78771. #ifdef EXDEV
  78772. case EXDEV: return DRMP3_ERROR;
  78773. #endif
  78774. #ifdef ENODEV
  78775. case ENODEV: return DRMP3_DOES_NOT_EXIST;
  78776. #endif
  78777. #ifdef ENOTDIR
  78778. case ENOTDIR: return DRMP3_NOT_DIRECTORY;
  78779. #endif
  78780. #ifdef EISDIR
  78781. case EISDIR: return DRMP3_IS_DIRECTORY;
  78782. #endif
  78783. #ifdef EINVAL
  78784. case EINVAL: return DRMP3_INVALID_ARGS;
  78785. #endif
  78786. #ifdef ENFILE
  78787. case ENFILE: return DRMP3_TOO_MANY_OPEN_FILES;
  78788. #endif
  78789. #ifdef EMFILE
  78790. case EMFILE: return DRMP3_TOO_MANY_OPEN_FILES;
  78791. #endif
  78792. #ifdef ENOTTY
  78793. case ENOTTY: return DRMP3_INVALID_OPERATION;
  78794. #endif
  78795. #ifdef ETXTBSY
  78796. case ETXTBSY: return DRMP3_BUSY;
  78797. #endif
  78798. #ifdef EFBIG
  78799. case EFBIG: return DRMP3_TOO_BIG;
  78800. #endif
  78801. #ifdef ENOSPC
  78802. case ENOSPC: return DRMP3_NO_SPACE;
  78803. #endif
  78804. #ifdef ESPIPE
  78805. case ESPIPE: return DRMP3_BAD_SEEK;
  78806. #endif
  78807. #ifdef EROFS
  78808. case EROFS: return DRMP3_ACCESS_DENIED;
  78809. #endif
  78810. #ifdef EMLINK
  78811. case EMLINK: return DRMP3_TOO_MANY_LINKS;
  78812. #endif
  78813. #ifdef EPIPE
  78814. case EPIPE: return DRMP3_BAD_PIPE;
  78815. #endif
  78816. #ifdef EDOM
  78817. case EDOM: return DRMP3_OUT_OF_RANGE;
  78818. #endif
  78819. #ifdef ERANGE
  78820. case ERANGE: return DRMP3_OUT_OF_RANGE;
  78821. #endif
  78822. #ifdef EDEADLK
  78823. case EDEADLK: return DRMP3_DEADLOCK;
  78824. #endif
  78825. #ifdef ENAMETOOLONG
  78826. case ENAMETOOLONG: return DRMP3_PATH_TOO_LONG;
  78827. #endif
  78828. #ifdef ENOLCK
  78829. case ENOLCK: return DRMP3_ERROR;
  78830. #endif
  78831. #ifdef ENOSYS
  78832. case ENOSYS: return DRMP3_NOT_IMPLEMENTED;
  78833. #endif
  78834. #ifdef ENOTEMPTY
  78835. case ENOTEMPTY: return DRMP3_DIRECTORY_NOT_EMPTY;
  78836. #endif
  78837. #ifdef ELOOP
  78838. case ELOOP: return DRMP3_TOO_MANY_LINKS;
  78839. #endif
  78840. #ifdef ENOMSG
  78841. case ENOMSG: return DRMP3_NO_MESSAGE;
  78842. #endif
  78843. #ifdef EIDRM
  78844. case EIDRM: return DRMP3_ERROR;
  78845. #endif
  78846. #ifdef ECHRNG
  78847. case ECHRNG: return DRMP3_ERROR;
  78848. #endif
  78849. #ifdef EL2NSYNC
  78850. case EL2NSYNC: return DRMP3_ERROR;
  78851. #endif
  78852. #ifdef EL3HLT
  78853. case EL3HLT: return DRMP3_ERROR;
  78854. #endif
  78855. #ifdef EL3RST
  78856. case EL3RST: return DRMP3_ERROR;
  78857. #endif
  78858. #ifdef ELNRNG
  78859. case ELNRNG: return DRMP3_OUT_OF_RANGE;
  78860. #endif
  78861. #ifdef EUNATCH
  78862. case EUNATCH: return DRMP3_ERROR;
  78863. #endif
  78864. #ifdef ENOCSI
  78865. case ENOCSI: return DRMP3_ERROR;
  78866. #endif
  78867. #ifdef EL2HLT
  78868. case EL2HLT: return DRMP3_ERROR;
  78869. #endif
  78870. #ifdef EBADE
  78871. case EBADE: return DRMP3_ERROR;
  78872. #endif
  78873. #ifdef EBADR
  78874. case EBADR: return DRMP3_ERROR;
  78875. #endif
  78876. #ifdef EXFULL
  78877. case EXFULL: return DRMP3_ERROR;
  78878. #endif
  78879. #ifdef ENOANO
  78880. case ENOANO: return DRMP3_ERROR;
  78881. #endif
  78882. #ifdef EBADRQC
  78883. case EBADRQC: return DRMP3_ERROR;
  78884. #endif
  78885. #ifdef EBADSLT
  78886. case EBADSLT: return DRMP3_ERROR;
  78887. #endif
  78888. #ifdef EBFONT
  78889. case EBFONT: return DRMP3_INVALID_FILE;
  78890. #endif
  78891. #ifdef ENOSTR
  78892. case ENOSTR: return DRMP3_ERROR;
  78893. #endif
  78894. #ifdef ENODATA
  78895. case ENODATA: return DRMP3_NO_DATA_AVAILABLE;
  78896. #endif
  78897. #ifdef ETIME
  78898. case ETIME: return DRMP3_TIMEOUT;
  78899. #endif
  78900. #ifdef ENOSR
  78901. case ENOSR: return DRMP3_NO_DATA_AVAILABLE;
  78902. #endif
  78903. #ifdef ENONET
  78904. case ENONET: return DRMP3_NO_NETWORK;
  78905. #endif
  78906. #ifdef ENOPKG
  78907. case ENOPKG: return DRMP3_ERROR;
  78908. #endif
  78909. #ifdef EREMOTE
  78910. case EREMOTE: return DRMP3_ERROR;
  78911. #endif
  78912. #ifdef ENOLINK
  78913. case ENOLINK: return DRMP3_ERROR;
  78914. #endif
  78915. #ifdef EADV
  78916. case EADV: return DRMP3_ERROR;
  78917. #endif
  78918. #ifdef ESRMNT
  78919. case ESRMNT: return DRMP3_ERROR;
  78920. #endif
  78921. #ifdef ECOMM
  78922. case ECOMM: return DRMP3_ERROR;
  78923. #endif
  78924. #ifdef EPROTO
  78925. case EPROTO: return DRMP3_ERROR;
  78926. #endif
  78927. #ifdef EMULTIHOP
  78928. case EMULTIHOP: return DRMP3_ERROR;
  78929. #endif
  78930. #ifdef EDOTDOT
  78931. case EDOTDOT: return DRMP3_ERROR;
  78932. #endif
  78933. #ifdef EBADMSG
  78934. case EBADMSG: return DRMP3_BAD_MESSAGE;
  78935. #endif
  78936. #ifdef EOVERFLOW
  78937. case EOVERFLOW: return DRMP3_TOO_BIG;
  78938. #endif
  78939. #ifdef ENOTUNIQ
  78940. case ENOTUNIQ: return DRMP3_NOT_UNIQUE;
  78941. #endif
  78942. #ifdef EBADFD
  78943. case EBADFD: return DRMP3_ERROR;
  78944. #endif
  78945. #ifdef EREMCHG
  78946. case EREMCHG: return DRMP3_ERROR;
  78947. #endif
  78948. #ifdef ELIBACC
  78949. case ELIBACC: return DRMP3_ACCESS_DENIED;
  78950. #endif
  78951. #ifdef ELIBBAD
  78952. case ELIBBAD: return DRMP3_INVALID_FILE;
  78953. #endif
  78954. #ifdef ELIBSCN
  78955. case ELIBSCN: return DRMP3_INVALID_FILE;
  78956. #endif
  78957. #ifdef ELIBMAX
  78958. case ELIBMAX: return DRMP3_ERROR;
  78959. #endif
  78960. #ifdef ELIBEXEC
  78961. case ELIBEXEC: return DRMP3_ERROR;
  78962. #endif
  78963. #ifdef EILSEQ
  78964. case EILSEQ: return DRMP3_INVALID_DATA;
  78965. #endif
  78966. #ifdef ERESTART
  78967. case ERESTART: return DRMP3_ERROR;
  78968. #endif
  78969. #ifdef ESTRPIPE
  78970. case ESTRPIPE: return DRMP3_ERROR;
  78971. #endif
  78972. #ifdef EUSERS
  78973. case EUSERS: return DRMP3_ERROR;
  78974. #endif
  78975. #ifdef ENOTSOCK
  78976. case ENOTSOCK: return DRMP3_NOT_SOCKET;
  78977. #endif
  78978. #ifdef EDESTADDRREQ
  78979. case EDESTADDRREQ: return DRMP3_NO_ADDRESS;
  78980. #endif
  78981. #ifdef EMSGSIZE
  78982. case EMSGSIZE: return DRMP3_TOO_BIG;
  78983. #endif
  78984. #ifdef EPROTOTYPE
  78985. case EPROTOTYPE: return DRMP3_BAD_PROTOCOL;
  78986. #endif
  78987. #ifdef ENOPROTOOPT
  78988. case ENOPROTOOPT: return DRMP3_PROTOCOL_UNAVAILABLE;
  78989. #endif
  78990. #ifdef EPROTONOSUPPORT
  78991. case EPROTONOSUPPORT: return DRMP3_PROTOCOL_NOT_SUPPORTED;
  78992. #endif
  78993. #ifdef ESOCKTNOSUPPORT
  78994. case ESOCKTNOSUPPORT: return DRMP3_SOCKET_NOT_SUPPORTED;
  78995. #endif
  78996. #ifdef EOPNOTSUPP
  78997. case EOPNOTSUPP: return DRMP3_INVALID_OPERATION;
  78998. #endif
  78999. #ifdef EPFNOSUPPORT
  79000. case EPFNOSUPPORT: return DRMP3_PROTOCOL_FAMILY_NOT_SUPPORTED;
  79001. #endif
  79002. #ifdef EAFNOSUPPORT
  79003. case EAFNOSUPPORT: return DRMP3_ADDRESS_FAMILY_NOT_SUPPORTED;
  79004. #endif
  79005. #ifdef EADDRINUSE
  79006. case EADDRINUSE: return DRMP3_ALREADY_IN_USE;
  79007. #endif
  79008. #ifdef EADDRNOTAVAIL
  79009. case EADDRNOTAVAIL: return DRMP3_ERROR;
  79010. #endif
  79011. #ifdef ENETDOWN
  79012. case ENETDOWN: return DRMP3_NO_NETWORK;
  79013. #endif
  79014. #ifdef ENETUNREACH
  79015. case ENETUNREACH: return DRMP3_NO_NETWORK;
  79016. #endif
  79017. #ifdef ENETRESET
  79018. case ENETRESET: return DRMP3_NO_NETWORK;
  79019. #endif
  79020. #ifdef ECONNABORTED
  79021. case ECONNABORTED: return DRMP3_NO_NETWORK;
  79022. #endif
  79023. #ifdef ECONNRESET
  79024. case ECONNRESET: return DRMP3_CONNECTION_RESET;
  79025. #endif
  79026. #ifdef ENOBUFS
  79027. case ENOBUFS: return DRMP3_NO_SPACE;
  79028. #endif
  79029. #ifdef EISCONN
  79030. case EISCONN: return DRMP3_ALREADY_CONNECTED;
  79031. #endif
  79032. #ifdef ENOTCONN
  79033. case ENOTCONN: return DRMP3_NOT_CONNECTED;
  79034. #endif
  79035. #ifdef ESHUTDOWN
  79036. case ESHUTDOWN: return DRMP3_ERROR;
  79037. #endif
  79038. #ifdef ETOOMANYREFS
  79039. case ETOOMANYREFS: return DRMP3_ERROR;
  79040. #endif
  79041. #ifdef ETIMEDOUT
  79042. case ETIMEDOUT: return DRMP3_TIMEOUT;
  79043. #endif
  79044. #ifdef ECONNREFUSED
  79045. case ECONNREFUSED: return DRMP3_CONNECTION_REFUSED;
  79046. #endif
  79047. #ifdef EHOSTDOWN
  79048. case EHOSTDOWN: return DRMP3_NO_HOST;
  79049. #endif
  79050. #ifdef EHOSTUNREACH
  79051. case EHOSTUNREACH: return DRMP3_NO_HOST;
  79052. #endif
  79053. #ifdef EALREADY
  79054. case EALREADY: return DRMP3_IN_PROGRESS;
  79055. #endif
  79056. #ifdef EINPROGRESS
  79057. case EINPROGRESS: return DRMP3_IN_PROGRESS;
  79058. #endif
  79059. #ifdef ESTALE
  79060. case ESTALE: return DRMP3_INVALID_FILE;
  79061. #endif
  79062. #ifdef EUCLEAN
  79063. case EUCLEAN: return DRMP3_ERROR;
  79064. #endif
  79065. #ifdef ENOTNAM
  79066. case ENOTNAM: return DRMP3_ERROR;
  79067. #endif
  79068. #ifdef ENAVAIL
  79069. case ENAVAIL: return DRMP3_ERROR;
  79070. #endif
  79071. #ifdef EISNAM
  79072. case EISNAM: return DRMP3_ERROR;
  79073. #endif
  79074. #ifdef EREMOTEIO
  79075. case EREMOTEIO: return DRMP3_IO_ERROR;
  79076. #endif
  79077. #ifdef EDQUOT
  79078. case EDQUOT: return DRMP3_NO_SPACE;
  79079. #endif
  79080. #ifdef ENOMEDIUM
  79081. case ENOMEDIUM: return DRMP3_DOES_NOT_EXIST;
  79082. #endif
  79083. #ifdef EMEDIUMTYPE
  79084. case EMEDIUMTYPE: return DRMP3_ERROR;
  79085. #endif
  79086. #ifdef ECANCELED
  79087. case ECANCELED: return DRMP3_CANCELLED;
  79088. #endif
  79089. #ifdef ENOKEY
  79090. case ENOKEY: return DRMP3_ERROR;
  79091. #endif
  79092. #ifdef EKEYEXPIRED
  79093. case EKEYEXPIRED: return DRMP3_ERROR;
  79094. #endif
  79095. #ifdef EKEYREVOKED
  79096. case EKEYREVOKED: return DRMP3_ERROR;
  79097. #endif
  79098. #ifdef EKEYREJECTED
  79099. case EKEYREJECTED: return DRMP3_ERROR;
  79100. #endif
  79101. #ifdef EOWNERDEAD
  79102. case EOWNERDEAD: return DRMP3_ERROR;
  79103. #endif
  79104. #ifdef ENOTRECOVERABLE
  79105. case ENOTRECOVERABLE: return DRMP3_ERROR;
  79106. #endif
  79107. #ifdef ERFKILL
  79108. case ERFKILL: return DRMP3_ERROR;
  79109. #endif
  79110. #ifdef EHWPOISON
  79111. case EHWPOISON: return DRMP3_ERROR;
  79112. #endif
  79113. default: return DRMP3_ERROR;
  79114. }
  79115. }
  79116. static drmp3_result drmp3_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  79117. {
  79118. #if defined(_MSC_VER) && _MSC_VER >= 1400
  79119. errno_t err;
  79120. #endif
  79121. if (ppFile != NULL) {
  79122. *ppFile = NULL;
  79123. }
  79124. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  79125. return DRMP3_INVALID_ARGS;
  79126. }
  79127. #if defined(_MSC_VER) && _MSC_VER >= 1400
  79128. err = fopen_s(ppFile, pFilePath, pOpenMode);
  79129. if (err != 0) {
  79130. return drmp3_result_from_errno(err);
  79131. }
  79132. #else
  79133. #if defined(_WIN32) || defined(__APPLE__)
  79134. *ppFile = fopen(pFilePath, pOpenMode);
  79135. #else
  79136. #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  79137. *ppFile = fopen64(pFilePath, pOpenMode);
  79138. #else
  79139. *ppFile = fopen(pFilePath, pOpenMode);
  79140. #endif
  79141. #endif
  79142. if (*ppFile == NULL) {
  79143. drmp3_result result = drmp3_result_from_errno(errno);
  79144. if (result == DRMP3_SUCCESS) {
  79145. result = DRMP3_ERROR;
  79146. }
  79147. return result;
  79148. }
  79149. #endif
  79150. return DRMP3_SUCCESS;
  79151. }
  79152. #if defined(_WIN32)
  79153. #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
  79154. #define DRMP3_HAS_WFOPEN
  79155. #endif
  79156. #endif
  79157. static drmp3_result drmp3_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79158. {
  79159. if (ppFile != NULL) {
  79160. *ppFile = NULL;
  79161. }
  79162. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  79163. return DRMP3_INVALID_ARGS;
  79164. }
  79165. #if defined(DRMP3_HAS_WFOPEN)
  79166. {
  79167. #if defined(_MSC_VER) && _MSC_VER >= 1400
  79168. errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  79169. if (err != 0) {
  79170. return drmp3_result_from_errno(err);
  79171. }
  79172. #else
  79173. *ppFile = _wfopen(pFilePath, pOpenMode);
  79174. if (*ppFile == NULL) {
  79175. return drmp3_result_from_errno(errno);
  79176. }
  79177. #endif
  79178. (void)pAllocationCallbacks;
  79179. }
  79180. #else
  79181. #if defined(__DJGPP__)
  79182. {
  79183. }
  79184. #else
  79185. {
  79186. mbstate_t mbs;
  79187. size_t lenMB;
  79188. const wchar_t* pFilePathTemp = pFilePath;
  79189. char* pFilePathMB = NULL;
  79190. char pOpenModeMB[32] = {0};
  79191. DRMP3_ZERO_OBJECT(&mbs);
  79192. lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  79193. if (lenMB == (size_t)-1) {
  79194. return drmp3_result_from_errno(errno);
  79195. }
  79196. pFilePathMB = (char*)drmp3__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
  79197. if (pFilePathMB == NULL) {
  79198. return DRMP3_OUT_OF_MEMORY;
  79199. }
  79200. pFilePathTemp = pFilePath;
  79201. DRMP3_ZERO_OBJECT(&mbs);
  79202. wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  79203. {
  79204. size_t i = 0;
  79205. for (;;) {
  79206. if (pOpenMode[i] == 0) {
  79207. pOpenModeMB[i] = '\0';
  79208. break;
  79209. }
  79210. pOpenModeMB[i] = (char)pOpenMode[i];
  79211. i += 1;
  79212. }
  79213. }
  79214. *ppFile = fopen(pFilePathMB, pOpenModeMB);
  79215. drmp3__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
  79216. }
  79217. #endif
  79218. if (*ppFile == NULL) {
  79219. return DRMP3_ERROR;
  79220. }
  79221. #endif
  79222. return DRMP3_SUCCESS;
  79223. }
  79224. static size_t drmp3__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead)
  79225. {
  79226. return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData);
  79227. }
  79228. static drmp3_bool32 drmp3__on_seek_stdio(void* pUserData, int offset, drmp3_seek_origin origin)
  79229. {
  79230. return fseek((FILE*)pUserData, offset, (origin == drmp3_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  79231. }
  79232. DRMP3_API drmp3_bool32 drmp3_init_file(drmp3* pMP3, const char* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79233. {
  79234. drmp3_bool32 result;
  79235. FILE* pFile;
  79236. if (drmp3_fopen(&pFile, pFilePath, "rb") != DRMP3_SUCCESS) {
  79237. return DRMP3_FALSE;
  79238. }
  79239. result = drmp3_init(pMP3, drmp3__on_read_stdio, drmp3__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  79240. if (result != DRMP3_TRUE) {
  79241. fclose(pFile);
  79242. return result;
  79243. }
  79244. return DRMP3_TRUE;
  79245. }
  79246. DRMP3_API drmp3_bool32 drmp3_init_file_w(drmp3* pMP3, const wchar_t* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79247. {
  79248. drmp3_bool32 result;
  79249. FILE* pFile;
  79250. if (drmp3_wfopen(&pFile, pFilePath, L"rb", pAllocationCallbacks) != DRMP3_SUCCESS) {
  79251. return DRMP3_FALSE;
  79252. }
  79253. result = drmp3_init(pMP3, drmp3__on_read_stdio, drmp3__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  79254. if (result != DRMP3_TRUE) {
  79255. fclose(pFile);
  79256. return result;
  79257. }
  79258. return DRMP3_TRUE;
  79259. }
  79260. #endif
  79261. DRMP3_API void drmp3_uninit(drmp3* pMP3)
  79262. {
  79263. if (pMP3 == NULL) {
  79264. return;
  79265. }
  79266. #ifndef DR_MP3_NO_STDIO
  79267. if (pMP3->onRead == drmp3__on_read_stdio) {
  79268. FILE* pFile = (FILE*)pMP3->pUserData;
  79269. if (pFile != NULL) {
  79270. fclose(pFile);
  79271. pMP3->pUserData = NULL;
  79272. }
  79273. }
  79274. #endif
  79275. drmp3__free_from_callbacks(pMP3->pData, &pMP3->allocationCallbacks);
  79276. }
  79277. #if defined(DR_MP3_FLOAT_OUTPUT)
  79278. static void drmp3_f32_to_s16(drmp3_int16* dst, const float* src, drmp3_uint64 sampleCount)
  79279. {
  79280. drmp3_uint64 i;
  79281. drmp3_uint64 i4;
  79282. drmp3_uint64 sampleCount4;
  79283. i = 0;
  79284. sampleCount4 = sampleCount >> 2;
  79285. for (i4 = 0; i4 < sampleCount4; i4 += 1) {
  79286. float x0 = src[i+0];
  79287. float x1 = src[i+1];
  79288. float x2 = src[i+2];
  79289. float x3 = src[i+3];
  79290. x0 = ((x0 < -1) ? -1 : ((x0 > 1) ? 1 : x0));
  79291. x1 = ((x1 < -1) ? -1 : ((x1 > 1) ? 1 : x1));
  79292. x2 = ((x2 < -1) ? -1 : ((x2 > 1) ? 1 : x2));
  79293. x3 = ((x3 < -1) ? -1 : ((x3 > 1) ? 1 : x3));
  79294. x0 = x0 * 32767.0f;
  79295. x1 = x1 * 32767.0f;
  79296. x2 = x2 * 32767.0f;
  79297. x3 = x3 * 32767.0f;
  79298. dst[i+0] = (drmp3_int16)x0;
  79299. dst[i+1] = (drmp3_int16)x1;
  79300. dst[i+2] = (drmp3_int16)x2;
  79301. dst[i+3] = (drmp3_int16)x3;
  79302. i += 4;
  79303. }
  79304. for (; i < sampleCount; i += 1) {
  79305. float x = src[i];
  79306. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  79307. x = x * 32767.0f;
  79308. dst[i] = (drmp3_int16)x;
  79309. }
  79310. }
  79311. #endif
  79312. #if !defined(DR_MP3_FLOAT_OUTPUT)
  79313. static void drmp3_s16_to_f32(float* dst, const drmp3_int16* src, drmp3_uint64 sampleCount)
  79314. {
  79315. drmp3_uint64 i;
  79316. for (i = 0; i < sampleCount; i += 1) {
  79317. float x = (float)src[i];
  79318. x = x * 0.000030517578125f;
  79319. dst[i] = x;
  79320. }
  79321. }
  79322. #endif
  79323. static drmp3_uint64 drmp3_read_pcm_frames_raw(drmp3* pMP3, drmp3_uint64 framesToRead, void* pBufferOut)
  79324. {
  79325. drmp3_uint64 totalFramesRead = 0;
  79326. DRMP3_ASSERT(pMP3 != NULL);
  79327. DRMP3_ASSERT(pMP3->onRead != NULL);
  79328. while (framesToRead > 0) {
  79329. drmp3_uint32 framesToConsume = (drmp3_uint32)DRMP3_MIN(pMP3->pcmFramesRemainingInMP3Frame, framesToRead);
  79330. if (pBufferOut != NULL) {
  79331. #if defined(DR_MP3_FLOAT_OUTPUT)
  79332. float* pFramesOutF32 = (float*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalFramesRead * pMP3->channels);
  79333. float* pFramesInF32 = (float*)DRMP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(float) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels);
  79334. DRMP3_COPY_MEMORY(pFramesOutF32, pFramesInF32, sizeof(float) * framesToConsume * pMP3->channels);
  79335. #else
  79336. drmp3_int16* pFramesOutS16 = (drmp3_int16*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(drmp3_int16) * totalFramesRead * pMP3->channels);
  79337. drmp3_int16* pFramesInS16 = (drmp3_int16*)DRMP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(drmp3_int16) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels);
  79338. DRMP3_COPY_MEMORY(pFramesOutS16, pFramesInS16, sizeof(drmp3_int16) * framesToConsume * pMP3->channels);
  79339. #endif
  79340. }
  79341. pMP3->currentPCMFrame += framesToConsume;
  79342. pMP3->pcmFramesConsumedInMP3Frame += framesToConsume;
  79343. pMP3->pcmFramesRemainingInMP3Frame -= framesToConsume;
  79344. totalFramesRead += framesToConsume;
  79345. framesToRead -= framesToConsume;
  79346. if (framesToRead == 0) {
  79347. break;
  79348. }
  79349. DRMP3_ASSERT(pMP3->pcmFramesRemainingInMP3Frame == 0);
  79350. if (drmp3_decode_next_frame(pMP3) == 0) {
  79351. break;
  79352. }
  79353. }
  79354. return totalFramesRead;
  79355. }
  79356. DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, float* pBufferOut)
  79357. {
  79358. if (pMP3 == NULL || pMP3->onRead == NULL) {
  79359. return 0;
  79360. }
  79361. #if defined(DR_MP3_FLOAT_OUTPUT)
  79362. return drmp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut);
  79363. #else
  79364. {
  79365. drmp3_int16 pTempS16[8192];
  79366. drmp3_uint64 totalPCMFramesRead = 0;
  79367. while (totalPCMFramesRead < framesToRead) {
  79368. drmp3_uint64 framesJustRead;
  79369. drmp3_uint64 framesRemaining = framesToRead - totalPCMFramesRead;
  79370. drmp3_uint64 framesToReadNow = DRMP3_COUNTOF(pTempS16) / pMP3->channels;
  79371. if (framesToReadNow > framesRemaining) {
  79372. framesToReadNow = framesRemaining;
  79373. }
  79374. framesJustRead = drmp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempS16);
  79375. if (framesJustRead == 0) {
  79376. break;
  79377. }
  79378. drmp3_s16_to_f32((float*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalPCMFramesRead * pMP3->channels), pTempS16, framesJustRead * pMP3->channels);
  79379. totalPCMFramesRead += framesJustRead;
  79380. }
  79381. return totalPCMFramesRead;
  79382. }
  79383. #endif
  79384. }
  79385. DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_s16(drmp3* pMP3, drmp3_uint64 framesToRead, drmp3_int16* pBufferOut)
  79386. {
  79387. if (pMP3 == NULL || pMP3->onRead == NULL) {
  79388. return 0;
  79389. }
  79390. #if !defined(DR_MP3_FLOAT_OUTPUT)
  79391. return drmp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut);
  79392. #else
  79393. {
  79394. float pTempF32[4096];
  79395. drmp3_uint64 totalPCMFramesRead = 0;
  79396. while (totalPCMFramesRead < framesToRead) {
  79397. drmp3_uint64 framesJustRead;
  79398. drmp3_uint64 framesRemaining = framesToRead - totalPCMFramesRead;
  79399. drmp3_uint64 framesToReadNow = DRMP3_COUNTOF(pTempF32) / pMP3->channels;
  79400. if (framesToReadNow > framesRemaining) {
  79401. framesToReadNow = framesRemaining;
  79402. }
  79403. framesJustRead = drmp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempF32);
  79404. if (framesJustRead == 0) {
  79405. break;
  79406. }
  79407. drmp3_f32_to_s16((drmp3_int16*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(drmp3_int16) * totalPCMFramesRead * pMP3->channels), pTempF32, framesJustRead * pMP3->channels);
  79408. totalPCMFramesRead += framesJustRead;
  79409. }
  79410. return totalPCMFramesRead;
  79411. }
  79412. #endif
  79413. }
  79414. static void drmp3_reset(drmp3* pMP3)
  79415. {
  79416. DRMP3_ASSERT(pMP3 != NULL);
  79417. pMP3->pcmFramesConsumedInMP3Frame = 0;
  79418. pMP3->pcmFramesRemainingInMP3Frame = 0;
  79419. pMP3->currentPCMFrame = 0;
  79420. pMP3->dataSize = 0;
  79421. pMP3->atEnd = DRMP3_FALSE;
  79422. drmp3dec_init(&pMP3->decoder);
  79423. }
  79424. static drmp3_bool32 drmp3_seek_to_start_of_stream(drmp3* pMP3)
  79425. {
  79426. DRMP3_ASSERT(pMP3 != NULL);
  79427. DRMP3_ASSERT(pMP3->onSeek != NULL);
  79428. if (!drmp3__on_seek(pMP3, 0, drmp3_seek_origin_start)) {
  79429. return DRMP3_FALSE;
  79430. }
  79431. drmp3_reset(pMP3);
  79432. return DRMP3_TRUE;
  79433. }
  79434. static drmp3_bool32 drmp3_seek_forward_by_pcm_frames__brute_force(drmp3* pMP3, drmp3_uint64 frameOffset)
  79435. {
  79436. drmp3_uint64 framesRead;
  79437. #if defined(DR_MP3_FLOAT_OUTPUT)
  79438. framesRead = drmp3_read_pcm_frames_f32(pMP3, frameOffset, NULL);
  79439. #else
  79440. framesRead = drmp3_read_pcm_frames_s16(pMP3, frameOffset, NULL);
  79441. #endif
  79442. if (framesRead != frameOffset) {
  79443. return DRMP3_FALSE;
  79444. }
  79445. return DRMP3_TRUE;
  79446. }
  79447. static drmp3_bool32 drmp3_seek_to_pcm_frame__brute_force(drmp3* pMP3, drmp3_uint64 frameIndex)
  79448. {
  79449. DRMP3_ASSERT(pMP3 != NULL);
  79450. if (frameIndex == pMP3->currentPCMFrame) {
  79451. return DRMP3_TRUE;
  79452. }
  79453. if (frameIndex < pMP3->currentPCMFrame) {
  79454. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  79455. return DRMP3_FALSE;
  79456. }
  79457. }
  79458. DRMP3_ASSERT(frameIndex >= pMP3->currentPCMFrame);
  79459. return drmp3_seek_forward_by_pcm_frames__brute_force(pMP3, (frameIndex - pMP3->currentPCMFrame));
  79460. }
  79461. static drmp3_bool32 drmp3_find_closest_seek_point(drmp3* pMP3, drmp3_uint64 frameIndex, drmp3_uint32* pSeekPointIndex)
  79462. {
  79463. drmp3_uint32 iSeekPoint;
  79464. DRMP3_ASSERT(pSeekPointIndex != NULL);
  79465. *pSeekPointIndex = 0;
  79466. if (frameIndex < pMP3->pSeekPoints[0].pcmFrameIndex) {
  79467. return DRMP3_FALSE;
  79468. }
  79469. for (iSeekPoint = 0; iSeekPoint < pMP3->seekPointCount; ++iSeekPoint) {
  79470. if (pMP3->pSeekPoints[iSeekPoint].pcmFrameIndex > frameIndex) {
  79471. break;
  79472. }
  79473. *pSeekPointIndex = iSeekPoint;
  79474. }
  79475. return DRMP3_TRUE;
  79476. }
  79477. static drmp3_bool32 drmp3_seek_to_pcm_frame__seek_table(drmp3* pMP3, drmp3_uint64 frameIndex)
  79478. {
  79479. drmp3_seek_point seekPoint;
  79480. drmp3_uint32 priorSeekPointIndex;
  79481. drmp3_uint16 iMP3Frame;
  79482. drmp3_uint64 leftoverFrames;
  79483. DRMP3_ASSERT(pMP3 != NULL);
  79484. DRMP3_ASSERT(pMP3->pSeekPoints != NULL);
  79485. DRMP3_ASSERT(pMP3->seekPointCount > 0);
  79486. if (drmp3_find_closest_seek_point(pMP3, frameIndex, &priorSeekPointIndex)) {
  79487. seekPoint = pMP3->pSeekPoints[priorSeekPointIndex];
  79488. } else {
  79489. seekPoint.seekPosInBytes = 0;
  79490. seekPoint.pcmFrameIndex = 0;
  79491. seekPoint.mp3FramesToDiscard = 0;
  79492. seekPoint.pcmFramesToDiscard = 0;
  79493. }
  79494. if (!drmp3__on_seek_64(pMP3, seekPoint.seekPosInBytes, drmp3_seek_origin_start)) {
  79495. return DRMP3_FALSE;
  79496. }
  79497. drmp3_reset(pMP3);
  79498. for (iMP3Frame = 0; iMP3Frame < seekPoint.mp3FramesToDiscard; ++iMP3Frame) {
  79499. drmp3_uint32 pcmFramesRead;
  79500. drmp3d_sample_t* pPCMFrames;
  79501. pPCMFrames = NULL;
  79502. if (iMP3Frame == seekPoint.mp3FramesToDiscard-1) {
  79503. pPCMFrames = (drmp3d_sample_t*)pMP3->pcmFrames;
  79504. }
  79505. pcmFramesRead = drmp3_decode_next_frame_ex(pMP3, pPCMFrames);
  79506. if (pcmFramesRead == 0) {
  79507. return DRMP3_FALSE;
  79508. }
  79509. }
  79510. pMP3->currentPCMFrame = seekPoint.pcmFrameIndex - seekPoint.pcmFramesToDiscard;
  79511. leftoverFrames = frameIndex - pMP3->currentPCMFrame;
  79512. return drmp3_seek_forward_by_pcm_frames__brute_force(pMP3, leftoverFrames);
  79513. }
  79514. DRMP3_API drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex)
  79515. {
  79516. if (pMP3 == NULL || pMP3->onSeek == NULL) {
  79517. return DRMP3_FALSE;
  79518. }
  79519. if (frameIndex == 0) {
  79520. return drmp3_seek_to_start_of_stream(pMP3);
  79521. }
  79522. if (pMP3->pSeekPoints != NULL && pMP3->seekPointCount > 0) {
  79523. return drmp3_seek_to_pcm_frame__seek_table(pMP3, frameIndex);
  79524. } else {
  79525. return drmp3_seek_to_pcm_frame__brute_force(pMP3, frameIndex);
  79526. }
  79527. }
  79528. DRMP3_API drmp3_bool32 drmp3_get_mp3_and_pcm_frame_count(drmp3* pMP3, drmp3_uint64* pMP3FrameCount, drmp3_uint64* pPCMFrameCount)
  79529. {
  79530. drmp3_uint64 currentPCMFrame;
  79531. drmp3_uint64 totalPCMFrameCount;
  79532. drmp3_uint64 totalMP3FrameCount;
  79533. if (pMP3 == NULL) {
  79534. return DRMP3_FALSE;
  79535. }
  79536. if (pMP3->onSeek == NULL) {
  79537. return DRMP3_FALSE;
  79538. }
  79539. currentPCMFrame = pMP3->currentPCMFrame;
  79540. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  79541. return DRMP3_FALSE;
  79542. }
  79543. totalPCMFrameCount = 0;
  79544. totalMP3FrameCount = 0;
  79545. for (;;) {
  79546. drmp3_uint32 pcmFramesInCurrentMP3Frame;
  79547. pcmFramesInCurrentMP3Frame = drmp3_decode_next_frame_ex(pMP3, NULL);
  79548. if (pcmFramesInCurrentMP3Frame == 0) {
  79549. break;
  79550. }
  79551. totalPCMFrameCount += pcmFramesInCurrentMP3Frame;
  79552. totalMP3FrameCount += 1;
  79553. }
  79554. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  79555. return DRMP3_FALSE;
  79556. }
  79557. if (!drmp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) {
  79558. return DRMP3_FALSE;
  79559. }
  79560. if (pMP3FrameCount != NULL) {
  79561. *pMP3FrameCount = totalMP3FrameCount;
  79562. }
  79563. if (pPCMFrameCount != NULL) {
  79564. *pPCMFrameCount = totalPCMFrameCount;
  79565. }
  79566. return DRMP3_TRUE;
  79567. }
  79568. DRMP3_API drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3)
  79569. {
  79570. drmp3_uint64 totalPCMFrameCount;
  79571. if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, NULL, &totalPCMFrameCount)) {
  79572. return 0;
  79573. }
  79574. return totalPCMFrameCount;
  79575. }
  79576. DRMP3_API drmp3_uint64 drmp3_get_mp3_frame_count(drmp3* pMP3)
  79577. {
  79578. drmp3_uint64 totalMP3FrameCount;
  79579. if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, NULL)) {
  79580. return 0;
  79581. }
  79582. return totalMP3FrameCount;
  79583. }
  79584. static void drmp3__accumulate_running_pcm_frame_count(drmp3* pMP3, drmp3_uint32 pcmFrameCountIn, drmp3_uint64* pRunningPCMFrameCount, float* pRunningPCMFrameCountFractionalPart)
  79585. {
  79586. float srcRatio;
  79587. float pcmFrameCountOutF;
  79588. drmp3_uint32 pcmFrameCountOut;
  79589. srcRatio = (float)pMP3->mp3FrameSampleRate / (float)pMP3->sampleRate;
  79590. DRMP3_ASSERT(srcRatio > 0);
  79591. pcmFrameCountOutF = *pRunningPCMFrameCountFractionalPart + (pcmFrameCountIn / srcRatio);
  79592. pcmFrameCountOut = (drmp3_uint32)pcmFrameCountOutF;
  79593. *pRunningPCMFrameCountFractionalPart = pcmFrameCountOutF - pcmFrameCountOut;
  79594. *pRunningPCMFrameCount += pcmFrameCountOut;
  79595. }
  79596. typedef struct
  79597. {
  79598. drmp3_uint64 bytePos;
  79599. drmp3_uint64 pcmFrameIndex;
  79600. } drmp3__seeking_mp3_frame_info;
  79601. DRMP3_API drmp3_bool32 drmp3_calculate_seek_points(drmp3* pMP3, drmp3_uint32* pSeekPointCount, drmp3_seek_point* pSeekPoints)
  79602. {
  79603. drmp3_uint32 seekPointCount;
  79604. drmp3_uint64 currentPCMFrame;
  79605. drmp3_uint64 totalMP3FrameCount;
  79606. drmp3_uint64 totalPCMFrameCount;
  79607. if (pMP3 == NULL || pSeekPointCount == NULL || pSeekPoints == NULL) {
  79608. return DRMP3_FALSE;
  79609. }
  79610. seekPointCount = *pSeekPointCount;
  79611. if (seekPointCount == 0) {
  79612. return DRMP3_FALSE;
  79613. }
  79614. currentPCMFrame = pMP3->currentPCMFrame;
  79615. if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, &totalPCMFrameCount)) {
  79616. return DRMP3_FALSE;
  79617. }
  79618. if (totalMP3FrameCount < DRMP3_SEEK_LEADING_MP3_FRAMES+1) {
  79619. seekPointCount = 1;
  79620. pSeekPoints[0].seekPosInBytes = 0;
  79621. pSeekPoints[0].pcmFrameIndex = 0;
  79622. pSeekPoints[0].mp3FramesToDiscard = 0;
  79623. pSeekPoints[0].pcmFramesToDiscard = 0;
  79624. } else {
  79625. drmp3_uint64 pcmFramesBetweenSeekPoints;
  79626. drmp3__seeking_mp3_frame_info mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES+1];
  79627. drmp3_uint64 runningPCMFrameCount = 0;
  79628. float runningPCMFrameCountFractionalPart = 0;
  79629. drmp3_uint64 nextTargetPCMFrame;
  79630. drmp3_uint32 iMP3Frame;
  79631. drmp3_uint32 iSeekPoint;
  79632. if (seekPointCount > totalMP3FrameCount-1) {
  79633. seekPointCount = (drmp3_uint32)totalMP3FrameCount-1;
  79634. }
  79635. pcmFramesBetweenSeekPoints = totalPCMFrameCount / (seekPointCount+1);
  79636. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  79637. return DRMP3_FALSE;
  79638. }
  79639. for (iMP3Frame = 0; iMP3Frame < DRMP3_SEEK_LEADING_MP3_FRAMES+1; ++iMP3Frame) {
  79640. drmp3_uint32 pcmFramesInCurrentMP3FrameIn;
  79641. DRMP3_ASSERT(pMP3->streamCursor >= pMP3->dataSize);
  79642. mp3FrameInfo[iMP3Frame].bytePos = pMP3->streamCursor - pMP3->dataSize;
  79643. mp3FrameInfo[iMP3Frame].pcmFrameIndex = runningPCMFrameCount;
  79644. pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL);
  79645. if (pcmFramesInCurrentMP3FrameIn == 0) {
  79646. return DRMP3_FALSE;
  79647. }
  79648. drmp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart);
  79649. }
  79650. nextTargetPCMFrame = 0;
  79651. for (iSeekPoint = 0; iSeekPoint < seekPointCount; ++iSeekPoint) {
  79652. nextTargetPCMFrame += pcmFramesBetweenSeekPoints;
  79653. for (;;) {
  79654. if (nextTargetPCMFrame < runningPCMFrameCount) {
  79655. pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos;
  79656. pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame;
  79657. pSeekPoints[iSeekPoint].mp3FramesToDiscard = DRMP3_SEEK_LEADING_MP3_FRAMES;
  79658. pSeekPoints[iSeekPoint].pcmFramesToDiscard = (drmp3_uint16)(nextTargetPCMFrame - mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex);
  79659. break;
  79660. } else {
  79661. size_t i;
  79662. drmp3_uint32 pcmFramesInCurrentMP3FrameIn;
  79663. for (i = 0; i < DRMP3_COUNTOF(mp3FrameInfo)-1; ++i) {
  79664. mp3FrameInfo[i] = mp3FrameInfo[i+1];
  79665. }
  79666. mp3FrameInfo[DRMP3_COUNTOF(mp3FrameInfo)-1].bytePos = pMP3->streamCursor - pMP3->dataSize;
  79667. mp3FrameInfo[DRMP3_COUNTOF(mp3FrameInfo)-1].pcmFrameIndex = runningPCMFrameCount;
  79668. pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL);
  79669. if (pcmFramesInCurrentMP3FrameIn == 0) {
  79670. pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos;
  79671. pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame;
  79672. pSeekPoints[iSeekPoint].mp3FramesToDiscard = DRMP3_SEEK_LEADING_MP3_FRAMES;
  79673. pSeekPoints[iSeekPoint].pcmFramesToDiscard = (drmp3_uint16)(nextTargetPCMFrame - mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex);
  79674. break;
  79675. }
  79676. drmp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart);
  79677. }
  79678. }
  79679. }
  79680. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  79681. return DRMP3_FALSE;
  79682. }
  79683. if (!drmp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) {
  79684. return DRMP3_FALSE;
  79685. }
  79686. }
  79687. *pSeekPointCount = seekPointCount;
  79688. return DRMP3_TRUE;
  79689. }
  79690. DRMP3_API drmp3_bool32 drmp3_bind_seek_table(drmp3* pMP3, drmp3_uint32 seekPointCount, drmp3_seek_point* pSeekPoints)
  79691. {
  79692. if (pMP3 == NULL) {
  79693. return DRMP3_FALSE;
  79694. }
  79695. if (seekPointCount == 0 || pSeekPoints == NULL) {
  79696. pMP3->seekPointCount = 0;
  79697. pMP3->pSeekPoints = NULL;
  79698. } else {
  79699. pMP3->seekPointCount = seekPointCount;
  79700. pMP3->pSeekPoints = pSeekPoints;
  79701. }
  79702. return DRMP3_TRUE;
  79703. }
  79704. static float* drmp3__full_read_and_close_f32(drmp3* pMP3, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount)
  79705. {
  79706. drmp3_uint64 totalFramesRead = 0;
  79707. drmp3_uint64 framesCapacity = 0;
  79708. float* pFrames = NULL;
  79709. float temp[4096];
  79710. DRMP3_ASSERT(pMP3 != NULL);
  79711. for (;;) {
  79712. drmp3_uint64 framesToReadRightNow = DRMP3_COUNTOF(temp) / pMP3->channels;
  79713. drmp3_uint64 framesJustRead = drmp3_read_pcm_frames_f32(pMP3, framesToReadRightNow, temp);
  79714. if (framesJustRead == 0) {
  79715. break;
  79716. }
  79717. if (framesCapacity < totalFramesRead + framesJustRead) {
  79718. drmp3_uint64 oldFramesBufferSize;
  79719. drmp3_uint64 newFramesBufferSize;
  79720. drmp3_uint64 newFramesCap;
  79721. float* pNewFrames;
  79722. newFramesCap = framesCapacity * 2;
  79723. if (newFramesCap < totalFramesRead + framesJustRead) {
  79724. newFramesCap = totalFramesRead + framesJustRead;
  79725. }
  79726. oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(float);
  79727. newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(float);
  79728. if (newFramesBufferSize > (drmp3_uint64)DRMP3_SIZE_MAX) {
  79729. break;
  79730. }
  79731. pNewFrames = (float*)drmp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks);
  79732. if (pNewFrames == NULL) {
  79733. drmp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks);
  79734. break;
  79735. }
  79736. pFrames = pNewFrames;
  79737. framesCapacity = newFramesCap;
  79738. }
  79739. DRMP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(float)));
  79740. totalFramesRead += framesJustRead;
  79741. if (framesJustRead != framesToReadRightNow) {
  79742. break;
  79743. }
  79744. }
  79745. if (pConfig != NULL) {
  79746. pConfig->channels = pMP3->channels;
  79747. pConfig->sampleRate = pMP3->sampleRate;
  79748. }
  79749. drmp3_uninit(pMP3);
  79750. if (pTotalFrameCount) {
  79751. *pTotalFrameCount = totalFramesRead;
  79752. }
  79753. return pFrames;
  79754. }
  79755. static drmp3_int16* drmp3__full_read_and_close_s16(drmp3* pMP3, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount)
  79756. {
  79757. drmp3_uint64 totalFramesRead = 0;
  79758. drmp3_uint64 framesCapacity = 0;
  79759. drmp3_int16* pFrames = NULL;
  79760. drmp3_int16 temp[4096];
  79761. DRMP3_ASSERT(pMP3 != NULL);
  79762. for (;;) {
  79763. drmp3_uint64 framesToReadRightNow = DRMP3_COUNTOF(temp) / pMP3->channels;
  79764. drmp3_uint64 framesJustRead = drmp3_read_pcm_frames_s16(pMP3, framesToReadRightNow, temp);
  79765. if (framesJustRead == 0) {
  79766. break;
  79767. }
  79768. if (framesCapacity < totalFramesRead + framesJustRead) {
  79769. drmp3_uint64 newFramesBufferSize;
  79770. drmp3_uint64 oldFramesBufferSize;
  79771. drmp3_uint64 newFramesCap;
  79772. drmp3_int16* pNewFrames;
  79773. newFramesCap = framesCapacity * 2;
  79774. if (newFramesCap < totalFramesRead + framesJustRead) {
  79775. newFramesCap = totalFramesRead + framesJustRead;
  79776. }
  79777. oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(drmp3_int16);
  79778. newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(drmp3_int16);
  79779. if (newFramesBufferSize > (drmp3_uint64)DRMP3_SIZE_MAX) {
  79780. break;
  79781. }
  79782. pNewFrames = (drmp3_int16*)drmp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks);
  79783. if (pNewFrames == NULL) {
  79784. drmp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks);
  79785. break;
  79786. }
  79787. pFrames = pNewFrames;
  79788. framesCapacity = newFramesCap;
  79789. }
  79790. DRMP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(drmp3_int16)));
  79791. totalFramesRead += framesJustRead;
  79792. if (framesJustRead != framesToReadRightNow) {
  79793. break;
  79794. }
  79795. }
  79796. if (pConfig != NULL) {
  79797. pConfig->channels = pMP3->channels;
  79798. pConfig->sampleRate = pMP3->sampleRate;
  79799. }
  79800. drmp3_uninit(pMP3);
  79801. if (pTotalFrameCount) {
  79802. *pTotalFrameCount = totalFramesRead;
  79803. }
  79804. return pFrames;
  79805. }
  79806. DRMP3_API float* drmp3_open_and_read_pcm_frames_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79807. {
  79808. drmp3 mp3;
  79809. if (!drmp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  79810. return NULL;
  79811. }
  79812. return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
  79813. }
  79814. DRMP3_API drmp3_int16* drmp3_open_and_read_pcm_frames_s16(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79815. {
  79816. drmp3 mp3;
  79817. if (!drmp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  79818. return NULL;
  79819. }
  79820. return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
  79821. }
  79822. DRMP3_API float* drmp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79823. {
  79824. drmp3 mp3;
  79825. if (!drmp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) {
  79826. return NULL;
  79827. }
  79828. return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
  79829. }
  79830. DRMP3_API drmp3_int16* drmp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79831. {
  79832. drmp3 mp3;
  79833. if (!drmp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) {
  79834. return NULL;
  79835. }
  79836. return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
  79837. }
  79838. #ifndef DR_MP3_NO_STDIO
  79839. DRMP3_API float* drmp3_open_file_and_read_pcm_frames_f32(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79840. {
  79841. drmp3 mp3;
  79842. if (!drmp3_init_file(&mp3, filePath, pAllocationCallbacks)) {
  79843. return NULL;
  79844. }
  79845. return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
  79846. }
  79847. DRMP3_API drmp3_int16* drmp3_open_file_and_read_pcm_frames_s16(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79848. {
  79849. drmp3 mp3;
  79850. if (!drmp3_init_file(&mp3, filePath, pAllocationCallbacks)) {
  79851. return NULL;
  79852. }
  79853. return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
  79854. }
  79855. #endif
  79856. DRMP3_API void* drmp3_malloc(size_t sz, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79857. {
  79858. if (pAllocationCallbacks != NULL) {
  79859. return drmp3__malloc_from_callbacks(sz, pAllocationCallbacks);
  79860. } else {
  79861. return drmp3__malloc_default(sz, NULL);
  79862. }
  79863. }
  79864. DRMP3_API void drmp3_free(void* p, const drmp3_allocation_callbacks* pAllocationCallbacks)
  79865. {
  79866. if (pAllocationCallbacks != NULL) {
  79867. drmp3__free_from_callbacks(p, pAllocationCallbacks);
  79868. } else {
  79869. drmp3__free_default(p, NULL);
  79870. }
  79871. }
  79872. #endif
  79873. /* dr_mp3_c end */
  79874. #endif /* DRMP3_IMPLEMENTATION */
  79875. #endif /* MA_NO_MP3 */
  79876. /* End globally disabled warnings. */
  79877. #if defined(_MSC_VER)
  79878. #pragma warning(pop)
  79879. #endif
  79880. #endif /* miniaudio_c */
  79881. #endif /* MINIAUDIO_IMPLEMENTATION */
  79882. /*
  79883. This software is available as a choice of the following licenses. Choose
  79884. whichever you prefer.
  79885. ===============================================================================
  79886. ALTERNATIVE 1 - Public Domain (www.unlicense.org)
  79887. ===============================================================================
  79888. This is free and unencumbered software released into the public domain.
  79889. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  79890. software, either in source code form or as a compiled binary, for any purpose,
  79891. commercial or non-commercial, and by any means.
  79892. In jurisdictions that recognize copyright laws, the author or authors of this
  79893. software dedicate any and all copyright interest in the software to the public
  79894. domain. We make this dedication for the benefit of the public at large and to
  79895. the detriment of our heirs and successors. We intend this dedication to be an
  79896. overt act of relinquishment in perpetuity of all present and future rights to
  79897. this software under copyright law.
  79898. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  79899. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  79900. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  79901. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  79902. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  79903. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  79904. For more information, please refer to <http://unlicense.org/>
  79905. ===============================================================================
  79906. ALTERNATIVE 2 - MIT No Attribution
  79907. ===============================================================================
  79908. Copyright 2023 David Reid
  79909. Permission is hereby granted, free of charge, to any person obtaining a copy of
  79910. this software and associated documentation files (the "Software"), to deal in
  79911. the Software without restriction, including without limitation the rights to
  79912. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  79913. of the Software, and to permit persons to whom the Software is furnished to do
  79914. so.
  79915. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  79916. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  79917. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  79918. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  79919. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  79920. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  79921. SOFTWARE.
  79922. */